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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1372  ! raeburn     4: # $Id: lonnet.pm,v 1.1371 2018/03/30 21:30:00 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.1361    raeburn   710:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1212    raeburn   711:     }
1.1245    raeburn   712: 
1.916     albertel  713:     return $handle;
                    714: }
                    715: 
1.830     albertel  716: sub timed_flock {
                    717:     my ($file,$lock_type) = @_;
                    718:     my $failed=0;
                    719:     eval {
                    720: 	local $SIG{__DIE__}='DEFAULT';
                    721: 	local $SIG{ALRM}=sub {
                    722: 	    $failed=1;
                    723: 	    die("failed lock");
                    724: 	};
                    725: 	alarm(13);
                    726: 	flock($file,$lock_type);
                    727: 	alarm(0);
                    728:     };
                    729:     if ($failed) {
                    730: 	return undef;
                    731:     } else {
                    732: 	return 1;
                    733:     }
                    734: }
                    735: 
1.5       www       736: # ---------------------------------------------------------- Append Environment
                    737: 
                    738: sub appenv {
1.949     raeburn   739:     my ($newenv,$roles) = @_;
                    740:     if (ref($newenv) eq 'HASH') {
                    741:         foreach my $key (keys(%{$newenv})) {
                    742:             my $refused = 0;
                    743: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    744:                 $refused = 1;
                    745:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   746:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   747:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    748:                         $refused = 0;
                    749:                     }
                    750:                 }
                    751:             }
                    752:             if ($refused) {
                    753:                 &logthis("<font color=\"blue\">WARNING: ".
                    754:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    755:                          .'</font>');
                    756: 	        delete($newenv->{$key});
                    757:             } else {
                    758:                 $env{$key}=$newenv->{$key};
                    759:             }
                    760:         }
                    761:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    762:         if ($opened
                    763: 	    && &timed_flock($env_file,LOCK_EX)
                    764: 	    &&
                    765: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    766: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    767: 	    while (my ($key,$value) = each(%{$newenv})) {
                    768: 	        $disk_env{$key} = $value;
                    769: 	    }
                    770: 	    untie(%disk_env);
1.35      www       771:         }
1.191     harris41  772:     }
1.56      www       773:     return 'ok';
                    774: }
                    775: # ----------------------------------------------------- Delete from Environment
                    776: 
                    777: sub delenv {
1.1104    raeburn   778:     my ($delthis,$regexp,$roles) = @_;
                    779:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    780:         my $refused = 1;
                    781:         if (ref($roles) eq 'ARRAY') {
                    782:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    783:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    784:                 $refused = 0;
                    785:             }
                    786:         }
                    787:         if ($refused) {
                    788:             &logthis("<font color=\"blue\">WARNING: ".
                    789:                      "Attempt to delete from environment ".$delthis);
                    790:             return 'error';
                    791:         }
1.56      www       792:     }
1.917     albertel  793:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    794:     if ($opened
1.915     albertel  795: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  796: 	&&
                    797: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    798: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  799: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   800: 	    if ($regexp) {
                    801:                 if ($key=~/^$delthis/) {
                    802:                     delete($env{$key});
                    803:                     delete($disk_env{$key});
                    804:                 } 
                    805:             } else {
                    806:                 if ($key=~/^\Q$delthis\E/) {
                    807: 		    delete($env{$key});
                    808: 		    delete($disk_env{$key});
                    809: 	        }
                    810:             }
1.448     albertel  811: 	}
1.783     albertel  812: 	untie(%disk_env);
1.5       www       813:     }
                    814:     return 'ok';
1.369     albertel  815: }
                    816: 
1.790     albertel  817: sub get_env_multiple {
                    818:     my ($name) = @_;
                    819:     my @values;
                    820:     if (defined($env{$name})) {
                    821:         # exists is it an array
                    822:         if (ref($env{$name})) {
                    823:             @values=@{ $env{$name} };
                    824:         } else {
                    825:             $values[0]=$env{$name};
                    826:         }
                    827:     }
                    828:     return(@values);
                    829: }
                    830: 
1.958     www       831: # ------------------------------------------------------------------- Locking
                    832: 
                    833: sub set_lock {
                    834:     my ($text)=@_;
                    835:     $locknum++;
                    836:     my $id=$$.'-'.$locknum;
                    837:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    838:              'session.lock.'.$id => $text});
                    839:     return $id;
                    840: }
                    841: 
                    842: sub get_locks {
                    843:     my $num=0;
                    844:     my %texts=();
                    845:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    846:        if ($lock=~/\w/) {
                    847:           $num++;
                    848:           $texts{$lock}=$env{'session.lock.'.$lock};
                    849:        }
                    850:    }
                    851:    return ($num,%texts);
                    852: }
                    853: 
                    854: sub remove_lock {
                    855:     my ($id)=@_;
                    856:     my $newlocks='';
                    857:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    858:        if (($lock=~/\w/) && ($lock ne $id)) {
                    859:           $newlocks.=','.$lock;
                    860:        }
                    861:     }
                    862:     &appenv({'session.locks' => $newlocks});
                    863:     &delenv('session.lock.'.$id);
                    864: }
                    865: 
                    866: sub remove_all_locks {
                    867:     my $activelocks=$env{'session.locks'};
                    868:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    869:        if ($lock=~/\w/) {
                    870:           &remove_lock($lock);
                    871:        }
                    872:     }
                    873: }
                    874: 
                    875: 
1.369     albertel  876: # ------------------------------------------ Find out current server userload
                    877: sub userload {
                    878:     my $numusers=0;
                    879:     {
                    880: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    881: 	my $filename;
                    882: 	my $curtime=time;
                    883: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  884: 	    next if ($filename eq '.' || $filename eq '..');
                    885: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  886: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  887: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  888: 	}
                    889: 	closedir(LONIDS);
                    890:     }
                    891:     my $userloadpercent=0;
                    892:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    893:     if ($maxuserload) {
1.371     albertel  894: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  895:     }
1.372     albertel  896:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  897:     return $userloadpercent;
1.283     www       898: }
                    899: 
1.1       albertel  900: # ------------------------------ Find server with least workload from spare.tab
1.11      www       901: 
1.1       albertel  902: sub spareserver {
1.1083    raeburn   903:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  904:     my $spare_server;
1.370     albertel  905:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  906:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    907:                                                      :  $userloadpercent;
1.1083    raeburn   908:     my ($uint_dom,$remotesessions);
                    909:     if (($udom ne '') && (&domain($udom) ne '')) {
                    910:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    911:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    912:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    913:         $remotesessions = $udomdefaults{'remotesessions'};
                    914:     }
1.1123    raeburn   915:     my $spareshash = &this_host_spares($udom);
                    916:     if (ref($spareshash) eq 'HASH') {
                    917:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    918:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   919:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    920:                                              $try_server));
1.1123    raeburn   921: 	        ($spare_server, $lowest_load) =
                    922: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    923:             }
1.1083    raeburn   924:         }
1.784     albertel  925: 
1.1123    raeburn   926:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    927: 
                    928:         if (!$found_server) {
                    929:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    930: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   931:                     next unless (&spare_can_host($udom,$uint_dom,
                    932:                                                  $remotesessions,$try_server));
1.1123    raeburn   933: 	            ($spare_server, $lowest_load) =
                    934: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    935:                 }
                    936: 	    }
                    937:         }
1.784     albertel  938:     }
                    939: 
                    940:     if (!$want_server_name) {
1.968     raeburn   941:         my $protocol = 'http';
                    942:         if ($protocol{$spare_server} eq 'https') {
                    943:             $protocol = $protocol{$spare_server};
                    944:         }
1.1001    raeburn   945:         if (defined($spare_server)) {
                    946:             my $hostname = &hostname($spare_server);
1.1083    raeburn   947:             if (defined($hostname)) {
1.1001    raeburn   948: 	        $spare_server = $protocol.'://'.$hostname;
                    949:             }
                    950:         }
1.784     albertel  951:     }
                    952:     return $spare_server;
                    953: }
                    954: 
                    955: sub compare_server_load {
1.1253    raeburn   956:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    957: 
                    958:     if ($required) {
                    959:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    960:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    961:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    962:         if (($major eq '' && $minor eq '') ||
                    963:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    964:             return ($spare_server,$lowest_load);
                    965:         }
                    966:     }
1.784     albertel  967: 
                    968:     my $loadans     = &reply('load',    $try_server);
                    969:     my $userloadans = &reply('userload',$try_server);
                    970: 
                    971:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   972: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  973:     }
                    974: 
                    975:     my $load;
                    976:     if ($loadans =~ /\d/) {
                    977: 	if ($userloadans =~ /\d/) {
                    978: 	    #both are numbers, pick the bigger one
                    979: 	    $load = ($loadans > $userloadans) ? $loadans 
                    980: 		                              : $userloadans;
1.411     albertel  981: 	} else {
1.784     albertel  982: 	    $load = $loadans;
1.411     albertel  983: 	}
1.784     albertel  984:     } else {
                    985: 	$load = $userloadans;
                    986:     }
                    987: 
                    988:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    989: 	$spare_server = $try_server;
                    990: 	$lowest_load  = $load;
1.370     albertel  991:     }
1.784     albertel  992:     return ($spare_server,$lowest_load);
1.202     matthew   993: }
1.914     albertel  994: 
                    995: # --------------------------- ask offload servers if user already has a session
                    996: sub find_existing_session {
                    997:     my ($udom,$uname) = @_;
1.1123    raeburn   998:     my $spareshash = &this_host_spares($udom);
                    999:     if (ref($spareshash) eq 'HASH') {
                   1000:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1001:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1002:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1003:             }
                   1004:         }
                   1005:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1006:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1007:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1008:             }
                   1009:         }
1.914     albertel 1010:     }
                   1011:     return;
                   1012: }
                   1013: 
                   1014: # -------------------------------- ask if server already has a session for user
                   1015: sub has_user_session {
                   1016:     my ($lonid,$udom,$uname) = @_;
                   1017:     my $result = &reply(join(':','userhassession',
                   1018: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1019:     return 1 if ($result eq 'ok');
                   1020: 
                   1021:     return 0;
                   1022: }
                   1023: 
1.1076    raeburn  1024: # --------- determine least loaded server in a user's domain which allows login
                   1025: 
                   1026: sub choose_server {
1.1259    raeburn  1027:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1028:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1029:     my %servers = &get_servers($udom);
1.1076    raeburn  1030:     my $lowest_load = 30000;
1.1259    raeburn  1031:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1032:     if ($skiploadbal) {
                   1033:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1034:         unless (defined($cached)) {
                   1035:             my $cachetime = 60*60*24;
                   1036:             my %domconfig =
                   1037:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1038:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1039:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1040:                                            $cachetime);
                   1041:             }
                   1042:         }
                   1043:     }
1.1076    raeburn  1044:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1045:         if ($skiploadbal) {
                   1046:             if (ref($balancers) eq 'HASH') {
                   1047:                 next if (exists($balancers->{$lonhost}));
                   1048:             }
                   1049:         }   
1.1115    raeburn  1050:         my $loginvia;
                   1051:         if ($checkloginvia) {
                   1052:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1053:             if ($loginvia) {
                   1054:                 my ($server,$path) = split(/:/,$loginvia);
                   1055:                 ($login_host, $lowest_load) =
1.1253    raeburn  1056:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1057:                 if ($login_host eq $server) {
                   1058:                     $portal_path = $path;
1.1151    raeburn  1059:                     $isredirect = 1;
1.1116    raeburn  1060:                 }
                   1061:             } else {
                   1062:                 ($login_host, $lowest_load) =
1.1253    raeburn  1063:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1064:                 if ($login_host eq $lonhost) {
                   1065:                     $portal_path = '';
1.1151    raeburn  1066:                     $isredirect = ''; 
1.1116    raeburn  1067:                 }
                   1068:             }
                   1069:         } else {
1.1076    raeburn  1070:             ($login_host, $lowest_load) =
1.1253    raeburn  1071:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1072:         }
                   1073:     }
                   1074:     if ($login_host ne '') {
1.1116    raeburn  1075:         $hostname = &hostname($login_host);
1.1076    raeburn  1076:     }
1.1331    raeburn  1077:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1078: }
                   1079: 
1.202     matthew  1080: # --------------------------------------------- Try to change a user's password
                   1081: 
                   1082: sub changepass {
1.799     raeburn  1083:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1084:     $currentpass = &escape($currentpass);
                   1085:     $newpass     = &escape($newpass);
1.1030    raeburn  1086:     my $lonhost = $perlvar{'lonHostID'};
                   1087:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1088: 		       $server);
                   1089:     if (! $answer) {
                   1090: 	&logthis("No reply on password change request to $server ".
                   1091: 		 "by $uname in domain $udom.");
                   1092:     } elsif ($answer =~ "^ok") {
                   1093:         &logthis("$uname in $udom successfully changed their password ".
                   1094: 		 "on $server.");
                   1095:     } elsif ($answer =~ "^pwchange_failure") {
                   1096: 	&logthis("$uname in $udom was unable to change their password ".
                   1097: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1098: 		 "or pwchange");
                   1099:     } elsif ($answer =~ "^non_authorized") {
                   1100:         &logthis("$uname in $udom did not get their password correct when ".
                   1101: 		 "attempting to change it on $server.");
                   1102:     } elsif ($answer =~ "^auth_mode_error") {
                   1103:         &logthis("$uname in $udom attempted to change their password despite ".
                   1104: 		 "not being locally or internally authenticated on $server.");
                   1105:     } elsif ($answer =~ "^unknown_user") {
                   1106:         &logthis("$uname in $udom attempted to change their password ".
                   1107: 		 "on $server but were unable to because $server is not ".
                   1108: 		 "their home server.");
                   1109:     } elsif ($answer =~ "^refused") {
                   1110: 	&logthis("$server refused to change $uname in $udom password because ".
                   1111: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1112:     } elsif ($answer =~ "invalid_client") {
                   1113:         &logthis("$server refused to change $uname in $udom password because ".
                   1114:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1115:     }
                   1116:     return $answer;
1.1       albertel 1117: }
                   1118: 
1.169     harris41 1119: # ----------------------- Try to determine user's current authentication scheme
                   1120: 
                   1121: sub queryauthenticate {
                   1122:     my ($uname,$udom)=@_;
1.456     albertel 1123:     my $uhome=&homeserver($uname,$udom);
                   1124:     if (!$uhome) {
                   1125: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1126: 	return 'no_host';
                   1127:     }
                   1128:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1129:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1130: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1131:     }
1.456     albertel 1132:     return $answer;
1.169     harris41 1133: }
                   1134: 
1.1       albertel 1135: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1136: 
1.1       albertel 1137: sub authenticate {
1.1073    raeburn  1138:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1139:     $upass=&escape($upass);
                   1140:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1141:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1142:     my $newhome;
1.836     www      1143:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1144: # Maybe the machine was offline and only re-appeared again recently?
                   1145:         &reconlonc();
                   1146: # One more
1.952     raeburn  1147: 	$uhome=&homeserver($uname,$udom,1);
                   1148:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1149:             if (defined(&domain($udom,'primary'))) {
                   1150:                 $newhome=&domain($udom,'primary');
                   1151:             }
                   1152:             if ($newhome ne '') {
                   1153:                 $uhome = $newhome;
                   1154:             }
                   1155:         }
1.836     www      1156: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1157: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1158: 	    return 'no_host';
                   1159:         }
1.1       albertel 1160:     }
1.1073    raeburn  1161:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1162:     if ($answer eq 'authorized') {
1.952     raeburn  1163:         if ($newhome) {
                   1164:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1165:             return 'no_account_on_host'; 
                   1166:         } else {
                   1167:             &logthis("User $uname at $udom authorized by $uhome");
                   1168:             return $uhome;
                   1169:         }
1.471     albertel 1170:     }
                   1171:     if ($answer eq 'non_authorized') {
                   1172: 	&logthis("User $uname at $udom rejected by $uhome");
                   1173: 	return 'no_host'; 
1.9       www      1174:     }
1.471     albertel 1175:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1176:     return 'no_host';
                   1177: }
                   1178: 
1.1073    raeburn  1179: sub can_host_session {
1.1074    raeburn  1180:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1181:     my $canhost = 1;
1.1074    raeburn  1182:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1183:     if (ref($remotesessions) eq 'HASH') {
                   1184:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1185:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1186:                 $canhost = 0;
                   1187:             } else {
                   1188:                 $canhost = 1;
                   1189:             }
                   1190:         }
                   1191:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1192:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1193:                 $canhost = 1;
                   1194:             } else {
                   1195:                 $canhost = 0;
                   1196:             }
                   1197:         }
                   1198:         if ($canhost) {
                   1199:             if ($remotesessions->{'version'} ne '') {
                   1200:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1201:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1202:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1203:                         my $major = $1;
                   1204:                         my $minor = $2;
                   1205:                         if (($major < $reqmajor ) ||
                   1206:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1207:                             $canhost = 0;
                   1208:                         }
                   1209:                     } else {
                   1210:                         $canhost = 0;
                   1211:                     }
                   1212:                 }
                   1213:             }
                   1214:         }
                   1215:     }
                   1216:     if ($canhost) {
                   1217:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1218:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1219:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1220:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1221:                 if (($uint_dom ne '') && 
                   1222:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1223:                     $canhost = 0;
                   1224:                 } else {
                   1225:                     $canhost = 1;
                   1226:                 }
                   1227:             }
                   1228:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1229:                 if (($uint_dom ne '') && 
                   1230:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1231:                     $canhost = 1;
                   1232:                 } else {
                   1233:                     $canhost = 0;
                   1234:                 }
                   1235:             }
                   1236:         }
                   1237:     }
                   1238:     return $canhost;
                   1239: }
                   1240: 
1.1083    raeburn  1241: sub spare_can_host {
                   1242:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1243:     my $canhost=1;
1.1279    raeburn  1244:     my $try_server_hostname = &hostname($try_server);
                   1245:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1246:     my $serverhomedom = &host_domain($serverhomeID);
                   1247:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1248:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1249:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1250:             $canhost = 0;
                   1251:         }
                   1252:     }
                   1253:     if (($canhost) && ($uint_dom)) {
                   1254:         my @intdoms;
                   1255:         my $internet_names = &get_internet_names($try_server);
                   1256:         if (ref($internet_names) eq 'ARRAY') {
                   1257:             @intdoms = @{$internet_names};
                   1258:         }
                   1259:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1260:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1261:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1262:                                          $remotesessions,
                   1263:                                          $defdomdefaults{'hostedsessions'});
                   1264:         }
1.1083    raeburn  1265:     }
                   1266:     return $canhost;
                   1267: }
                   1268: 
1.1123    raeburn  1269: sub this_host_spares {
                   1270:     my ($dom) = @_;
1.1126    raeburn  1271:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1272:     my @hosts = &current_machine_ids();
                   1273:     foreach my $lonhost (@hosts) {
                   1274:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1275:             $dom_in_use = $dom;
                   1276:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1277:             last;
                   1278:         }
                   1279:     }
1.1126    raeburn  1280:     if ($dom_in_use ne '') {
                   1281:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1282:     }
                   1283:     if (ref($result) ne 'HASH') {
                   1284:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1285:         $dom_in_use = &host_domain($lonhost_in_use);
                   1286:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1287:         if (ref($result) ne 'HASH') {
                   1288:             $result = \%spareid;
                   1289:         }
                   1290:     }
                   1291:     return $result;
                   1292: }
                   1293: 
                   1294: sub spares_for_offload  {
                   1295:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1296:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1297:     if (defined($cached)) {
                   1298:         return $result;
                   1299:     } else {
1.1126    raeburn  1300:         my $cachetime = 60*60*24;
                   1301:         my %domconfig =
                   1302:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1303:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1304:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1305:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1306:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1307:                 }
                   1308:             }
                   1309:         }
                   1310:     }
1.1126    raeburn  1311:     return;
1.1123    raeburn  1312: }
                   1313: 
1.1129    raeburn  1314: sub get_lonbalancer_config {
                   1315:     my ($servers) = @_;
                   1316:     my ($currbalancer,$currtargets);
                   1317:     if (ref($servers) eq 'HASH') {
                   1318:         foreach my $server (keys(%{$servers})) {
                   1319:             my %what = (
                   1320:                          spareid => 1,
                   1321:                          perlvar => 1,
                   1322:                        );
                   1323:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1324:             if ($result eq 'ok') {
                   1325:                 if (ref($returnhash) eq 'HASH') {
                   1326:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1327:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1328:                             $currbalancer = $server;
                   1329:                             $currtargets = {};
                   1330:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1331:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1332:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1333:                                 }
                   1334:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1335:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1336:                                 }
                   1337:                             }
                   1338:                             last;
                   1339:                         }
                   1340:                     }
                   1341:                 }
                   1342:             }
                   1343:         }
                   1344:     }
                   1345:     return ($currbalancer,$currtargets);
                   1346: }
                   1347: 
                   1348: sub check_loadbalancing {
1.1331    raeburn  1349:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1350:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1351:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1352:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1353:     my @hosts = &current_machine_ids();
1.1129    raeburn  1354:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1355:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1356:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1357:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1358:     my $domneedscache;
1.1129    raeburn  1359:     my $cachetime = 60*60*24;
                   1360: 
                   1361:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1362:         $dom_in_use = $udom;
                   1363:         $homeintdom = 1;
                   1364:     } else {
                   1365:         $dom_in_use = $serverhomedom;
                   1366:     }
                   1367:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1368:     unless (defined($cached)) {
                   1369:         my %domconfig =
                   1370:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1371:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1372:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1373:         } else {
                   1374:             $domneedscache = $dom_in_use;
1.1129    raeburn  1375:         }
                   1376:     }
                   1377:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1378:         ($is_balancer,$currtargets,$currrules) = 
                   1379:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1380:         if ($is_balancer) {
                   1381:             if (ref($currrules) eq 'HASH') {
                   1382:                 if ($homeintdom) {
                   1383:                     if ($uname ne '') {
                   1384:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1385:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1386:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1387:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1388:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1389:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1390:                             }
                   1391:                         }
                   1392:                         if ($rule_in_effect eq '') {
                   1393:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1394:                             if ($userenv{'inststatus'} ne '') {
                   1395:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1396:                                 my ($othertitle,$usertypes,$types) =
                   1397:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1398:                                 if (ref($types) eq 'ARRAY') {
                   1399:                                     foreach my $type (@{$types}) {
                   1400:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1401:                                             if (exists($currrules->{$type})) {
                   1402:                                                 $rule_in_effect = $currrules->{$type};
                   1403:                                             }
                   1404:                                         }
                   1405:                                     }
                   1406:                                 }
                   1407:                             } else {
                   1408:                                 if (exists($currrules->{'default'})) {
                   1409:                                     $rule_in_effect = $currrules->{'default'};
                   1410:                                 }
                   1411:                             }
                   1412:                         }
                   1413:                     } else {
                   1414:                         if (exists($currrules->{'default'})) {
                   1415:                             $rule_in_effect = $currrules->{'default'};
                   1416:                         }
                   1417:                     }
                   1418:                 } else {
                   1419:                     if ($currrules->{'_LC_external'} ne '') {
                   1420:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1421:                     }
                   1422:                 }
                   1423:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1424:                                                        $uname,$udom);
                   1425:             }
                   1426:         }
                   1427:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1428:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1429:         unless (defined($cached)) {
                   1430:             my %domconfig =
                   1431:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1432:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1433:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1434:             } else {
                   1435:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1436:             }
                   1437:         }
                   1438:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1439:             ($is_balancer,$currtargets,$currrules) = 
                   1440:                 &check_balancer_result($result,@hosts);
                   1441:             if ($is_balancer) {
1.1129    raeburn  1442:                 if (ref($currrules) eq 'HASH') {
                   1443:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1444:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1445:                     }
                   1446:                 }
                   1447:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1448:                                                        $uname,$udom);
                   1449:             }
                   1450:         } else {
                   1451:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1452:                 $is_balancer = 1;
                   1453:                 $offloadto = &this_host_spares($dom_in_use);
                   1454:             }
1.1307    raeburn  1455:             unless (defined($cached)) {
                   1456:                 $domneedscache = $serverhomedom;
                   1457:             }
1.1129    raeburn  1458:         }
                   1459:     } else {
                   1460:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1461:             $is_balancer = 1;
                   1462:             $offloadto = &this_host_spares($dom_in_use);
                   1463:         }
1.1307    raeburn  1464:         unless (defined($cached)) {
                   1465:             $domneedscache = $serverhomedom;
                   1466:         }
                   1467:     }
                   1468:     if ($domneedscache) {
                   1469:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1470:     }
1.1176    raeburn  1471:     if ($is_balancer) {
                   1472:         my $lowest_load = 30000;
                   1473:         if (ref($offloadto) eq 'HASH') {
                   1474:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1475:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1476:                     ($otherserver,$lowest_load) =
                   1477:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1478:                 }
1.1129    raeburn  1479:             }
1.1176    raeburn  1480:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1481: 
1.1176    raeburn  1482:             if (!$found_server) {
                   1483:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1484:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1485:                         ($otherserver,$lowest_load) =
                   1486:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1487:                     }
                   1488:                 }
                   1489:             }
                   1490:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1491:             if (@{$offloadto} == 1) {
                   1492:                 $otherserver = $offloadto->[0];
                   1493:             } elsif (@{$offloadto} > 1) {
                   1494:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1495:                     ($otherserver,$lowest_load) =
                   1496:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1497:                 }
                   1498:             }
                   1499:         }
1.1331    raeburn  1500:         unless ($caller eq 'login') {
                   1501:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1502:                 $is_balancer = 0;
                   1503:                 if ($uname ne '' && $udom ne '') {
                   1504:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1505:                     
1.1331    raeburn  1506:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1507:                                  'user.loadbalcheck.time' => time});
                   1508:                     }
1.1176    raeburn  1509:                 }
1.1129    raeburn  1510:             }
                   1511:         }
                   1512:     }
                   1513:     return ($is_balancer,$otherserver);
                   1514: }
                   1515: 
1.1191    raeburn  1516: sub check_balancer_result {
                   1517:     my ($result,@hosts) = @_;
                   1518:     my ($is_balancer,$currtargets,$currrules);
                   1519:     if (ref($result) eq 'HASH') {
                   1520:         if ($result->{'lonhost'} ne '') {
                   1521:             my $currbalancer = $result->{'lonhost'};
                   1522:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1523:                 $is_balancer = 1;
                   1524:                 $currtargets = $result->{'targets'};
                   1525:                 $currrules = $result->{'rules'};
                   1526:             }
                   1527:         } else {
                   1528:             foreach my $key (keys(%{$result})) {
                   1529:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1530:                     (ref($result->{$key}) eq 'HASH')) {
                   1531:                     $is_balancer = 1;
                   1532:                     $currrules = $result->{$key}{'rules'};
                   1533:                     $currtargets = $result->{$key}{'targets'};
                   1534:                     last;
                   1535:                 }
                   1536:             }
                   1537:         }
                   1538:     }
                   1539:     return ($is_balancer,$currtargets,$currrules);
                   1540: }
                   1541: 
1.1129    raeburn  1542: sub get_loadbalancer_targets {
                   1543:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1544:     my $offloadto;
1.1175    raeburn  1545:     if ($rule_in_effect eq 'none') {
                   1546:         return [$perlvar{'lonHostID'}];
                   1547:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1548:         $offloadto = $currtargets;
                   1549:     } else {
                   1550:         if ($rule_in_effect eq 'homeserver') {
                   1551:             my $homeserver = &homeserver($uname,$udom);
                   1552:             if ($homeserver ne 'no_host') {
                   1553:                 $offloadto = [$homeserver];
                   1554:             }
                   1555:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1556:             my %domconfig =
                   1557:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1558:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1559:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1560:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1561:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1562:                     }
                   1563:                 }
                   1564:             } else {
1.1178    raeburn  1565:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1566:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1567:                 if (&hostname($remotebalancer) ne '') {
                   1568:                     $offloadto = [$remotebalancer];
                   1569:                 }
                   1570:             }
                   1571:         } elsif (&hostname($rule_in_effect) ne '') {
                   1572:             $offloadto = [$rule_in_effect];
                   1573:         }
                   1574:     }
                   1575:     return $offloadto;
                   1576: }
                   1577: 
1.1127    raeburn  1578: sub internet_dom_servers {
                   1579:     my ($dom) = @_;
                   1580:     my (%uniqservers,%servers);
                   1581:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1582:     my @machinedoms = &machine_domains($primaryserver);
                   1583:     foreach my $mdom (@machinedoms) {
                   1584:         my %currservers = %servers;
                   1585:         my %server = &get_servers($mdom);
                   1586:         %servers = (%currservers,%server);
                   1587:     }
                   1588:     my %by_hostname;
                   1589:     foreach my $id (keys(%servers)) {
                   1590:         push(@{$by_hostname{$servers{$id}}},$id);
                   1591:     }
                   1592:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1593:         if (@{$by_hostname{$hostname}} > 1) {
                   1594:             my $match = 0;
                   1595:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1596:                 if (&host_domain($id) eq $dom) {
                   1597:                     $uniqservers{$id} = $hostname;
                   1598:                     $match = 1;
                   1599:                 }
                   1600:             }
                   1601:             unless ($match) {
                   1602:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1603:             }
                   1604:         } else {
                   1605:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1606:         }
                   1607:     }
                   1608:     return %uniqservers;
                   1609: }
                   1610: 
1.1347    raeburn  1611: sub trusted_domains {
                   1612:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1613:     my ($trusted,$untrusted);
1.1347    raeburn  1614:     if (&domain($calldom) eq '') {
1.1349    raeburn  1615:         return ($trusted,$untrusted);
1.1347    raeburn  1616:     }
                   1617:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1618:         return ($trusted,$untrusted);
1.1347    raeburn  1619:     }
                   1620:     my $callprimary = &domain($calldom,'primary');
                   1621:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1622:     if ($intcalldom eq '') {
1.1349    raeburn  1623:         return ($trusted,$untrusted);
1.1347    raeburn  1624:     }
                   1625: 
                   1626:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1627:     unless (defined($cached)) {
                   1628:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1629:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1630:         $trustconfig = $domconfig{'trust'};
                   1631:     }
                   1632:     if (ref($trustconfig)) {
                   1633:         my (%possexc,%possinc,@allexc,@allinc); 
                   1634:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1635:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1636:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1637:             }
                   1638:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1639:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1640:             }
                   1641:         }
                   1642:         if (keys(%possexc)) {
                   1643:             if (keys(%possinc)) {
                   1644:                 foreach my $key (sort(keys(%possexc))) {
                   1645:                     next if ($key eq $intcalldom);
                   1646:                     unless ($possinc{$key}) {
                   1647:                         push(@allexc,$key);
                   1648:                     }
                   1649:                 }
                   1650:             } else {
                   1651:                 @allexc = sort(keys(%possexc));
                   1652:             }
                   1653:         }
                   1654:         if (keys(%possinc)) {
                   1655:             $possinc{$intcalldom} = 1;
                   1656:             @allinc = sort(keys(%possinc));
                   1657:         }
                   1658:         if ((@allexc > 0) || (@allinc > 0)) {
                   1659:             my %doms_by_intdom;
                   1660:             my %allintdoms = &all_host_intdom();
                   1661:             my %alldoms = &all_host_domain();
                   1662:             foreach my $key (%allintdoms) {
                   1663:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1664:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1665:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1666:                     }
                   1667:                 } else {
                   1668:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1669:                 }
                   1670:             }
                   1671:             foreach my $exc (@allexc) {
                   1672:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1673:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1674:                 }
                   1675:             }
                   1676:             foreach my $inc (@allinc) {
                   1677:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1678:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1679:                 }
                   1680:             }
                   1681:         }
                   1682:     }
1.1349    raeburn  1683:     return ($trusted,$untrusted);
1.1347    raeburn  1684: }
                   1685: 
                   1686: sub will_trust {
                   1687:     my ($cmdtype,$domain,$possdom) = @_;
                   1688:     return 1 if ($domain eq $possdom);
                   1689:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1690:     my $willtrust; 
                   1691:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1692:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1693:             $willtrust = 1;
                   1694:         }
                   1695:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1696:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1697:             $willtrust = 1;
                   1698:         }
                   1699:     } else {
                   1700:         $willtrust = 1;
                   1701:     }
                   1702:     return $willtrust;
                   1703: }
                   1704: 
1.1       albertel 1705: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1706: 
1.599     albertel 1707: my %homecache;
1.1       albertel 1708: sub homeserver {
1.230     stredwic 1709:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1710:     my $index="$uname:$udom";
1.426     albertel 1711: 
1.599     albertel 1712:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1713: 
                   1714:     my %servers = &get_servers($udom,'library');
                   1715:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1716:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1717: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1718: 
                   1719: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1720: 	if ($answer eq 'found') {
                   1721: 	    delete($badServerCache{$tryserver}); 
                   1722: 	    return $homecache{$index}=$tryserver;
                   1723: 	} elsif ($answer eq 'no_host') {
                   1724: 	    $badServerCache{$tryserver}=1;
                   1725: 	}
1.1       albertel 1726:     }    
                   1727:     return 'no_host';
1.70      www      1728: }
                   1729: 
1.1300    raeburn  1730: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1731: 
                   1732: sub idget {
1.1300    raeburn  1733:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1734:     my %returnhash=();
1.1300    raeburn  1735:     my @ids=(); 
                   1736:     if (ref($idsref) eq 'ARRAY') {
                   1737:         @ids = @{$idsref};
                   1738:     } else {
                   1739:         return %returnhash; 
                   1740:     }
                   1741:     if ($namespace eq '') {
                   1742:         $namespace = 'ids';
                   1743:     }
1.70      www      1744:     
1.841     albertel 1745:     my %servers = &get_servers($udom,'library');
                   1746:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1747: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1748: 	if ($namespace eq 'ids') {
                   1749: 	    $idlist=~tr/A-Z/a-z/;
                   1750: 	}
                   1751: 	my $reply;
                   1752: 	if ($namespace eq 'ids') {
                   1753: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1754: 	} else {
                   1755: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1756: 	}
1.841     albertel 1757: 	my @answer=();
                   1758: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1759: 	    @answer=split(/\&/,$reply);
                   1760: 	}                    ;
                   1761: 	my $i;
                   1762: 	for ($i=0;$i<=$#ids;$i++) {
                   1763: 	    if ($answer[$i]) {
1.1299    raeburn  1764: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1765: 	    }
1.841     albertel 1766: 	}
1.1300    raeburn  1767:     }
1.70      www      1768:     return %returnhash;
                   1769: }
                   1770: 
                   1771: # ------------------------------------- Find the IDs behind a list of usernames
                   1772: 
                   1773: sub idrget {
                   1774:     my ($udom,@unames)=@_;
                   1775:     my %returnhash=();
1.800     albertel 1776:     foreach my $uname (@unames) {
                   1777:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1778:     }
1.70      www      1779:     return %returnhash;
                   1780: }
                   1781: 
1.1300    raeburn  1782: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1783: 
                   1784: sub idput {
1.1300    raeburn  1785:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1786:     my %servers=();
1.1300    raeburn  1787:     my %ids=();
                   1788:     my %byid = ();
                   1789:     if (ref($idsref) eq 'HASH') {
                   1790:         %ids=%{$idsref};
                   1791:     }
                   1792:     if ($namespace eq '') {
                   1793:         $namespace = 'ids'; 
                   1794:     }
1.800     albertel 1795:     foreach my $uname (keys(%ids)) {
                   1796: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1797:         if ($uhom eq '') {
                   1798:             $uhom=&homeserver($uname,$udom);
                   1799:         }
1.70      www      1800:         if ($uhom ne 'no_host') {
1.800     albertel 1801:             my $esc_unam=&escape($uname);
1.1300    raeburn  1802:             if ($namespace eq 'ids') {
                   1803:                 my $id=&escape($ids{$uname});
                   1804:                 $id=~tr/A-Z/a-z/;
                   1805:                 my $esc_unam=&escape($uname);
                   1806:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1807:             } else {
1.1300    raeburn  1808:                 my @currids = split(/,/,$ids{$uname});
                   1809:                 foreach my $id (@currids) {
                   1810:                     $byid{$uhom}{$id} .= $uname.',';
                   1811:                 }
                   1812:             }
                   1813:         }
                   1814:     }
                   1815:     if ($namespace eq 'clickers') {
                   1816:         foreach my $server (keys(%byid)) {
                   1817:             if (ref($byid{$server}) eq 'HASH') {
                   1818:                 foreach my $id (keys(%{$byid{$server}})) {
                   1819:                     $byid{$server} =~ s/,$//;
                   1820:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1821:                 }
1.70      www      1822:             }
                   1823:         }
1.191     harris41 1824:     }
1.800     albertel 1825:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1826:         $servers{$server} =~ s/\&$//;
                   1827:         if ($namespace eq 'ids') {     
                   1828:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1829:         } else {
                   1830:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1831:         }
1.191     harris41 1832:     }
1.344     www      1833: }
                   1834: 
1.1300    raeburn  1835: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1836: 
                   1837: sub iddel {
1.1300    raeburn  1838:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1839:     my %result=();
1.1300    raeburn  1840:     my %ids=();
                   1841:     my %byid = ();
                   1842:     if (ref($idshashref) eq 'HASH') {
                   1843:         %ids=%{$idshashref};
                   1844:     } else {
1.1231    raeburn  1845:         return %result;
                   1846:     }
1.1300    raeburn  1847:     if ($namespace eq '') {
                   1848:         $namespace = 'ids';
                   1849:     }
1.1231    raeburn  1850:     my %servers=();
1.1300    raeburn  1851:     while (my ($id,$unamestr) = each(%ids)) {
                   1852:         if ($namespace eq 'ids') {
                   1853:             my $uhom = $uhome;
                   1854:             if ($uhom eq '') { 
                   1855:                 $uhom=&homeserver($unamestr,$udom);
                   1856:             }
                   1857:             if ($uhom ne 'no_host') {
                   1858:                 $servers{$uhom}.='&'.&escape($id);
                   1859:             }
                   1860:          } else {
                   1861:             my @curritems = split(/,/,$ids{$id});
                   1862:             foreach my $uname (@curritems) {
                   1863:                 my $uhom = $uhome;
                   1864:                 if ($uhom eq '') {
                   1865:                     $uhom=&homeserver($uname,$udom);
                   1866:                 }
                   1867:                 if ($uhom ne 'no_host') { 
                   1868:                     $byid{$uhom}{$id} .= $uname.',';
                   1869:                 }
                   1870:             }
1.1231    raeburn  1871:         }
1.1300    raeburn  1872:     }
                   1873:     if ($namespace eq 'clickers') {
                   1874:         foreach my $server (keys(%byid)) {
                   1875:             if (ref($byid{$server}) eq 'HASH') {
                   1876:                 foreach my $id (keys(%{$byid{$server}})) {
                   1877:                     $byid{$server}{$id} =~ s/,$//;
                   1878:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1879:                 }
1.1231    raeburn  1880:             }
                   1881:         }
                   1882:     }
                   1883:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1884:         $servers{$server} =~ s/\&$//;
                   1885:         if ($namespace eq 'ids') {
                   1886:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1887:         } elsif ($namespace eq 'clickers') {
                   1888:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1889:         }
1.1231    raeburn  1890:     }
                   1891:     return %result;
                   1892: }
                   1893: 
1.1300    raeburn  1894: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1895: 
                   1896: sub updateclickers {
                   1897:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1898:     my %clickers;
                   1899:     if (ref($idshashref) eq 'HASH') {
                   1900:         %clickers=%{$idshashref};
                   1901:     } else {
                   1902:         return;
                   1903:     }
                   1904:     my $items='';
                   1905:     foreach my $item (keys(%clickers)) {
                   1906:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1907:     }
                   1908:     $items=~s/\&$//;
                   1909:     my $request = "updateclickers:$udom:$action:$items";
                   1910:     if ($critical) {
                   1911:         return &critical($request,$uhome);
                   1912:     } else {
                   1913:         return &reply($request,$uhome);
                   1914:     }
                   1915: }
                   1916: 
1.1023    raeburn  1917: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1918: sub dump_dom {
1.1165    droeschl 1919:     my ($namespace, $udom, $regexp) = @_;
                   1920: 
                   1921:     $udom ||= $env{'user.domain'};
                   1922: 
                   1923:     return () unless $udom;
                   1924: 
                   1925:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1926: }
                   1927: 
1.1023    raeburn  1928: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1929: 
                   1930: sub get_dom {
1.860     raeburn  1931:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1932:     return if ($udom eq 'public');
1.806     raeburn  1933:     my $items='';
                   1934:     foreach my $item (@$storearr) {
                   1935:         $items.=&escape($item).'&';
                   1936:     }
                   1937:     $items=~s/\&$//;
1.860     raeburn  1938:     if (!$udom) {
                   1939:         $udom=$env{'user.domain'};
1.1267    raeburn  1940:         return if ($udom eq 'public');
1.860     raeburn  1941:         if (defined(&domain($udom,'primary'))) {
                   1942:             $uhome=&domain($udom,'primary');
                   1943:         } else {
1.874     albertel 1944:             undef($uhome);
1.860     raeburn  1945:         }
                   1946:     } else {
                   1947:         if (!$uhome) {
                   1948:             if (defined(&domain($udom,'primary'))) {
                   1949:                 $uhome=&domain($udom,'primary');
                   1950:             }
                   1951:         }
                   1952:     }
                   1953:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  1954:         my $rep;
                   1955:         if ($namespace =~ /^enc/) {
                   1956:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1957:         } else {
                   1958:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1959:         }
1.866     raeburn  1960:         my %returnhash;
1.875     albertel 1961:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1962:             return %returnhash;
                   1963:         }
1.806     raeburn  1964:         my @pairs=split(/\&/,$rep);
                   1965:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1966:             return @pairs;
                   1967:         }
                   1968:         my $i=0;
                   1969:         foreach my $item (@$storearr) {
                   1970:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1971:             $i++;
                   1972:         }
                   1973:         return %returnhash;
                   1974:     } else {
1.880     banghart 1975:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1976:     }
                   1977: }
                   1978: 
                   1979: # -------------------------------------------- put items in domain db files 
                   1980: 
                   1981: sub put_dom {
1.860     raeburn  1982:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1983:     if (!$udom) {
                   1984:         $udom=$env{'user.domain'};
                   1985:         if (defined(&domain($udom,'primary'))) {
                   1986:             $uhome=&domain($udom,'primary');
                   1987:         } else {
1.874     albertel 1988:             undef($uhome);
1.860     raeburn  1989:         }
                   1990:     } else {
                   1991:         if (!$uhome) {
                   1992:             if (defined(&domain($udom,'primary'))) {
                   1993:                 $uhome=&domain($udom,'primary');
                   1994:             }
                   1995:         }
                   1996:     } 
                   1997:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1998:         my $items='';
                   1999:         foreach my $item (keys(%$storehash)) {
                   2000:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2001:         }
                   2002:         $items=~s/\&$//;
1.1344    raeburn  2003:         if ($namespace =~ /^enc/) {
                   2004:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2005:         } else {
                   2006:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2007:         }
1.806     raeburn  2008:     } else {
1.860     raeburn  2009:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2010:     }
                   2011: }
                   2012: 
1.1023    raeburn  2013: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2014: sub newput_dom {
1.1023    raeburn  2015:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2016:     my $result;
                   2017:     if (!$udom) {
                   2018:         $udom=$env{'user.domain'};
                   2019:     }
1.1023    raeburn  2020:     if ($udom) {
                   2021:         my $uname = &get_domainconfiguser($udom);
                   2022:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2023:     }
                   2024:     return $result;
                   2025: }
                   2026: 
1.1023    raeburn  2027: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2028: sub del_dom {
1.1023    raeburn  2029:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2030:     if (ref($storearr) eq 'ARRAY') {
                   2031:         if (!$udom) {
                   2032:             $udom=$env{'user.domain'};
                   2033:         }
1.1023    raeburn  2034:         if ($udom) {
                   2035:             my $uname = &get_domainconfiguser($udom); 
                   2036:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2037:         }
                   2038:     }
                   2039: }
                   2040: 
1.1023    raeburn  2041: # ----------------------------------construct domainconfig user for a domain 
                   2042: sub get_domainconfiguser {
                   2043:     my ($udom) = @_;
                   2044:     return $udom.'-domainconfig';
                   2045: }
                   2046: 
1.837     raeburn  2047: sub retrieve_inst_usertypes {
                   2048:     my ($udom) = @_;
                   2049:     my (%returnhash,@order);
1.989     raeburn  2050:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2051:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2052:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2053:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2054:     } else {
                   2055:         if (defined(&domain($udom,'primary'))) {
                   2056:             my $uhome=&domain($udom,'primary');
                   2057:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2058:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2059:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2060:                 return (\%returnhash,\@order);
                   2061:             }
                   2062:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2063:             my @pairs=split(/\&/,$hashitems);
                   2064:             foreach my $item (@pairs) {
                   2065:                 my ($key,$value)=split(/=/,$item,2);
                   2066:                 $key = &unescape($key);
                   2067:                 next if ($key =~ /^error: 2 /);
                   2068:                 $returnhash{$key}=&thaw_unescape($value);
                   2069:             }
                   2070:             my @esc_order = split(/\&/,$orderitems);
                   2071:             foreach my $item (@esc_order) {
                   2072:                 push(@order,&unescape($item));
                   2073:             }
                   2074:         } else {
1.1256    raeburn  2075:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2076:         }
1.1256    raeburn  2077:         return (\%returnhash,\@order);
1.837     raeburn  2078:     }
                   2079: }
                   2080: 
1.868     raeburn  2081: sub is_domainimage {
                   2082:     my ($url) = @_;
1.1306    raeburn  2083:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2084:         if (&domain($1) ne '') {
                   2085:             return '1';
                   2086:         }
                   2087:     }
                   2088:     return;
                   2089: }
                   2090: 
1.899     raeburn  2091: sub inst_directory_query {
                   2092:     my ($srch) = @_;
                   2093:     my $udom = $srch->{'srchdomain'};
                   2094:     my %results;
                   2095:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2096:     my $outcome;
1.899     raeburn  2097:     if ($homeserver ne '') {
1.1357    raeburn  2098:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2099:             if ($srch->{'srchby'} eq 'email') {
                   2100:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2101:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2102:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2103:                     (($major == 2) && ($minor < 12))) {
                   2104:                     return;
                   2105:                 }
                   2106:             }
                   2107:         }
1.904     albertel 2108: 	my $queryid=&reply("querysend:instdirsearch:".
                   2109: 			   &escape($srch->{'srchby'}).':'.
                   2110: 			   &escape($srch->{'srchterm'}).':'.
                   2111: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2112: 	my $host=&hostname($homeserver);
                   2113: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2114: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2115: 	    return;
                   2116: 	}
                   2117: 	my $response = &get_query_reply($queryid);
                   2118: 	my $maxtries = 5;
                   2119: 	my $tries = 1;
                   2120: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2121: 	    $response = &get_query_reply($queryid);
                   2122: 	    $tries ++;
                   2123: 	}
                   2124: 
                   2125:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2126:             if ($response eq 'unavailable') {
                   2127:                 $outcome = $response;
                   2128:             } else {
                   2129:                 $outcome = 'ok';
                   2130:                 my @matches = split(/\n/,$response);
                   2131:                 foreach my $match (@matches) {
                   2132:                     my ($key,$value) = split(/=/,$match);
                   2133:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2134:                 }
1.899     raeburn  2135:             }
                   2136:         }
                   2137:     }
1.909     raeburn  2138:     return ($outcome,%results);
1.899     raeburn  2139: }
                   2140: 
                   2141: sub usersearch {
                   2142:     my ($srch) = @_;
                   2143:     my $dom = $srch->{'srchdomain'};
                   2144:     my %results;
                   2145:     my %libserv = &all_library();
                   2146:     my $query = 'usersearch';
                   2147:     foreach my $tryserver (keys(%libserv)) {
                   2148:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2149:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2150:                 if ($srch->{'srchby'} eq 'email') {
                   2151:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2152:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2153:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2154:                              (($major == 2) && ($minor < 12)));
                   2155:                 }
                   2156:             }
1.899     raeburn  2157:             my $host=&hostname($tryserver);
                   2158:             my $queryid=
1.911     raeburn  2159:                 &reply("querysend:".&escape($query).':'.
                   2160:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2161:                        &escape($srch->{'srchtype'}).':'.
                   2162:                        &escape($srch->{'srchterm'}),$tryserver);
                   2163:             if ($queryid !~/^\Q$host\E\_/) {
                   2164:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2165:                 next;
1.899     raeburn  2166:             }
                   2167:             my $reply = &get_query_reply($queryid);
                   2168:             my $maxtries = 1;
                   2169:             my $tries = 1;
                   2170:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2171:                 $reply = &get_query_reply($queryid);
                   2172:                 $tries ++;
                   2173:             }
                   2174:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2175:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2176:             } else {
1.911     raeburn  2177:                 my @matches;
                   2178:                 if ($reply =~ /\n/) {
                   2179:                     @matches = split(/\n/,$reply);
                   2180:                 } else {
                   2181:                     @matches = split(/\&/,$reply);
                   2182:                 }
1.899     raeburn  2183:                 foreach my $match (@matches) {
                   2184:                     my ($uname,$udom,%userhash);
1.911     raeburn  2185:                     foreach my $entry (split(/:/,$match)) {
                   2186:                         my ($key,$value) =
                   2187:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2188:                         $userhash{$key} = $value;
                   2189:                         if ($key eq 'username') {
                   2190:                             $uname = $value;
                   2191:                         } elsif ($key eq 'domain') {
                   2192:                             $udom = $value;
1.911     raeburn  2193:                         }
1.899     raeburn  2194:                     }
                   2195:                     $results{$uname.':'.$udom} = \%userhash;
                   2196:                 }
                   2197:             }
                   2198:         }
                   2199:     }
                   2200:     return %results;
                   2201: }
                   2202: 
1.912     raeburn  2203: sub get_instuser {
                   2204:     my ($udom,$uname,$id) = @_;
                   2205:     my $homeserver = &domain($udom,'primary');
                   2206:     my ($outcome,%results);
                   2207:     if ($homeserver ne '') {
                   2208:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2209:                            &escape($id).':'.&escape($udom),$homeserver);
                   2210:         my $host=&hostname($homeserver);
                   2211:         if ($queryid !~/^\Q$host\E\_/) {
                   2212:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2213:             return;
                   2214:         }
                   2215:         my $response = &get_query_reply($queryid);
                   2216:         my $maxtries = 5;
                   2217:         my $tries = 1;
                   2218:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2219:             $response = &get_query_reply($queryid);
                   2220:             $tries ++;
                   2221:         }
                   2222:         if (!&error($response) && $response ne 'refused') {
                   2223:             if ($response eq 'unavailable') {
                   2224:                 $outcome = $response;
                   2225:             } else {
                   2226:                 $outcome = 'ok';
                   2227:                 my @matches = split(/\n/,$response);
                   2228:                 foreach my $match (@matches) {
                   2229:                     my ($key,$value) = split(/=/,$match);
                   2230:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2231:                 }
                   2232:             }
                   2233:         }
                   2234:     }
                   2235:     my %userinfo;
                   2236:     if (ref($results{$uname}) eq 'HASH') {
                   2237:         %userinfo = %{$results{$uname}};
                   2238:     } 
                   2239:     return ($outcome,%userinfo);
                   2240: }
                   2241: 
1.1290    raeburn  2242: sub get_multiple_instusers {
                   2243:     my ($udom,$users,$caller) = @_;
                   2244:     my ($outcome,$results);
                   2245:     if (ref($users) eq 'HASH') {
                   2246:         my $count = keys(%{$users}); 
                   2247:         my $requested = &freeze_escape($users);
                   2248:         my $homeserver = &domain($udom,'primary');
                   2249:         if ($homeserver ne '') {
                   2250:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2251:             my $host=&hostname($homeserver);
                   2252:             if ($queryid !~/^\Q$host\E\_/) {
                   2253:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2254:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2255:                 return ($outcome,$results);
                   2256:             }
                   2257:             my $response = &get_query_reply($queryid);
                   2258:             my $maxtries = 5;
                   2259:             if ($count > 100) {
                   2260:                 $maxtries = 1+int($count/20);
                   2261:             }
                   2262:             my $tries = 1;
                   2263:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2264:                 $response = &get_query_reply($queryid);
                   2265:                 $tries ++;
                   2266:             }
                   2267:             if ($response eq '') {
                   2268:                 $results = {};
                   2269:                 foreach my $key (keys(%{$users})) {
                   2270:                     my ($uname,$id);
                   2271:                     if ($caller eq 'id') {
                   2272:                         $id = $key;
                   2273:                     } else {
                   2274:                         $uname = $key;
                   2275:                     }
                   2276:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2277:                     $outcome = $resp;
1.1290    raeburn  2278:                     if ($resp eq 'ok') {
                   2279:                         %{$results} = (%{$results}, %info);
                   2280:                     } else {
                   2281:                         last;
                   2282:                     }
                   2283:                 }
                   2284:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2285:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2286:                     $outcome = $response;
                   2287:                 } else {
1.1291    raeburn  2288:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2289:                     if ($outcome eq 'ok') {
                   2290:                         $results = &thaw_unescape($userdata); 
                   2291:                     }
                   2292:                 }
                   2293:             }
                   2294:         }
                   2295:     }
                   2296:     return ($outcome,$results);
                   2297: }
                   2298: 
1.912     raeburn  2299: sub inst_rulecheck {
1.923     raeburn  2300:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2301:     my %returnhash;
                   2302:     if ($udom ne '') {
                   2303:         if (ref($rules) eq 'ARRAY') {
                   2304:             @{$rules} = map {&escape($_);} (@{$rules});
                   2305:             my $rulestr = join(':',@{$rules});
                   2306:             my $homeserver=&domain($udom,'primary');
                   2307:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2308:                 my $response;
                   2309:                 if ($item eq 'username') {                
                   2310:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2311:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2312:                                               $homeserver));
1.923     raeburn  2313:                 } elsif ($item eq 'id') {
                   2314:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2315:                                               ':'.&escape($id).':'.$rulestr,
                   2316:                                               $homeserver));
1.945     raeburn  2317:                 } elsif ($item eq 'selfcreate') {
                   2318:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2319:                                                &escape($udom).':'.&escape($uname).
                   2320:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2321:                 }
1.912     raeburn  2322:                 if ($response ne 'refused') {
                   2323:                     my @pairs=split(/\&/,$response);
                   2324:                     foreach my $item (@pairs) {
                   2325:                         my ($key,$value)=split(/=/,$item,2);
                   2326:                         $key = &unescape($key);
                   2327:                         next if ($key =~ /^error: 2 /);
                   2328:                         $returnhash{$key}=&thaw_unescape($value);
                   2329:                     }
                   2330:                 }
                   2331:             }
                   2332:         }
                   2333:     }
                   2334:     return %returnhash;
                   2335: }
                   2336: 
                   2337: sub inst_userrules {
1.923     raeburn  2338:     my ($udom,$check) = @_;
1.912     raeburn  2339:     my (%ruleshash,@ruleorder);
                   2340:     if ($udom ne '') {
                   2341:         my $homeserver=&domain($udom,'primary');
                   2342:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2343:             my $response;
                   2344:             if ($check eq 'id') {
                   2345:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2346:                                  $homeserver);
1.943     raeburn  2347:             } elsif ($check eq 'email') {
                   2348:                 $response=&reply('instemailrules:'.&escape($udom),
                   2349:                                  $homeserver);
1.923     raeburn  2350:             } else {
                   2351:                 $response=&reply('instuserrules:'.&escape($udom),
                   2352:                                  $homeserver);
                   2353:             }
1.912     raeburn  2354:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2355:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2356:                 ($response ne 'no_such_host')) {
                   2357:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2358:                 my @pairs=split(/\&/,$hashitems);
                   2359:                 foreach my $item (@pairs) {
                   2360:                     my ($key,$value)=split(/=/,$item,2);
                   2361:                     $key = &unescape($key);
                   2362:                     next if ($key =~ /^error: 2 /);
                   2363:                     $ruleshash{$key}=&thaw_unescape($value);
                   2364:                 }
                   2365:                 my @esc_order = split(/\&/,$orderitems);
                   2366:                 foreach my $item (@esc_order) {
                   2367:                     push(@ruleorder,&unescape($item));
                   2368:                 }
                   2369:             }
                   2370:         }
                   2371:     }
                   2372:     return (\%ruleshash,\@ruleorder);
                   2373: }
                   2374: 
1.976     raeburn  2375: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2376: 
                   2377: sub get_domain_defaults {
1.1240    raeburn  2378:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2379:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2380:     my $cachetime = 60*60*24;
1.1240    raeburn  2381:     unless ($ignore_cache) {
                   2382:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2383:         if (defined($cached)) {
                   2384:             if (ref($result) eq 'HASH') {
                   2385:                 return %{$result};
                   2386:             }
1.943     raeburn  2387:         }
                   2388:     }
                   2389:     my %domdefaults;
                   2390:     my %domconfig =
1.989     raeburn  2391:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2392:                                   'requestcourses','inststatus',
1.1183    raeburn  2393:                                   'coursedefaults','usersessions',
1.1258    raeburn  2394:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2395:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2396:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2397:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2398:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2399:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2400:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2401:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2402:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2403:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2404:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2405:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2406:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2407:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2408:     } else {
                   2409:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2410:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2411:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2412:     }
1.976     raeburn  2413:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2414:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2415:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2416:         } else {
                   2417:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2418:         }
1.1177    raeburn  2419:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2420:         foreach my $item (@usertools) {
                   2421:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2422:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2423:             }
                   2424:         }
1.1229    raeburn  2425:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2426:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2427:         }
1.976     raeburn  2428:     }
1.985     raeburn  2429:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2430:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2431:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2432:         }
                   2433:     }
1.1183    raeburn  2434:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2435:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2436:     }
1.989     raeburn  2437:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2438:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2439:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2440:         }
                   2441:     }
1.1047    raeburn  2442:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2443:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2444:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2445:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2446:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2447:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2448:         }
1.1254    raeburn  2449:         foreach my $type (@coursetypes) {
                   2450:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2451:                 unless ($type eq 'community') {
                   2452:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2453:                 }
                   2454:             }
                   2455:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2456:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2457:             }
1.1277    raeburn  2458:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2459:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2460:                     $domdefaults{$type.'postsubtimeout'} = 
                   2461:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2462:                 }
                   2463:             }
1.1230    raeburn  2464:         }
1.1286    raeburn  2465:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2466:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2467:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2468:                 if (@clonecodes) {
                   2469:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2470:                 }
                   2471:             }
                   2472:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2473:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2474:         }
1.1356    raeburn  2475:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2476:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2477:         } 
1.1047    raeburn  2478:     }
1.1073    raeburn  2479:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2480:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2481:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2482:         }
                   2483:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2484:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2485:         }
1.1279    raeburn  2486:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2487:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2488:         }
1.1073    raeburn  2489:     }
1.1254    raeburn  2490:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2491:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2492:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2493:                             'approval','limit');
                   2494:             foreach my $type (@coursetypes) {
                   2495:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2496:                     my @mgrdc = ();
                   2497:                     foreach my $item (@settings) {
                   2498:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2499:                             push(@mgrdc,$item);
                   2500:                         }
                   2501:                     }
                   2502:                     if (@mgrdc) {
                   2503:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2504:                     }
                   2505:                 }
                   2506:             }
                   2507:         }
                   2508:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2509:             foreach my $type (@coursetypes) {
                   2510:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2511:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2512:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2513:                     }
                   2514:                 }
                   2515:             }
                   2516:         }
                   2517:     }
1.1258    raeburn  2518:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2519:         $domdefaults{'catauth'} = 'std';
                   2520:         $domdefaults{'catunauth'} = 'std';
                   2521:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2522:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2523:         }
                   2524:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2525:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2526:         }
                   2527:     }
1.1315    raeburn  2528:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2529:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2530:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2531:         }
1.1338    raeburn  2532:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2533:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2534:         }
                   2535:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2536:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2537:         }
                   2538:     }
1.1320    raeburn  2539:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2540:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2541:         foreach my $prefix (@prefixes) {
                   2542:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2543:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2544:             }
                   2545:         }
                   2546:     }
1.1314    raeburn  2547:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2548:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2549:     }
1.1332    raeburn  2550:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2551:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2552:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2553:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2554:         }
                   2555:     }
1.1219    raeburn  2556:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2557:     return %domdefaults;
                   2558: }
                   2559: 
1.1311    raeburn  2560: sub course_portal_url {
                   2561:     my ($cnum,$cdom) = @_;
                   2562:     my $chome = &homeserver($cnum,$cdom);
                   2563:     my $hostname = &hostname($chome);
                   2564:     my $protocol = $protocol{$chome};
                   2565:     $protocol = 'http' if ($protocol ne 'https');
                   2566:     my %domdefaults = &get_domain_defaults($cdom);
                   2567:     my $firsturl;
                   2568:     if ($domdefaults{'portal_def'}) {
                   2569:         $firsturl = $domdefaults{'portal_def'};
                   2570:     } else {
                   2571:         $firsturl = $protocol.'://'.$hostname;
                   2572:     }
                   2573:     return $firsturl;
                   2574: }
                   2575: 
1.344     www      2576: # --------------------------------------------------- Assign a key to a student
                   2577: 
                   2578: sub assign_access_key {
1.364     www      2579: #
                   2580: # a valid key looks like uname:udom#comments
                   2581: # comments are being appended
                   2582: #
1.498     www      2583:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2584:     $kdom=
1.620     albertel 2585:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2586:     $knum=
1.620     albertel 2587:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2588:     $cdom=
1.620     albertel 2589:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2590:     $cnum=
1.620     albertel 2591:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2592:     $udom=$env{'user.name'} unless (defined($udom));
                   2593:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2594:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2595:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2596:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2597:                                                   # assigned to this person
                   2598:                                                   # - this should not happen,
1.345     www      2599:                                                   # unless something went wrong
                   2600:                                                   # the first time around
                   2601: # ready to assign
1.364     www      2602:         $logentry=$1.'; '.$logentry;
1.496     www      2603:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2604:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2605: # key now belongs to user
1.346     www      2606: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2607:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2608:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2609:                 return 'ok';
                   2610:             } else {
                   2611:                 return 
                   2612:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2613: 	    }
                   2614:         } else {
                   2615:             return 'error: Could not assign key, try again later.';
                   2616:         }
1.364     www      2617:     } elsif (!$existing{$ckey}) {
1.345     www      2618: # the key does not exist
                   2619: 	return 'error: The key does not exist';
                   2620:     } else {
                   2621: # the key is somebody else's
                   2622: 	return 'error: The key is already in use';
                   2623:     }
1.344     www      2624: }
                   2625: 
1.364     www      2626: # ------------------------------------------ put an additional comment on a key
                   2627: 
                   2628: sub comment_access_key {
                   2629: #
                   2630: # a valid key looks like uname:udom#comments
                   2631: # comments are being appended
                   2632: #
                   2633:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2634:     $cdom=
1.620     albertel 2635:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2636:     $cnum=
1.620     albertel 2637:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2638:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2639:     if ($existing{$ckey}) {
                   2640:         $existing{$ckey}.='; '.$logentry;
                   2641: # ready to assign
1.367     www      2642:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2643:                                                  $cdom,$cnum) eq 'ok') {
                   2644: 	    return 'ok';
                   2645:         } else {
                   2646: 	    return 'error: Count not store comment.';
                   2647:         }
                   2648:     } else {
                   2649: # the key does not exist
                   2650: 	return 'error: The key does not exist';
                   2651:     }
                   2652: }
                   2653: 
1.344     www      2654: # ------------------------------------------------------ Generate a set of keys
                   2655: 
                   2656: sub generate_access_keys {
1.364     www      2657:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2658:     $cdom=
1.620     albertel 2659:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2660:     $cnum=
1.620     albertel 2661:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2662:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2663:     unless (($cdom) && ($cnum)) { return 0; }
                   2664:     if ($number>10000) { return 0; }
                   2665:     sleep(2); # make sure don't get same seed twice
                   2666:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2667:     my $total=0;
                   2668:     for (my $i=1;$i<=$number;$i++) {
                   2669:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2670:                   sprintf("%lx",int(100000*rand)).'-'.
                   2671:                   sprintf("%lx",int(100000*rand));
                   2672:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2673:        $newkey=~s/0/h/g; # and also 0 and O
                   2674:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2675:        if ($existing{$newkey}) {
                   2676:            $i--;
                   2677:        } else {
1.364     www      2678: 	  if (&put('accesskeys',
                   2679:               { $newkey => '# generated '.localtime().
1.620     albertel 2680:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2681:                            '; '.$logentry },
                   2682: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2683:               $total++;
                   2684: 	  }
                   2685:        }
                   2686:     }
1.620     albertel 2687:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2688:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2689:     return $total;
                   2690: }
                   2691: 
                   2692: # ------------------------------------------------------- Validate an accesskey
                   2693: 
                   2694: sub validate_access_key {
                   2695:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2696:     $cdom=
1.620     albertel 2697:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2698:     $cnum=
1.620     albertel 2699:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2700:     $udom=$env{'user.domain'} unless (defined($udom));
                   2701:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2702:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2703:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2704: }
                   2705: 
                   2706: # ------------------------------------- Find the section of student in a course
1.652     albertel 2707: sub devalidate_getsection_cache {
                   2708:     my ($udom,$unam,$courseid)=@_;
                   2709:     my $hashid="$udom:$unam:$courseid";
                   2710:     &devalidate_cache_new('getsection',$hashid);
                   2711: }
1.298     matthew  2712: 
1.815     albertel 2713: sub courseid_to_courseurl {
                   2714:     my ($courseid) = @_;
                   2715:     #already url style courseid
                   2716:     return $courseid if ($courseid =~ m{^/});
                   2717: 
                   2718:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2719: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2720: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2721: 	return "/$cdom/$cnum";
                   2722:     }
                   2723: 
                   2724:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2725:     if (exists($courseinfo{'num'})) {
                   2726: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2727:     }
                   2728: 
                   2729:     return undef;
                   2730: }
                   2731: 
1.298     matthew  2732: sub getsection {
                   2733:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2734:     my $cachetime=1800;
1.551     albertel 2735: 
                   2736:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2737:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2738:     if (defined($cached)) { return $result; }
                   2739: 
1.298     matthew  2740:     my %Pending; 
                   2741:     my %Expired;
                   2742:     #
                   2743:     # Each role can either have not started yet (pending), be active, 
                   2744:     #    or have expired.
                   2745:     #
                   2746:     # If there is an active role, we are done.
                   2747:     #
                   2748:     # If there is more than one role which has not started yet, 
                   2749:     #     choose the one which will start sooner
                   2750:     # If there is one role which has not started yet, return it.
                   2751:     #
                   2752:     # If there is more than one expired role, choose the one which ended last.
                   2753:     # If there is a role which has expired, return it.
                   2754:     #
1.815     albertel 2755:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2756:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2757:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2758:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2759:         my $section=$1;
                   2760:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2761:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2762:         my $now=time;
1.548     albertel 2763:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2764:             $Expired{$end}=$section;
                   2765:             next;
                   2766:         }
1.548     albertel 2767:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2768:             $Pending{$start}=$section;
                   2769:             next;
                   2770:         }
1.599     albertel 2771:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2772:     }
                   2773:     #
                   2774:     # Presumedly there will be few matching roles from the above
                   2775:     # loop and the sorting time will be negligible.
                   2776:     if (scalar(keys(%Pending))) {
                   2777:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2778:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2779:     } 
                   2780:     if (scalar(keys(%Expired))) {
                   2781:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2782:         my $time = pop(@sorted);
1.599     albertel 2783:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2784:     }
1.599     albertel 2785:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2786: }
1.70      www      2787: 
1.599     albertel 2788: sub save_cache {
                   2789:     &purge_remembered();
1.722     albertel 2790:     #&Apache::loncommon::validate_page();
1.620     albertel 2791:     undef(%env);
1.780     albertel 2792:     undef($env_loaded);
1.599     albertel 2793: }
1.452     albertel 2794: 
1.599     albertel 2795: my $to_remember=-1;
                   2796: my %remembered;
                   2797: my %accessed;
                   2798: my $kicks=0;
                   2799: my $hits=0;
1.849     albertel 2800: sub make_key {
                   2801:     my ($name,$id) = @_;
1.872     albertel 2802:     if (length($id) > 65 
                   2803: 	&& length(&escape($id)) > 200) {
                   2804: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2805:     }
1.849     albertel 2806:     return &escape($name.':'.$id);
                   2807: }
                   2808: 
1.599     albertel 2809: sub devalidate_cache_new {
                   2810:     my ($name,$id,$debug) = @_;
                   2811:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2812:     my $remembered_id=$name.':'.$id;
1.849     albertel 2813:     $id=&make_key($name,$id);
1.599     albertel 2814:     $memcache->delete($id);
1.1319    damieng  2815:     delete($remembered{$remembered_id});
                   2816:     delete($accessed{$remembered_id});
1.599     albertel 2817: }
                   2818: 
                   2819: sub is_cached_new {
                   2820:     my ($name,$id,$debug) = @_;
1.1319    damieng  2821:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2822:     if (exists($remembered{$remembered_id})) {
                   2823: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2824: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2825: 	$hits++;
1.1319    damieng  2826: 	return ($remembered{$remembered_id},1);
1.599     albertel 2827:     }
1.1319    damieng  2828:     $id=&make_key($name,$id);
1.599     albertel 2829:     my $value = $memcache->get($id);
                   2830:     if (!(defined($value))) {
                   2831: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2832: 	return (undef,undef);
1.416     albertel 2833:     }
1.599     albertel 2834:     if ($value eq '__undef__') {
                   2835: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2836: 	$value=undef;
                   2837:     }
1.1319    damieng  2838:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2839:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2840:     return ($value,1);
                   2841: }
                   2842: 
                   2843: sub do_cache_new {
                   2844:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2845:     my $remembered_id=$name.':'.$id;
1.849     albertel 2846:     $id=&make_key($name,$id);
1.599     albertel 2847:     my $setvalue=$value;
                   2848:     if (!defined($setvalue)) {
                   2849: 	$setvalue='__undef__';
                   2850:     }
1.623     albertel 2851:     if (!defined($time) ) {
                   2852: 	$time=600;
                   2853:     }
1.599     albertel 2854:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2855:     my $result = $memcache->set($id,$setvalue,$time);
                   2856:     if (! $result) {
1.872     albertel 2857: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2858: 	$memcache->disconnect_all();
1.872     albertel 2859:     }
1.600     albertel 2860:     # need to make a copy of $value
1.1319    damieng  2861:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2862:     return $value;
                   2863: }
                   2864: 
                   2865: sub make_room {
1.1319    damieng  2866:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2867: 
1.1319    damieng  2868:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2869:                                     : $value;
1.599     albertel 2870:     if ($to_remember<0) { return; }
1.1319    damieng  2871:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2872:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2873:     my $to_kick;
                   2874:     my $max_time=0;
                   2875:     foreach my $other (keys(%accessed)) {
                   2876: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2877: 	    $to_kick=$other;
                   2878: 	    $max_time=&tv_interval($accessed{$other});
                   2879: 	}
                   2880:     }
                   2881:     delete($remembered{$to_kick});
                   2882:     delete($accessed{$to_kick});
                   2883:     $kicks++;
                   2884:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2885:     return;
                   2886: }
                   2887: 
1.599     albertel 2888: sub purge_remembered {
1.604     albertel 2889:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2890:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2891:     undef(%remembered);
                   2892:     undef(%accessed);
1.428     albertel 2893: }
1.70      www      2894: # ------------------------------------- Read an entry from a user's environment
                   2895: 
                   2896: sub userenvironment {
                   2897:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2898:     my $items;
                   2899:     foreach my $item (@what) {
                   2900:         $items.=&escape($item).'&';
                   2901:     }
                   2902:     $items=~s/\&$//;
1.70      www      2903:     my %returnhash=();
1.1009    raeburn  2904:     my $uhome = &homeserver($unam,$udom);
                   2905:     unless ($uhome eq 'no_host') {
                   2906:         my @answer=split(/\&/, 
                   2907:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2908:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2909:             return %returnhash;
                   2910:         }
1.1009    raeburn  2911:         my $i;
                   2912:         for ($i=0;$i<=$#what;$i++) {
                   2913: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2914:         }
1.70      www      2915:     }
                   2916:     return %returnhash;
1.1       albertel 2917: }
                   2918: 
1.617     albertel 2919: # ---------------------------------------------------------- Get a studentphoto
                   2920: sub studentphoto {
                   2921:     my ($udom,$unam,$ext) = @_;
                   2922:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2923:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2924:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2925:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2926:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2927:             } else {
                   2928:                 my ($result,$perm_reqd)=
1.707     albertel 2929: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2930:                 if ($result eq 'ok') {
                   2931:                     if (!($perm_reqd eq 'yes')) {
                   2932:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2933:                     }
                   2934:                 }
                   2935:             }
                   2936:         }
                   2937:     } else {
                   2938:         my ($result,$perm_reqd) = 
1.707     albertel 2939: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2940:         if ($result eq 'ok') {
                   2941:             if (!($perm_reqd eq 'yes')) {
                   2942:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2943:             }
                   2944:         }
                   2945:     }
                   2946:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2947: }
                   2948: 
                   2949: sub retrievestudentphoto {
                   2950:     my ($udom,$unam,$ext,$type) = @_;
                   2951:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2952:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2953:     if ($ret eq 'ok') {
                   2954:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2955:         if ($type eq 'thumbnail') {
                   2956:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2957:         }
                   2958:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2959:         return $tokenurl;
                   2960:     } else {
                   2961:         if ($type eq 'thumbnail') {
                   2962:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2963:         } else { 
                   2964:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2965:         }
1.617     albertel 2966:     }
                   2967: }
                   2968: 
1.263     www      2969: # -------------------------------------------------------------------- New chat
                   2970: 
                   2971: sub chatsend {
1.724     raeburn  2972:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2973:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2974:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2975:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2976:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2977: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2978: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2979: }
                   2980: 
                   2981: # ------------------------------------------ Find current version of a resource
                   2982: 
                   2983: sub getversion {
                   2984:     my $fname=&clutter(shift);
1.1189    raeburn  2985:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2986:     return &currentversion(&filelocation('',$fname));
                   2987: }
                   2988: 
                   2989: sub currentversion {
                   2990:     my $fname=shift;
                   2991:     my $author=$fname;
                   2992:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2993:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2994:     my $home=&homeserver($uname,$udom);
1.292     www      2995:     if ($home eq 'no_host') { 
                   2996:         return -1; 
                   2997:     }
1.1112    www      2998:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2999:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3000: 	return -1;
                   3001:     }
1.1112    www      3002:     return $answer;
1.263     www      3003: }
                   3004: 
1.1111    www      3005: #
                   3006: # Return special version number of resource if set by override, empty otherwise
                   3007: #
                   3008: sub usedversion {
                   3009:     my $fname=shift;
                   3010:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3011:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3012:     if ($urlversion) { return $urlversion; }
                   3013:     return '';
                   3014: }
                   3015: 
1.1       albertel 3016: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3017: 
1.1       albertel 3018: sub subscribe {
                   3019:     my $fname=shift;
1.761     raeburn  3020:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3021:     $fname=~s/[\n\r]//g;
1.1       albertel 3022:     my $author=$fname;
                   3023:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3024:     my ($udom,$uname)=split(/\//,$author);
                   3025:     my $home=homeserver($uname,$udom);
1.335     albertel 3026:     if ($home eq 'no_host') {
                   3027:         return 'not_found';
1.1       albertel 3028:     }
                   3029:     my $answer=reply("sub:$fname",$home);
1.64      www      3030:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3031: 	$answer.=' by '.$home;
                   3032:     }
1.1       albertel 3033:     return $answer;
                   3034: }
                   3035:     
1.8       www      3036: # -------------------------------------------------------------- Replicate file
                   3037: 
                   3038: sub repcopy {
                   3039:     my $filename=shift;
1.23      www      3040:     $filename=~s/\/+/\//g;
1.1142    raeburn  3041:     my $londocroot = $perlvar{'lonDocRoot'};
                   3042:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3043:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3044:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3045: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3046: 	return &repcopy_userfile($filename);
                   3047:     }
1.532     albertel 3048:     $filename=~s/[\n\r]//g;
1.8       www      3049:     my $transname="$filename.in.transfer";
1.828     www      3050: # FIXME: this should flock
1.607     raeburn  3051:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3052:     my $remoteurl=subscribe($filename);
1.64      www      3053:     if ($remoteurl =~ /^con_lost by/) {
                   3054: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3055:            return 'unavailable';
1.8       www      3056:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3057: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3058: 	   return 'not_found';
1.64      www      3059:     } elsif ($remoteurl =~ /^rejected by/) {
                   3060: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3061:            return 'forbidden';
1.20      www      3062:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3063:            return 'ok';
1.8       www      3064:     } else {
1.290     www      3065:         my $author=$filename;
                   3066:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3067:         my ($udom,$uname)=split(/\//,$author);
                   3068:         my $home=homeserver($uname,$udom);
                   3069:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3070:            my @parts=split(/\//,$filename);
                   3071:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3072:            if ($path ne "$londocroot/res") {
1.8       www      3073:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3074: 	       return 'bad_request';
1.8       www      3075:            }
                   3076:            my $count;
                   3077:            for ($count=5;$count<$#parts;$count++) {
                   3078:                $path.="/$parts[$count]";
                   3079:                if ((-e $path)!=1) {
                   3080: 		   mkdir($path,0777);
                   3081:                }
                   3082:            }
                   3083:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3084:            my $response;
                   3085:            if ($remoteurl =~ m{/raw/}) {
                   3086:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3087:            } else {
                   3088:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3089:            }
1.8       www      3090:            if ($response->is_error()) {
                   3091: 	       unlink($transname);
                   3092:                my $message=$response->status_line;
1.672     albertel 3093:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3094:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3095:                return 'unavailable';
1.8       www      3096:            } else {
1.16      www      3097: 	       if ($remoteurl!~/\.meta$/) {
                   3098:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3099:                   my $mresponse;
                   3100:                   if ($remoteurl =~ m{/raw/}) {
                   3101:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3102:                   } else {
                   3103:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3104:                   }
1.16      www      3105:                   if ($mresponse->is_error()) {
                   3106: 		      unlink($filename.'.meta');
                   3107:                       &logthis(
1.672     albertel 3108:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3109:                   }
                   3110: 	       }
1.8       www      3111:                rename($transname,$filename);
1.607     raeburn  3112:                return 'ok';
1.8       www      3113:            }
1.290     www      3114:        }
1.8       www      3115:     }
1.330     www      3116: }
                   3117: 
                   3118: # ------------------------------------------------ Get server side include body
                   3119: sub ssi_body {
1.381     albertel 3120:     my ($filelink,%form)=@_;
1.606     matthew  3121:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3122:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3123:     }
1.953     www      3124:     my $output='';
                   3125:     my $response;
1.980     raeburn  3126:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3127:        ($output,$response)=&externalssi($filelink);
1.953     www      3128:     } else {
1.1004    droeschl 3129:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3130:        $filelink .= 'inhibitmenu=yes';
1.953     www      3131:        ($output,$response)=&ssi($filelink,%form);
                   3132:     }
1.778     albertel 3133:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3134:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3135:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3136:     if (wantarray) {
                   3137:         return ($output, $response);
                   3138:     } else {
                   3139:         return $output;
                   3140:     }
1.8       www      3141: }
                   3142: 
1.15      www      3143: # --------------------------------------------------------- Server Side Include
                   3144: 
1.782     albertel 3145: sub absolute_url {
                   3146:     my ($host_name) = @_;
                   3147:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3148:     if ($host_name eq '') {
                   3149: 	$host_name = $ENV{'SERVER_NAME'};
                   3150:     }
                   3151:     return $protocol.$host_name;
                   3152: }
                   3153: 
1.942     foxr     3154: #
                   3155: #   Server side include.
                   3156: # Parameters:
                   3157: #  fn     Possibly encrypted resource name/id.
                   3158: #  form   Hash that describes how the rendering should be done
                   3159: #         and other things.
1.944     foxr     3160: # Returns:
1.950     raeburn  3161: #   Scalar context: The content of the response.
                   3162: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3163: #     
1.15      www      3164: sub ssi {
                   3165: 
1.944     foxr     3166:     my ($fn,%form)=@_;
1.23      www      3167:     my $request;
1.711     albertel 3168: 
                   3169:     $form{'no_update_last_known'}=1;
1.895     albertel 3170:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3171:     if (%form) {
1.782     albertel 3172:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3173:       $request->content(join('&',map { 
                   3174:             my $name = escape($_);
                   3175:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3176:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3177:             : &escape($form{$_}) );    
                   3178:         } keys(%form)));
1.23      www      3179:     } else {
1.782     albertel 3180:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3181:     }
                   3182: 
1.15      www      3183:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3184:     my $lonhost = $perlvar{'lonHostID'};
                   3185:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
1.1182    foxr     3186: 
1.944     foxr     3187:     if (wantarray) {
1.1345    raeburn  3188: 	return ($response->content, $response);
1.944     foxr     3189:     } else {
1.1345    raeburn  3190: 	return $response->content;
1.942     foxr     3191:     }
1.324     www      3192: }
                   3193: 
                   3194: sub externalssi {
                   3195:     my ($url)=@_;
                   3196:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3197:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3198:     if (wantarray) {
                   3199:         return ($response->content, $response);
                   3200:     } else {
                   3201:         return $response->content;
                   3202:     }
1.15      www      3203: }
1.254     www      3204: 
1.1354    raeburn  3205: 
                   3206: # If the local copy of a replicated resource is outdated, trigger a  
                   3207: # connection from the homeserver to flush the delayed queue. If no update 
                   3208: # happens, remove local copies of outdated resource (and corresponding
                   3209: # metadata file).
                   3210: 
1.1352    raeburn  3211: sub remove_stale_resfile {
                   3212:     my ($url) = @_;
1.1354    raeburn  3213:     my $removed;
1.1352    raeburn  3214:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3215:         my $audom = $1;
                   3216:         my $auname = $2;
1.1353    raeburn  3217:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3218:             my $homeserver = &homeserver($auname,$audom);
                   3219:             unless (($homeserver eq 'no_host') ||
                   3220:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3221:                 my $fname = &filelocation('',$url);
                   3222:                 if (-e $fname) {
                   3223:                     my $protocol = $protocol{$homeserver};
                   3224:                     $protocol = 'http' if ($protocol ne 'https');
                   3225:                     my $hostname = &hostname($homeserver);
                   3226:                     if ($hostname) {
                   3227:                         my $uri = &declutter($url);
                   3228:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3229:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3230:                         if ($response->is_success()) {
                   3231:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3232:                             my $locmodtime = (stat($fname))[9];
                   3233:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3234:                                 my $stale;
                   3235:                                 my $answer = &reply('pong',$homeserver);
                   3236:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3237:                                     sleep(0.2);
                   3238:                                     $locmodtime = (stat($fname))[9];
                   3239:                                     if ($locmodtime < $remmodtime) {
                   3240:                                         my $posstransfer = $fname.'.in.transfer';
                   3241:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3242:                                             $removed = 1;
                   3243:                                         } else {
                   3244:                                             $stale = 1;
                   3245:                                         }
                   3246:                                     } else {
                   3247:                                         $removed = 1;
                   3248:                                     }
                   3249:                                 } else {
                   3250:                                     $stale = 1;
                   3251:                                 }
                   3252:                                 if ($stale) {
                   3253:                                     unlink($fname);
                   3254:                                     if ($uri!~/\.meta$/) {
                   3255:                                         unlink($fname.'.meta');
                   3256:                                     }
                   3257:                                     &reply("unsub:$fname",$homeserver);
                   3258:                                     $removed = 1;
1.1352    raeburn  3259:                                 }
                   3260:                             }
                   3261:                         }
                   3262:                     }
                   3263:                 }
                   3264:             }
                   3265:         }
                   3266:     }
1.1354    raeburn  3267:     return $removed;
1.1352    raeburn  3268: }
                   3269: 
1.492     albertel 3270: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3271: 
                   3272: sub allowuploaded {
                   3273:     my ($srcurl,$url)=@_;
                   3274:     $url=&clutter(&declutter($url));
                   3275:     my $dir=$url;
                   3276:     $dir=~s/\/[^\/]+$//;
                   3277:     my %httpref=();
                   3278:     my $httpurl=&hreflocation('',$url);
                   3279:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3280:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3281: }
1.477     raeburn  3282: 
1.1193    raeburn  3283: #
                   3284: # Determine if the current user should be able to edit a particular resource,
                   3285: # when viewing in course context.
                   3286: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3287: #     Functions.
                   3288: # (b) When displaying folder contents in course editor, used to determine if
                   3289: #     "Edit" link will be displayed alongside resource.
                   3290: #
1.1196    raeburn  3291: #  input: six args -- filename (decluttered), course number, course domain,
                   3292: #                   url, symb (if registered) and group (if this is a group
                   3293: #                   item -- e.g., bulletin board, group page etc.).
                   3294: #  output: array of five scalars -- 
1.1193    raeburn  3295: #          $cfile -- url for file editing if editable on current server
                   3296: #          $home -- homeserver of resource (i.e., for author if published,
                   3297: #                                           or course if uploaded.).
                   3298: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3299: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3300: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3301: #
                   3302: 
                   3303: sub can_edit_resource {
1.1194    raeburn  3304:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3305:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3306: #
                   3307: # For aboutme pages user can only edit his/her own.
                   3308: #
1.1199    raeburn  3309:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3310:         my ($sdom,$sname) = ($1,$2);
                   3311:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3312:             $home = $env{'user.home'};
                   3313:             $cfile = $resurl;
                   3314:             if ($env{'form.forceedit'}) {
                   3315:                 $forceview = 1;
                   3316:             } else {
                   3317:                 $forceedit = 1;
                   3318:             }
                   3319:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3320:         } else {
                   3321:             return;
                   3322:         }
                   3323:     }
                   3324: 
                   3325:     if ($env{'request.course.id'}) {
                   3326:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3327:         if ($group ne '') {
                   3328: # if this is a group homepage or group bulletin board, check group privs
                   3329:             my $allowed = 0;
1.1197    raeburn  3330:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3331:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3332:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3333:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3334:                     $allowed = 1;
                   3335:                 }
1.1197    raeburn  3336:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3337:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3338:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3339:                     $allowed = 1;
                   3340:                 }
                   3341:             }
                   3342:             if ($allowed) {
                   3343:                 $home=&homeserver($cnum,$cdom);
                   3344:                 if ($env{'form.forceedit'}) {
                   3345:                     $forceview = 1;
                   3346:                 } else {
                   3347:                     $forceedit = 1;
                   3348:                 }
                   3349:                 $cfile = $resurl;
                   3350:             } else {
                   3351:                 return;
                   3352:             }
                   3353:         } else {
1.1208    raeburn  3354:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3355:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3356:                     return;
                   3357:                 }
                   3358:             } elsif (!$crsedit) {
1.1194    raeburn  3359: #
                   3360: # No edit allowed where CC has switched to student role.
                   3361: #
                   3362:                 return;
                   3363:             }
                   3364:         }
                   3365:     }
                   3366: 
1.1193    raeburn  3367:     if ($file ne '') {
                   3368:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3369:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3370:                 $uploaded = 1;
                   3371:                 $incourse = 1;
1.1193    raeburn  3372:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3373:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3374:                     if ($env{'form.forceedit'}) {
                   3375:                         $forceview = 1;
                   3376:                     } else {
                   3377:                         $forceedit = 1;
                   3378:                     }
1.1194    raeburn  3379:                 }
                   3380:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3381:                 $incourse = 1;
                   3382:                 if ($env{'form.forceedit'}) {
                   3383:                     $forceview = 1;
                   3384:                 } else {
                   3385:                     $forceedit = 1;
                   3386:                 }
                   3387:                 $cfile = $resurl;
                   3388:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3389:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3390:                     $incourse = 1;
                   3391:                     if ($env{'form.forceedit'}) {
                   3392:                         $forceview = 1;
                   3393:                     } else {
                   3394:                         $forceedit = 1;
                   3395:                     }
                   3396:                     $cfile = $resurl;
1.1199    raeburn  3397:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3398:                     $incourse = 1;
                   3399:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3400:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3401:                     $incourse = 1;
1.1199    raeburn  3402:                     if ($env{'form.forceedit'}) {
                   3403:                         $forceview = 1;
                   3404:                     } else {
                   3405:                         $forceedit = 1;
                   3406:                     }
                   3407:                     $cfile = $resurl;
1.1343    raeburn  3408:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3409:                     $incourse = 1;
                   3410:                     if ($env{'form.forceedit'}) {
                   3411:                         $forceview = 1;
                   3412:                     } else {
                   3413:                         $forceedit = 1;
                   3414:                     }
                   3415:                     $cfile = $resurl;
1.1208    raeburn  3416:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3417:                     $incourse = 1;
                   3418:                     if ($env{'form.forceedit'}) {
                   3419:                         $forceview = 1;
                   3420:                     } else {
                   3421:                         $forceedit = 1;
                   3422:                     }
                   3423:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3424:                 }
                   3425:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3426:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3427:                 if (&is_on_map($template)) { 
                   3428:                     $incourse = 1;
                   3429:                     $forceview = 1;
                   3430:                     $cfile = $template;
1.1193    raeburn  3431:                 }
1.1199    raeburn  3432:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3433:                     $incourse = 1;
                   3434:                     if ($env{'form.forceedit'}) {
                   3435:                         $forceview = 1;
                   3436:                     } else {
                   3437:                         $forceedit = 1;
                   3438:                     }
                   3439:                     $cfile = $resurl;
1.1343    raeburn  3440:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3441:                 $incourse = 1;
                   3442:                 if ($env{'form.forceedit'}) {
                   3443:                     $forceview = 1;
                   3444:                 } else {
                   3445:                     $forceedit = 1;
                   3446:                 }
                   3447:                 $cfile = $resurl;
1.1199    raeburn  3448:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3449:                 $incourse = 1;
                   3450:                 $forceview = 1;
                   3451:                 if ($symb) {
                   3452:                     my ($map,$id,$res)=&decode_symb($symb);
                   3453:                     $env{'request.symb'} = $symb;
                   3454:                     $cfile = &clutter($res);
                   3455:                 } else {
                   3456:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3457:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3458:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3459:                         $cfile = '/adm/wrapper'.$escfile;
                   3460:                     } else {
                   3461:                         $escfile =~ s{^http://}{};
                   3462:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3463:                     }
1.1199    raeburn  3464:                 }
1.1234    raeburn  3465:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3466:                 if ($env{'form.forceedit'}) {
                   3467:                     $forceview = 1;
                   3468:                 } else {
                   3469:                     $forceedit = 1;
                   3470:                 }
                   3471:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3472:             }
                   3473:         }
1.1194    raeburn  3474:         if ($uploaded || $incourse) {
                   3475:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3476:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3477:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3478:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3479:             # Check that the user has permission to edit this resource
                   3480:             my $setpriv = 1;
                   3481:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3482:             if (defined($cfudom)) {
                   3483:                 $home=&homeserver($cfuname,$cfudom);
                   3484:                 $cfile=$file;
                   3485:             }
                   3486:         }
1.1194    raeburn  3487:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3488:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3489:             my @ids=&current_machine_ids();
                   3490:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3491:                 $switchserver=1;
                   3492:             }
                   3493:         }
                   3494:     }
1.1194    raeburn  3495:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3496: }
                   3497: 
                   3498: sub is_course_upload {
                   3499:     my ($file,$cnum,$cdom) = @_;
                   3500:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3501:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3502:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3503:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3504:         return 1;
                   3505:     }
                   3506:     return;
                   3507: }
                   3508: 
1.1194    raeburn  3509: sub in_course {
1.1195    raeburn  3510:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3511:     if ($hideprivileged) {
                   3512:         my $skipuser;
1.1219    raeburn  3513:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3514:         my @possdoms = ($cdom);  
                   3515:         if ($coursehash{'checkforpriv'}) { 
                   3516:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3517:         }
                   3518:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3519:             $skipuser = 1;
                   3520:             if ($coursehash{'nothideprivileged'}) {
                   3521:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3522:                     my $user;
                   3523:                     if ($item =~ /:/) {
                   3524:                         $user = $item;
                   3525:                     } else {
                   3526:                         $user = join(':',split(/[\@]/,$item));
                   3527:                     }
                   3528:                     if ($user eq $uname.':'.$udom) {
                   3529:                         undef($skipuser);
                   3530:                         last;
                   3531:                     }
                   3532:                 }
                   3533:             }
                   3534:             if ($skipuser) {
                   3535:                 return 0;
                   3536:             }
                   3537:         }
                   3538:     }
1.1194    raeburn  3539:     $type ||= 'any';
                   3540:     if (!defined($cdom) || !defined($cnum)) {
                   3541:         my $cid  = $env{'request.course.id'};
                   3542:         $cdom = $env{'course.'.$cid.'.domain'};
                   3543:         $cnum = $env{'course.'.$cid.'.num'};
                   3544:     }
                   3545:     my $typesref;
1.1195    raeburn  3546:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3547:         $typesref = ['active','previous','future'];
                   3548:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3549:         $typesref = [$type];
                   3550:     }
                   3551:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3552:                               $typesref,undef,[$cdom]);
                   3553:     my ($tmp) = keys(%roles);
                   3554:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3555:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3556:     if (@course_roles > 0) {
                   3557:         return 1;
                   3558:     }
                   3559:     return 0;
                   3560: }
                   3561: 
1.478     albertel 3562: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3563: # input: action, courseID, current domain, intended
1.637     raeburn  3564: #        path to file, source of file, instruction to parse file for objects,
                   3565: #        ref to hash for embedded objects,
                   3566: #        ref to hash for codebase of java objects.
1.1095    raeburn  3567: #        reference to scalar to accommodate mime type determined
                   3568: #          from File::MMagic if $parser = parse.
1.637     raeburn  3569: #
1.485     raeburn  3570: # output: url to file (if action was uploaddoc), 
                   3571: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3572: #
1.478     albertel 3573: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3574: # course.
1.477     raeburn  3575: #
1.478     albertel 3576: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3577: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3578: #          course's home server.
1.477     raeburn  3579: #
1.478     albertel 3580: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3581: #          be copied from $source (current location) to 
                   3582: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3583: #         and will then be copied to
                   3584: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3585: #         course's home server.
1.485     raeburn  3586: #
1.481     raeburn  3587: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3588: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3589: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3590: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3591: #         in course's home server.
1.637     raeburn  3592: #
1.477     raeburn  3593: 
                   3594: sub process_coursefile {
1.1095    raeburn  3595:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3596:         $mimetype)=@_;
1.477     raeburn  3597:     my $fetchresult;
1.638     albertel 3598:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3599:     if ($action eq 'propagate') {
1.638     albertel 3600:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3601: 			     $home);
1.481     raeburn  3602:     } else {
1.477     raeburn  3603:         my $fpath = '';
                   3604:         my $fname = $file;
1.478     albertel 3605:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3606:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3607:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3608:         if ($action eq 'copy') {
                   3609:             if ($source eq '') {
                   3610:                 $fetchresult = 'no source file';
                   3611:                 return $fetchresult;
                   3612:             } else {
                   3613:                 my $destination = $filepath.'/'.$fname;
                   3614:                 rename($source,$destination);
                   3615:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3616:                                  $home);
1.481     raeburn  3617:             }
                   3618:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3619:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3620:             print $fh $env{'form.'.$source};
1.481     raeburn  3621:             close($fh);
1.637     raeburn  3622:             if ($parser eq 'parse') {
1.1024    raeburn  3623:                 my $mm = new File::MMagic;
1.1095    raeburn  3624:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3625:                 if ($type eq 'text/html') {
1.1024    raeburn  3626:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3627:                     unless ($parse_result eq 'ok') {
                   3628:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3629:                     }
1.637     raeburn  3630:                 }
1.1095    raeburn  3631:                 if (ref($mimetype)) {
                   3632:                     $$mimetype = $type;
                   3633:                 } 
1.637     raeburn  3634:             }
1.477     raeburn  3635:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3636:                                  $home);
1.481     raeburn  3637:             if ($fetchresult eq 'ok') {
                   3638:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3639:             } else {
                   3640:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3641:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3642:                 return '/adm/notfound.html';
                   3643:             }
1.477     raeburn  3644:         }
                   3645:     }
1.485     raeburn  3646:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3647:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3648:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3649:     }
                   3650:     return $fetchresult;
                   3651: }
                   3652: 
1.637     raeburn  3653: sub build_filepath {
                   3654:     my ($fpath) = @_;
                   3655:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3656:     unless ($fpath eq '') {
                   3657:         my @parts=split('/',$fpath);
                   3658:         foreach my $part (@parts) {
                   3659:             $filepath.= '/'.$part;
                   3660:             if ((-e $filepath)!=1) {
                   3661:                 mkdir($filepath,0777);
                   3662:             }
                   3663:         }
                   3664:     }
                   3665:     return $filepath;
                   3666: }
                   3667: 
                   3668: sub store_edited_file {
1.638     albertel 3669:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3670:     my $file = $primary_url;
                   3671:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3672:     my $fpath = '';
                   3673:     my $fname = $file;
                   3674:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3675:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3676:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3677:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3678:     print $fh $content;
                   3679:     close($fh);
1.638     albertel 3680:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3681:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3682: 			  $home);
1.637     raeburn  3683:     if ($$fetchresult eq 'ok') {
                   3684:         return '/uploaded/'.$fpath.'/'.$fname;
                   3685:     } else {
1.638     albertel 3686:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3687: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3688:         return '/adm/notfound.html';
                   3689:     }
                   3690: }
                   3691: 
1.531     albertel 3692: sub clean_filename {
1.831     albertel 3693:     my ($fname,$args)=@_;
1.315     www      3694: # Replace Windows backslashes by forward slashes
1.257     www      3695:     $fname=~s/\\/\//g;
1.831     albertel 3696:     if (!$args->{'keep_path'}) {
                   3697:         # Get rid of everything but the actual filename
                   3698: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3699:     }
1.315     www      3700: # Replace spaces by underscores
                   3701:     $fname=~s/\s+/\_/g;
                   3702: # Replace all other weird characters by nothing
1.831     albertel 3703:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3704: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3705: # numbers
                   3706:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3707:     return $fname;
                   3708: }
1.1051    raeburn  3709: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3710: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3711: # image with the same aspect ratio as the original, but with dimensions which do 
                   3712: # not exceed $resizewidth and $resizeheight.
                   3713:  
1.984     neumanie 3714: sub resizeImage {
1.1051    raeburn  3715:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3716:     my $ima = Image::Magick->new;
                   3717:     my $resized;
                   3718:     if (-e $img_path) {
                   3719:         $ima->Read($img_path);
                   3720:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3721:             my $width = $ima->Get('width');
                   3722:             my $height = $ima->Get('height');
                   3723:             if ($width > $resizewidth) {
                   3724: 	        my $factor = $width/$resizewidth;
                   3725:                 my $newheight = $height/$factor;
                   3726:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3727:                 $resized = 1;
                   3728:             }
                   3729:         }
                   3730:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3731:             my $width = $ima->Get('width');
                   3732:             my $height = $ima->Get('height');
                   3733:             if ($height > $resizeheight) {
                   3734:                 my $factor = $height/$resizeheight;
                   3735:                 my $newwidth = $width/$factor;
                   3736:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3737:                 $resized = 1;
                   3738:             }
                   3739:         }
                   3740:         if ($resized) {
                   3741:             $ima->Write($img_path);
                   3742:         }
                   3743:     }
                   3744:     return;
1.977     amueller 3745: }
                   3746: 
1.608     albertel 3747: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3748: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3749: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3750: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3751: #                                    canceloverwrite, or ''. 
                   3752: #                   if 'coursedoc': upload to the current course
                   3753: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3754: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3755: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3756: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3757: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3758: #        $allfiles - reference to hash for embedded objects
                   3759: #        $codebase - reference to hash for codebase of java objects
                   3760: #        $desuname - username for permanent storage of uploaded file
                   3761: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3762: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3763: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3764: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3765: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3766: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3767: #                    from File::MMagic.
1.858     raeburn  3768: # 
1.686     albertel 3769: # output: url of file in userspace, or error: <message> 
                   3770: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3771: 
1.531     albertel 3772: sub userfileupload {
1.1090    raeburn  3773:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3774:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3775:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3776:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3777:     $fname=&clean_filename($fname);
1.1090    raeburn  3778:     # See if there is anything left
1.257     www      3779:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3780:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3781:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3782:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3783:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3784:         my $now = time;
1.1090    raeburn  3785:         my $filepath;
1.1095    raeburn  3786:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3787:              $filepath = 'tmp/helprequests/'.$now;
                   3788:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3789:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3790:                          '_'.$env{'user.domain'}.'/pending';
                   3791:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3792:             my ($docuname,$docudom);
1.1350    raeburn  3793:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3794:                 $docudom = $destudom;
                   3795:             } else {
                   3796:                 $docudom = $env{'user.domain'};
                   3797:             }
1.1350    raeburn  3798:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3799:                 $docuname = $destuname;
                   3800:             } else {
                   3801:                 $docuname = $env{'user.name'};
                   3802:             }
                   3803:             if (exists($env{'form.group'})) {
                   3804:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3805:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3806:             }
                   3807:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3808:             if ($context eq 'canceloverwrite') {
                   3809:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3810:                 if (-e  $tempfile) {
                   3811:                     my @info = stat($tempfile);
                   3812:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3813:                         unlink($tempfile);
                   3814:                     }
                   3815:                 }
                   3816:                 return;
1.523     raeburn  3817:             }
                   3818:         }
1.1090    raeburn  3819:         # Create the directory if not present
1.741     raeburn  3820:         my @parts=split(/\//,$filepath);
                   3821:         my $fullpath = $perlvar{'lonDaemons'};
                   3822:         for (my $i=0;$i<@parts;$i++) {
                   3823:             $fullpath .= '/'.$parts[$i];
                   3824:             if ((-e $fullpath)!=1) {
                   3825:                 mkdir($fullpath,0777);
                   3826:             }
                   3827:         }
1.1359    raeburn  3828:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3829:         print $fh $env{'form.'.$formname};
                   3830:         close($fh);
1.1090    raeburn  3831:         if ($context eq 'existingfile') {
                   3832:             my @info = stat($fullpath.'/'.$fname);
                   3833:             return ($fullpath.'/'.$fname,$info[9]);
                   3834:         } else {
                   3835:             return $fullpath.'/'.$fname;
                   3836:         }
1.523     raeburn  3837:     }
1.995     raeburn  3838:     if ($subdir eq 'scantron') {
                   3839:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3840:     } else {
1.995     raeburn  3841:         $fname="$subdir/$fname";
                   3842:     }
1.1090    raeburn  3843:     if ($context eq 'coursedoc') {
1.638     albertel 3844: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3845: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3846:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3847:             return &finishuserfileupload($docuname,$docudom,
                   3848: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3849: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3850:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3851:         } else {
1.1218    raeburn  3852:             if ($env{'form.folder'}) {
                   3853:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3854:             }
1.638     albertel 3855:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3856: 				       $fname,$formname,$parser,
1.1095    raeburn  3857: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3858:         }
1.719     banghart 3859:     } elsif (defined($destuname)) {
                   3860:         my $docuname=$destuname;
                   3861:         my $docudom=$destudom;
1.860     raeburn  3862: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3863: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3864:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3865:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3866:     } else {
1.638     albertel 3867:         my $docuname=$env{'user.name'};
                   3868:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3869:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3870:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3871:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3872:         }
1.860     raeburn  3873: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3874: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3875:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3876:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3877:     }
1.271     www      3878: }
                   3879: 
                   3880: sub finishuserfileupload {
1.860     raeburn  3881:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3882:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3883:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3884:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3885:   
1.860     raeburn  3886:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3887:     $file=$fname;
                   3888:     if ($fname=~m|/|) {
                   3889:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3890: 	$path.=$fnamepath.'/';
                   3891:     }
1.259     www      3892:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3893:     my $count;
                   3894:     for ($count=4;$count<=$#parts;$count++) {
                   3895:         $filepath.="/$parts[$count]";
                   3896:         if ((-e $filepath)!=1) {
                   3897: 	    mkdir($filepath,0777);
                   3898:         }
                   3899:     }
1.984     neumanie 3900: 
1.258     www      3901: # Save the file
                   3902:     {
1.1359    raeburn  3903: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3904: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3905: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3906: 	    return '/adm/notfound.html';
                   3907: 	}
1.1090    raeburn  3908:         if ($context eq 'overwrite') {
1.1117    foxr     3909:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3910:             my $target = $filepath.'/'.$file;
                   3911:             if (-e $source) {
                   3912:                 my @info = stat($source);
                   3913:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3914:                     unless (&File::Copy::move($source,$target)) {
                   3915:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3916:                         return "Moving from $source failed";
                   3917:                     }
                   3918:                 } else {
                   3919:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3920:                 }
                   3921:             } else {
                   3922:                 return "Temporary file: $source missing";
                   3923:             }
                   3924:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3925: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3926: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3927: 	    return '/adm/notfound.html';
                   3928: 	}
1.570     albertel 3929: 	close(FH);
1.1051    raeburn  3930:         if ($resizewidth && $resizeheight) {
                   3931:             my $mm = new File::MMagic;
                   3932:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3933:             if ($mime_type =~ m{^image/}) {
                   3934: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3935:             }  
1.977     amueller 3936: 	}
1.258     www      3937:     }
1.1152    raeburn  3938:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3939:         if (ref($mimetype)) {
                   3940:             if ($$mimetype eq '') {
                   3941:                 my $mm = new File::MMagic;
                   3942:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3943:                 $$mimetype = $type;
                   3944:             }
                   3945:         }
                   3946:     }
1.637     raeburn  3947:     if ($parser eq 'parse') {
1.1152    raeburn  3948:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3949:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3950:                                                        $allfiles,$codebase);
                   3951:             unless ($parse_result eq 'ok') {
                   3952:                 &logthis('Failed to parse '.$filepath.$file.
                   3953: 	   	         ' for embedded media: '.$parse_result); 
                   3954:             }
1.637     raeburn  3955:         }
                   3956:     }
1.860     raeburn  3957:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3958:         my $input = $filepath.'/'.$file;
                   3959:         my $output = $filepath.'/'.'tn-'.$file;
                   3960:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  3961:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3962:         system({$args[0]} @args);
1.860     raeburn  3963:         if (-e $filepath.'/'.'tn-'.$file) {
                   3964:             $fetchthumb  = 1; 
                   3965:         }
                   3966:     }
1.858     raeburn  3967:  
1.259     www      3968: # Notify homeserver to grep it
                   3969: #
1.984     neumanie 3970:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3971:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3972:     if ($fetchresult eq 'ok') {
1.860     raeburn  3973:         if ($fetchthumb) {
                   3974:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3975:             if ($thumbresult ne 'ok') {
                   3976:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3977:                          $docuhome.': '.$thumbresult);
                   3978:             }
                   3979:         }
1.259     www      3980: #
1.258     www      3981: # Return the URL to it
1.494     albertel 3982:         return '/uploaded/'.$path.$file;
1.263     www      3983:     } else {
1.494     albertel 3984:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3985: 		 ': '.$fetchresult);
1.263     www      3986:         return '/adm/notfound.html';
1.858     raeburn  3987:     }
1.493     albertel 3988: }
                   3989: 
1.637     raeburn  3990: sub extract_embedded_items {
1.961     raeburn  3991:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3992:     my @state = ();
1.1164    raeburn  3993:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3994:     my %javafiles = (
                   3995:                       codebase => '',
                   3996:                       code => '',
                   3997:                       archive => ''
                   3998:                     );
                   3999:     my %mediafiles = (
                   4000:                       src => '',
                   4001:                       movie => '',
                   4002:                      );
1.648     raeburn  4003:     my $p;
                   4004:     if ($content) {
                   4005:         $p = HTML::LCParser->new($content);
                   4006:     } else {
1.961     raeburn  4007:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4008:     }
1.641     albertel 4009:     while (my $t=$p->get_token()) {
1.640     albertel 4010: 	if ($t->[0] eq 'S') {
                   4011: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4012: 	    push(@state, $tagname);
1.648     raeburn  4013:             if (lc($tagname) eq 'allow') {
                   4014:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4015:             }
1.640     albertel 4016: 	    if (lc($tagname) eq 'img') {
                   4017: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4018: 	    }
1.886     albertel 4019: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4020:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4021:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4022:                 }
1.886     albertel 4023: 	    }
1.645     raeburn  4024:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4025:                 my $src;
1.645     raeburn  4026:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4027:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4028:                 } else {
1.1164    raeburn  4029:                     if ($attr->{'src'} ne '') {
                   4030:                         $src = $attr->{'src'};
                   4031:                         &add_filetype($allfiles,$src,'src');
                   4032:                     }
                   4033:                 }
                   4034:                 my $text = $p->get_trimmed_text();
                   4035:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4036:                     my @swfargs = split(/,/,$1);
                   4037:                     foreach my $item (@swfargs) {
                   4038:                         $item =~ s/["']//g;
                   4039:                         $item =~ s/^\s+//;
                   4040:                         $item =~ s/\s+$//;
                   4041:                     }
                   4042:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4043:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4044:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4045:                         } else {
                   4046:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4047:                         }
                   4048:                     }
1.645     raeburn  4049:                 }
                   4050:             }
                   4051:             if (lc($tagname) eq 'link') {
                   4052:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4053:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4054:                 }
                   4055:             }
1.640     albertel 4056: 	    if (lc($tagname) eq 'object' ||
                   4057: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4058: 		foreach my $item (keys(%javafiles)) {
                   4059: 		    $javafiles{$item} = '';
                   4060: 		}
1.1164    raeburn  4061:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4062:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4063:                 }
1.640     albertel 4064: 	    }
                   4065: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4066: 		my $name = lc($attr->{'name'});
                   4067: 		foreach my $item (keys(%javafiles)) {
                   4068: 		    if ($name eq $item) {
                   4069: 			$javafiles{$item} = $attr->{'value'};
                   4070: 			last;
                   4071: 		    }
                   4072: 		}
1.1164    raeburn  4073:                 my $pathfrom;
1.640     albertel 4074: 		foreach my $item (keys(%mediafiles)) {
                   4075: 		    if ($name eq $item) {
1.1164    raeburn  4076:                         $pathfrom = $attr->{'value'};
                   4077:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4078: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4079: 			last;
                   4080: 		    }
                   4081: 		}
1.1164    raeburn  4082:                 if ($name eq 'flashvars') {
                   4083:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4084:                 }
                   4085:                 if ($pathfrom ne '') {
                   4086:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4087:                                          $pathfrom);
                   4088:                 }
1.640     albertel 4089: 	    }
                   4090: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4091: 		foreach my $item (keys(%javafiles)) {
                   4092: 		    if ($attr->{$item}) {
                   4093: 			$javafiles{$item} = $attr->{$item};
                   4094: 			last;
                   4095: 		    }
                   4096: 		}
                   4097: 		foreach my $item (keys(%mediafiles)) {
                   4098: 		    if ($attr->{$item}) {
                   4099: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4100: 			last;
                   4101: 		    }
                   4102: 		}
1.1164    raeburn  4103:                 if (lc($tagname) eq 'embed') {
                   4104:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4105:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4106:                                              $attr->{'src'});
                   4107:                     }
                   4108:                 }
1.640     albertel 4109: 	    }
1.1243    raeburn  4110:             if (lc($tagname) eq 'iframe') {
                   4111:                 my $src = $attr->{'src'} ;
                   4112:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4113:                     &add_filetype($allfiles,$src,'src');
                   4114:                 } elsif ($src =~ m{^/}) {
                   4115:                     if ($env{'request.course.id'}) {
                   4116:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4117:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4118:                         my $url = &hreflocation('',$fullpath);
                   4119:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4120:                             my $relpath = $1;
                   4121:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4122:                                 &add_filetype($allfiles,$1,'src');
                   4123:                             }
                   4124:                         }
                   4125:                     }
                   4126:                 }
                   4127:             }
1.1164    raeburn  4128:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4129:                 pop(@state);
1.1164    raeburn  4130:             }
1.640     albertel 4131: 	} elsif ($t->[0] eq 'E') {
                   4132: 	    my ($tagname) = ($t->[1]);
                   4133: 	    if ($javafiles{'codebase'} ne '') {
                   4134: 		$javafiles{'codebase'} .= '/';
                   4135: 	    }  
                   4136: 	    if (lc($tagname) eq 'applet' ||
                   4137: 		lc($tagname) eq 'object' ||
                   4138: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4139: 		) {
                   4140: 		foreach my $item (keys(%javafiles)) {
                   4141: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4142: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4143: 			&add_filetype($allfiles,$file,$item);
                   4144: 		    }
                   4145: 		}
                   4146: 	    } 
                   4147: 	    pop @state;
                   4148: 	}
                   4149:     }
1.1164    raeburn  4150:     foreach my $id (sort(keys(%flashvars))) {
                   4151:         if ($shockwave{$id} ne '') {
                   4152:             my @pairs = split(/\&/,$flashvars{$id});
                   4153:             foreach my $pair (@pairs) {
                   4154:                 my ($key,$value) = split(/\=/,$pair);
                   4155:                 if ($key eq 'thumb') {
                   4156:                     &add_filetype($allfiles,$value,$key);
                   4157:                 } elsif ($key eq 'content') {
                   4158:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4159:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4160:                     if ($ext ne '') {
                   4161:                         &add_filetype($allfiles,$path.$value,$ext);
                   4162:                     }
                   4163:                 }
                   4164:             }
                   4165:         }
                   4166:     }
1.637     raeburn  4167:     return 'ok';
                   4168: }
                   4169: 
1.639     albertel 4170: sub add_filetype {
                   4171:     my ($allfiles,$file,$type)=@_;
                   4172:     if (exists($allfiles->{$file})) {
                   4173: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4174: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4175: 	}
                   4176:     } else {
                   4177: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4178:     }
                   4179: }
                   4180: 
1.1164    raeburn  4181: sub embedded_dependency {
                   4182:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4183:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4184:         if (($identifier ne '') &&
                   4185:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4186:             ($pathfrom ne '')) {
                   4187:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4188:             foreach my $dep (@{$related->{$identifier}}) {
                   4189:                 &add_filetype($allfiles,$path.$dep,'object');
                   4190:             }
                   4191:         }
                   4192:     }
                   4193:     return;
                   4194: }
                   4195: 
1.493     albertel 4196: sub removeuploadedurl {
1.984     neumanie 4197:     my ($url)=@_;	
                   4198:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4199:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4200: }
                   4201: 
                   4202: sub removeuserfile {
                   4203:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4204:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4205:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4206:     if ($result eq 'ok') {	
1.798     raeburn  4207:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4208:             my $metafile = $fname.'.meta';
                   4209:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4210: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4211:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4212:             my $sqlresult = 
1.823     albertel 4213:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4214:                                         'portfolio_metadata',$group,
                   4215:                                         'delete');
1.798     raeburn  4216:         }
                   4217:     }
                   4218:     return $result;
1.257     www      4219: }
1.15      www      4220: 
1.530     albertel 4221: sub mkdiruserfile {
                   4222:     my ($docuname,$docudom,$dir)=@_;
                   4223:     my $home=&homeserver($docuname,$docudom);
                   4224:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4225: }
                   4226: 
1.531     albertel 4227: sub renameuserfile {
                   4228:     my ($docuname,$docudom,$old,$new)=@_;
                   4229:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4230:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4231:                         &escape("$old").':'.&escape("$new"),$home);
                   4232:     if ($result eq 'ok') {
                   4233:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4234:             my $oldmeta = $old.'.meta';
                   4235:             my $newmeta = $new.'.meta';
                   4236:             my $metaresult = 
                   4237:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4238: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4239:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4240:             my $sqlresult = 
1.823     albertel 4241:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4242:                                         'portfolio_metadata',$group,
                   4243:                                         'delete');
1.798     raeburn  4244:         }
                   4245:     }
                   4246:     return $result;
1.531     albertel 4247: }
                   4248: 
1.14      www      4249: # ------------------------------------------------------------------------- Log
                   4250: 
                   4251: sub log {
                   4252:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4253:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4254: }
                   4255: 
                   4256: # ------------------------------------------------------------------ Course Log
1.352     www      4257: #
                   4258: # This routine flushes several buffers of non-mission-critical nature
                   4259: #
1.157     www      4260: 
                   4261: sub flushcourselogs {
1.352     www      4262:     &logthis('Flushing log buffers');
                   4263: #
                   4264: # course logs
                   4265: # This is a log of all transactions in a course, which can be used
                   4266: # for data mining purposes
                   4267: #
                   4268: # It also collects the courseid database, which lists last transaction
                   4269: # times and course titles for all courseids
                   4270: #
                   4271:     my %courseidbuffer=();
1.921     raeburn  4272:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4273:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4274: 		          &escape($courselogs{$crsid}),
                   4275: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4276: 	    delete $courselogs{$crsid};
                   4277:         } else {
                   4278:             &logthis('Failed to flush log buffer for '.$crsid);
                   4279:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4280:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4281:                         " exceeded maximum size, deleting.</font>");
                   4282:                delete $courselogs{$crsid};
                   4283:             }
1.352     www      4284:         }
1.920     raeburn  4285:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4286:             'description' => $coursedescrbuf{$crsid},
                   4287:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4288:             'type'        => $coursetypebuf{$crsid},
                   4289:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4290:         };
1.191     harris41 4291:     }
1.352     www      4292: #
                   4293: # Write course id database (reverse lookup) to homeserver of courses 
                   4294: # Is used in pickcourse
                   4295: #
1.840     albertel 4296:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4297:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4298:                                     $courseidbuffer{$crs_home},
                   4299:                                     $crs_home,'timeonly');
1.352     www      4300:     }
                   4301: #
                   4302: # File accesses
                   4303: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4304: #
1.449     matthew  4305:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4306:         if ($entry =~ /___count$/) {
                   4307:             my ($dom,$name);
1.807     albertel 4308:             ($dom,$name,undef)=
1.811     albertel 4309: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4310:             if (! defined($dom) || $dom eq '' || 
                   4311:                 ! defined($name) || $name eq '') {
1.620     albertel 4312:                 my $cid = $env{'request.course.id'};
                   4313:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4314:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4315:             }
1.450     matthew  4316:             my $value = $accesshash{$entry};
                   4317:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4318:             my %temphash=($url => $value);
1.449     matthew  4319:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4320:             if ($result eq 'ok') {
                   4321:                 delete $accesshash{$entry};
                   4322:             }
                   4323:         } else {
1.811     albertel 4324:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4325:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4326:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4327:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4328:                 delete $accesshash{$entry};
                   4329:             }
1.185     www      4330:         }
1.191     harris41 4331:     }
1.352     www      4332: #
                   4333: # Roles
                   4334: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4335: #
1.800     albertel 4336:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4337:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4338: 	    split(/\:/,$entry);
                   4339:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4340:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4341:                 $rudom,$runame) eq 'ok') {
                   4342: 	    delete $userrolehash{$entry};
                   4343:         }
                   4344:     }
1.662     raeburn  4345: #
1.1334    raeburn  4346: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4347: #
                   4348:     my %domrolebuffer = ();
1.1000    raeburn  4349:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4350:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4351:         if ($domrolebuffer{$rudom}) {
                   4352:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4353:                       '='.&escape($domainrolehash{$entry});
                   4354:         } else {
                   4355:             $domrolebuffer{$rudom}.=&escape($entry).
                   4356:                       '='.&escape($domainrolehash{$entry});
                   4357:         }
                   4358:         delete $domainrolehash{$entry};
                   4359:     }
                   4360:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4361: 	my %servers;
                   4362: 	if (defined(&domain($dom,'primary'))) {
                   4363: 	    my $primary=&domain($dom,'primary');
                   4364: 	    my $hostname=&hostname($primary);
                   4365: 	    $servers{$primary} = $hostname;
                   4366: 	} else { 
                   4367: 	    %servers = &get_servers($dom,'library');
                   4368: 	}
1.841     albertel 4369: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4370: 	    if (&reply('domroleput:'.$dom.':'.
                   4371: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4372: 		last;
                   4373: 	    } else {  
1.841     albertel 4374: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4375: 	    }
1.662     raeburn  4376:         }
                   4377:     }
1.186     www      4378:     $dumpcount++;
1.157     www      4379: }
                   4380: 
                   4381: sub courselog {
                   4382:     my $what=shift;
1.158     www      4383:     $what=time.':'.$what;
1.620     albertel 4384:     unless ($env{'request.course.id'}) { return ''; }
                   4385:     $coursedombuf{$env{'request.course.id'}}=
                   4386:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4387:     $coursenumbuf{$env{'request.course.id'}}=
                   4388:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4389:     $coursehombuf{$env{'request.course.id'}}=
                   4390:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4391:     $coursedescrbuf{$env{'request.course.id'}}=
                   4392:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4393:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4394:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4395:     $courseownerbuf{$env{'request.course.id'}}=
                   4396:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4397:     $coursetypebuf{$env{'request.course.id'}}=
                   4398:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4399:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4400: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4401:     } else {
1.620     albertel 4402: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4403:     }
1.620     albertel 4404:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4405: 	&flushcourselogs();
                   4406:     }
1.158     www      4407: }
                   4408: 
                   4409: sub courseacclog {
                   4410:     my $fnsymb=shift;
1.620     albertel 4411:     unless ($env{'request.course.id'}) { return ''; }
                   4412:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4413:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4414:         $what.=':POST';
1.583     matthew  4415:         # FIXME: Probably ought to escape things....
1.800     albertel 4416: 	foreach my $key (keys(%env)) {
                   4417:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4418:                 my $formitem = $1;
                   4419:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4420:                     $what.=':'.$formitem.'='.$env{$key};
                   4421:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4422:                     $what.=':'.$formitem.'='.$env{$key};
                   4423:                 }
1.158     www      4424:             }
1.191     harris41 4425:         }
1.583     matthew  4426:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4427:         # FIXME: We should not be depending on a form parameter that someone
                   4428:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4429:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4430:             $what.= ':POST';
                   4431:             # FIXME: Probably ought to escape things....
                   4432:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4433:                                  'crsdiscuss') {
1.620     albertel 4434:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4435:             }
                   4436:         }
1.158     www      4437:     }
                   4438:     &courselog($what);
1.149     www      4439: }
                   4440: 
1.185     www      4441: sub countacc {
                   4442:     my $url=&declutter(shift);
1.458     matthew  4443:     return if (! defined($url) || $url eq '');
1.620     albertel 4444:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4445: #
                   4446: # Mark that this url was used in this course
                   4447: #
1.620     albertel 4448:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4449: #
                   4450: # Increase the access count for this resource in this child process
                   4451: #
1.281     www      4452:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4453:     $accesshash{$key}++;
1.185     www      4454: }
1.349     www      4455: 
1.361     www      4456: sub linklog {
                   4457:     my ($from,$to)=@_;
                   4458:     $from=&declutter($from);
                   4459:     $to=&declutter($to);
                   4460:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4461:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4462: }
1.1160    www      4463: 
                   4464: sub statslog {
                   4465:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4466:     if ($users<2) { return; }
                   4467:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4468:             'course'       => $env{'request.course.id'},
                   4469:             'sections'     => '"all"',
                   4470:             'num_students' => $users,
                   4471:             'part'         => $part,
                   4472:             'symb'         => $symb,
                   4473:             'mean_tries'   => $av_attempts,
                   4474:             'deg_of_diff'  => $degdiff});
                   4475:     foreach my $key (keys(%dynstore)) {
                   4476:         $accesshash{$key}=$dynstore{$key};
                   4477:     }
                   4478: }
1.361     www      4479:   
1.349     www      4480: sub userrolelog {
                   4481:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4482:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4483:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4484:        $userrolehash
                   4485:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4486:                     =$tend.':'.$tstart;
1.662     raeburn  4487:     }
1.1169    droeschl 4488:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4489:        $userrolehash
                   4490:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4491:                     =$tend.':'.$tstart;
                   4492:     }
1.1334    raeburn  4493:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4494:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4495:        $domainrolehash
                   4496:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4497:                     = $tend.':'.$tstart;
                   4498:     }
1.351     www      4499: }
                   4500: 
1.957     raeburn  4501: sub courserolelog {
                   4502:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4503:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4504:         my $cdom = $1;
                   4505:         my $cnum = $2;
                   4506:         my $sec = $3;
                   4507:         my $namespace = 'rolelog';
                   4508:         my %storehash = (
                   4509:                            role    => $trole,
                   4510:                            start   => $tstart,
                   4511:                            end     => $tend,
                   4512:                            selfenroll => $selfenroll,
                   4513:                            context    => $context,
                   4514:                         );
                   4515:         if ($trole eq 'gr') {
                   4516:             $namespace = 'groupslog';
                   4517:             $storehash{'group'} = $sec;
                   4518:         } else {
                   4519:             $storehash{'section'} = $sec;
                   4520:         }
1.1188    raeburn  4521:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4522:                    $domain,$cnum,$cdom);
1.1184    raeburn  4523:         if (($trole ne 'st') || ($sec ne '')) {
                   4524:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4525:         }
                   4526:     }
                   4527:     return;
                   4528: }
                   4529: 
1.1184    raeburn  4530: sub domainrolelog {
                   4531:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4532:     if ($area =~ m{^/($match_domain)/$}) {
                   4533:         my $cdom = $1;
                   4534:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4535:         my $namespace = 'rolelog';
                   4536:         my %storehash = (
                   4537:                            role    => $trole,
                   4538:                            start   => $tstart,
                   4539:                            end     => $tend,
                   4540:                            context => $context,
                   4541:                         );
1.1188    raeburn  4542:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4543:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4544:     }
                   4545:     return;
                   4546: 
                   4547: }
                   4548: 
                   4549: sub coauthorrolelog {
                   4550:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4551:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4552:         my $audom = $1;
                   4553:         my $auname = $2;
                   4554:         my $namespace = 'rolelog';
                   4555:         my %storehash = (
                   4556:                            role    => $trole,
                   4557:                            start   => $tstart,
                   4558:                            end     => $tend,
                   4559:                            context => $context,
                   4560:                         );
1.1188    raeburn  4561:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4562:                    $domain,$auname,$audom);
1.1184    raeburn  4563:     }
                   4564:     return;
                   4565: }
                   4566: 
1.351     www      4567: sub get_course_adv_roles {
1.948     raeburn  4568:     my ($cid,$codes) = @_;
1.620     albertel 4569:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4570:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4571:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4572:     my %nothide=();
1.800     albertel 4573:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4574:         if ($user !~ /:/) {
                   4575: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4576:         } else {
                   4577:             $nothide{$user}=1;
                   4578:         }
1.470     www      4579:     }
1.1219    raeburn  4580:     my @possdoms = ($coursehash{'domain'});
                   4581:     if ($coursehash{'checkforpriv'}) {
                   4582:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4583:     }
1.351     www      4584:     my %returnhash=();
                   4585:     my %dumphash=
                   4586:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4587:     my $now=time;
1.997     raeburn  4588:     my %privileged;
1.1000    raeburn  4589:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4590: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4591:         if (($tstart) && ($tstart<0)) { next; }
                   4592:         if (($tend) && ($tend<$now)) { next; }
                   4593:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4594:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4595: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4596:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4597:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4598: 	if ($role eq 'cr') { next; }
1.948     raeburn  4599:         if ($codes) {
                   4600:             if ($section) { $role .= ':'.$section; }
                   4601:             if ($returnhash{$role}) {
                   4602:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4603:             } else {
                   4604:                 $returnhash{$role}=$username.':'.$domain;
                   4605:             }
1.351     www      4606:         } else {
1.988     raeburn  4607:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4608:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4609:             if ($returnhash{$key}) {
                   4610: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4611:             } else {
                   4612:                 $returnhash{$key}=$username.':'.$domain;
                   4613:             }
1.351     www      4614:         }
1.948     raeburn  4615:     }
1.400     www      4616:     return %returnhash;
                   4617: }
                   4618: 
                   4619: sub get_my_roles {
1.937     raeburn  4620:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4621:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4622:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4623:     my (%dumphash,%nothide);
1.1086    raeburn  4624:     if ($context eq 'userroles') {
1.1166    raeburn  4625:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4626:     } else {
1.1219    raeburn  4627:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4628:         if ($hidepriv) {
                   4629:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4630:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4631:                 if ($user !~ /:/) {
                   4632:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4633:                 } else {
                   4634:                     $nothide{$user} = 1;
                   4635:                 }
                   4636:             }
                   4637:         }
1.858     raeburn  4638:     }
1.400     www      4639:     my %returnhash=();
                   4640:     my $now=time;
1.999     raeburn  4641:     my %privileged;
1.800     albertel 4642:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4643:         my ($role,$tend,$tstart);
                   4644:         if ($context eq 'userroles') {
1.1149    raeburn  4645:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4646: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4647:         } else {
                   4648:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4649:         }
1.400     www      4650:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4651:         my $status = 'active';
1.939     raeburn  4652:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4653:             $status = 'previous';
                   4654:         } 
                   4655:         if (($tstart) && ($now<$tstart)) {
                   4656:             $status = 'future';
                   4657:         }
                   4658:         if (ref($types) eq 'ARRAY') {
                   4659:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4660:                 next;
                   4661:             } 
                   4662:         } else {
                   4663:             if ($status ne 'active') {
                   4664:                 next;
                   4665:             }
                   4666:         }
1.867     raeburn  4667:         my ($rolecode,$username,$domain,$section,$area);
                   4668:         if ($context eq 'userroles') {
1.1186    raeburn  4669:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4670:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4671:         } else {
                   4672:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4673:         }
1.832     raeburn  4674:         if (ref($roledoms) eq 'ARRAY') {
                   4675:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4676:                 next;
                   4677:             }
                   4678:         }
                   4679:         if (ref($roles) eq 'ARRAY') {
                   4680:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4681:                 if ($role =~ /^cr\//) {
                   4682:                     if (!grep(/^cr$/,@{$roles})) {
                   4683:                         next;
                   4684:                     }
1.1104    raeburn  4685:                 } elsif ($role =~ /^gr\//) {
                   4686:                     if (!grep(/^gr$/,@{$roles})) {
                   4687:                         next;
                   4688:                     }
1.922     raeburn  4689:                 } else {
                   4690:                     next;
                   4691:                 }
1.832     raeburn  4692:             }
1.867     raeburn  4693:         }
1.937     raeburn  4694:         if ($hidepriv) {
1.1219    raeburn  4695:             my @privroles = ('dc','su');
1.999     raeburn  4696:             if ($context eq 'userroles') {
1.1219    raeburn  4697:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4698:             } else {
1.1219    raeburn  4699:                 my $possdoms = [$domain];
                   4700:                 if (ref($roledoms) eq 'ARRAY') {
                   4701:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4702:                 }
1.1219    raeburn  4703:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4704:                     if (!$nothide{$username.':'.$domain}) {
                   4705:                         next;
                   4706:                     }
                   4707:                 }
1.937     raeburn  4708:             }
                   4709:         }
1.933     raeburn  4710:         if ($withsec) {
                   4711:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4712:                 $tstart.':'.$tend;
                   4713:         } else {
                   4714:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4715:         }
1.832     raeburn  4716:     }
1.373     www      4717:     return %returnhash;
1.399     www      4718: }
                   4719: 
1.1333    raeburn  4720: sub get_all_adhocroles {
                   4721:     my ($dom) = @_;
                   4722:     my @roles_by_num = ();
                   4723:     my %domdefaults = &get_domain_defaults($dom);
                   4724:     my (%description,%access_in_dom,%access_info);
                   4725:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4726:         my $count = 0;
                   4727:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4728:         my %ordered;
                   4729:         foreach my $role (sort(keys(%domcurrent))) {
                   4730:             my ($order,$desc,$access_in_dom);
                   4731:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4732:                 $order = $domcurrent{$role}{'order'};
                   4733:                 $desc = $domcurrent{$role}{'desc'};
                   4734:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4735:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4736:             }
                   4737:             if ($order eq '') {
                   4738:                 $order = $count;
                   4739:             }
                   4740:             $ordered{$order} = $role;
                   4741:             if ($desc ne '') {
                   4742:                 $description{$role} = $desc;
                   4743:             } else {
                   4744:                 $description{$role}= $role;
                   4745:             }
                   4746:             $count++;
                   4747:         }
                   4748:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4749:             push(@roles_by_num,$ordered{$item});
                   4750:         }
                   4751:     }
                   4752:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4753: }
                   4754: 
1.1332    raeburn  4755: sub get_my_adhocroles {
1.1333    raeburn  4756:     my ($cid,$checkreg) = @_;
                   4757:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4758:     if ($env{'request.course.id'} eq $cid) {
                   4759:         $cdom = $env{'course.'.$cid.'.domain'};
                   4760:         $cnum = $env{'course.'.$cid.'.num'};
                   4761:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4762:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4763:         $cdom = $1;
                   4764:         $cnum = $2;
                   4765:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4766:                                      $cdom,$cnum);
                   4767:     }
                   4768:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4769:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4770:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4771:         if ($rosterhash{$user} ne '') {
                   4772:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4773:             return ([],{}) if ($type eq 'auto');
                   4774:         }
                   4775:     }
                   4776:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4777:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4778:             my $then=$env{'user.login.time'};
                   4779:             my $update=$env{'user.update.time'};
1.1335    raeburn  4780:             if (!$update) {
                   4781:                 $update = $then;
                   4782:             }
                   4783:             my @liveroles;
1.1334    raeburn  4784:             foreach my $role ('dh','da') {
                   4785:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4786:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4787:                     my $limit = $update;
                   4788:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4789:                         $limit = $then;
                   4790:                     }
1.1335    raeburn  4791:                     my $activerole = 1;
                   4792:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4793:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4794:                     if ($activerole) {
                   4795:                         push(@liveroles,$role);
                   4796:                     }
1.1334    raeburn  4797:                 }
1.1332    raeburn  4798:             }
1.1335    raeburn  4799:             if (@liveroles) {
1.1332    raeburn  4800:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4801:                     my ($accessref,$accessinfo,%access_in_dom);
                   4802:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4803:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4804:                         if (@{$roles_by_num}) {
1.1332    raeburn  4805:                             my %settings;
                   4806:                             if ($env{'request.course.id'} eq $cid) {
                   4807:                                 foreach my $envkey (keys(%env)) {
                   4808:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4809:                                         $settings{$1} = $env{$envkey};
                   4810:                                     }
                   4811:                                 }
                   4812:                             } else {
                   4813:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4814:                             }
                   4815:                             my %setincrs;
                   4816:                             if ($settings{'internal.adhocaccess'}) {
                   4817:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4818:                             }
                   4819:                             my @statuses;
                   4820:                             if ($env{'environment.inststatus'}) {
                   4821:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4822:                             }
                   4823:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4824:                             if (ref($accessref) eq 'HASH') {
                   4825:                                 %access_in_dom = %{$accessref};
                   4826:                             }
                   4827:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4828:                                 my ($curraccess,@okstatus,@personnel);
                   4829:                                 if ($setincrs{$role}) {
                   4830:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4831:                                     if ($curraccess eq 'status') {
                   4832:                                         @okstatus = split(/\&/,$rest);
                   4833:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4834:                                         @personnel = split(/\&/,$rest);
                   4835:                                     }
                   4836:                                 } else {
                   4837:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4838:                                     if (ref($accessinfo) eq 'HASH') {
                   4839:                                         if ($curraccess eq 'status') {
                   4840:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4841:                                                 @okstatus = @{$accessinfo->{$role}};
                   4842:                                             }
                   4843:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4844:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4845:                                                 @personnel = @{$accessinfo->{$role}};
                   4846:                                             }
1.1332    raeburn  4847:                                         }
                   4848:                                     }
                   4849:                                 }
                   4850:                                 if ($curraccess eq 'none') {
                   4851:                                     next;
                   4852:                                 } elsif ($curraccess eq 'all') {
                   4853:                                     push(@possroles,$role);
1.1336    raeburn  4854:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4855:                                     if (grep(/^dh$/,@liveroles)) {
                   4856:                                         push(@possroles,$role);
                   4857:                                     } else {
                   4858:                                         next;
                   4859:                                     }
1.1336    raeburn  4860:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4861:                                     if (grep(/^da$/,@liveroles)) {
                   4862:                                         push(@possroles,$role);
                   4863:                                     } else {
                   4864:                                         next;
                   4865:                                     }
1.1332    raeburn  4866:                                 } elsif ($curraccess eq 'status') {
                   4867:                                     if (@okstatus) {
                   4868:                                         if (!@statuses) {
                   4869:                                             if (grep(/^default$/,@okstatus)) {
                   4870:                                                 push(@possroles,$role);
                   4871:                                             }
                   4872:                                         } else {
                   4873:                                             foreach my $status (@okstatus) {
                   4874:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4875:                                                     push(@possroles,$role);
                   4876:                                                     last;
                   4877:                                                 }
                   4878:                                             }
                   4879:                                         }
                   4880:                                     }
                   4881:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4882:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4883:                                         if ($curraccess eq 'exc') {
                   4884:                                             push(@possroles,$role);
                   4885:                                         }
                   4886:                                     } elsif ($curraccess eq 'inc') {
                   4887:                                         push(@possroles,$role);
                   4888:                                     }
                   4889:                                 }
                   4890:                             }
                   4891:                         }
                   4892:                     }
                   4893:                 }
                   4894:             }
                   4895:         }
                   4896:     }
1.1333    raeburn  4897:     unless (ref($description) eq 'HASH') {
                   4898:         if (ref($roles_by_num) eq 'ARRAY') {
                   4899:             my %desc;
                   4900:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4901:             $description = \%desc;
                   4902:         } else {
                   4903:             $description = {};
                   4904:         }
                   4905:     }
                   4906:     return (\@possroles,$description);
1.1332    raeburn  4907: }
                   4908: 
1.399     www      4909: # ----------------------------------------------------- Frontpage Announcements
                   4910: #
                   4911: #
                   4912: 
                   4913: sub postannounce {
                   4914:     my ($server,$text)=@_;
1.844     albertel 4915:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4916:     unless ($text=~/\w/) { $text=''; }
                   4917:     return &reply('setannounce:'.&escape($text),$server);
                   4918: }
                   4919: 
                   4920: sub getannounce {
1.448     albertel 4921: 
1.1359    raeburn  4922:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4923: 	my $announcement='';
1.800     albertel 4924: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4925: 	close($fh);
1.399     www      4926: 	if ($announcement=~/\w/) { 
                   4927: 	    return 
                   4928:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4929:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4930: 	} else {
                   4931: 	    return '';
                   4932: 	}
                   4933:     } else {
                   4934: 	return '';
                   4935:     }
1.351     www      4936: }
1.353     www      4937: 
                   4938: # ---------------------------------------------------------- Course ID routines
                   4939: # Deal with domain's nohist_courseid.db files
                   4940: #
                   4941: 
                   4942: sub courseidput {
1.921     raeburn  4943:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4944:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4945:     my $outcome;
                   4946:     if ($caller eq 'timeonly') {
                   4947:         my $cids = '';
                   4948:         foreach my $item (keys(%$storehash)) {
                   4949:             $cids.=&escape($item).'&';
                   4950:         }
                   4951:         $cids=~s/\&$//;
                   4952:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4953:                           $coursehome);       
                   4954:     } else {
                   4955:         my $items = '';
                   4956:         foreach my $item (keys(%$storehash)) {
                   4957:             $items.= &escape($item).'='.
                   4958:                      &freeze_escape($$storehash{$item}).'&';
                   4959:         }
                   4960:         $items=~s/\&$//;
                   4961:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4962:                           $coursehome);
1.918     raeburn  4963:     }
                   4964:     if ($outcome eq 'unknown_cmd') {
                   4965:         my $what;
                   4966:         foreach my $cid (keys(%$storehash)) {
                   4967:             $what .= &escape($cid).'=';
1.921     raeburn  4968:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4969:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4970:             }
                   4971:             $what =~ s/\:$/&/;
                   4972:         }
                   4973:         $what =~ s/\&$//;  
                   4974:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4975:     } else {
                   4976:         return $outcome;
                   4977:     }
1.353     www      4978: }
                   4979: 
                   4980: sub courseiddump {
1.921     raeburn  4981:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4982:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4983:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4984:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4985:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4986:     my $as_hash = 1;
                   4987:     my %returnhash;
                   4988:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4989:     my %libserv = &all_library();
                   4990:     foreach my $tryserver (keys(%libserv)) {
                   4991:         if ( (  $hostidflag == 1 
                   4992: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4993: 	     || (!defined($hostidflag)) ) {
                   4994: 
1.918     raeburn  4995: 	    if (($domfilter eq '') ||
                   4996: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4997:                 my $rep;
                   4998:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4999:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5000:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5001:                                 &escape($descfilter), &escape($instcodefilter), 
                   5002:                                 &escape($ownerfilter), &escape($coursefilter),
                   5003:                                 &escape($typefilter), &escape($regexp_ok), 
                   5004:                                 $as_hash, &escape($selfenrollonly), 
                   5005:                                 &escape($catfilter), $showhidden, $caller, 
                   5006:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5007:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5008:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5009:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5010:                 } else {
                   5011:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5012:                              $sincefilter.':'.&escape($descfilter).':'.
                   5013:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5014:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5015:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5016:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5017:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5018:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5019:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5020:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5021:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5022:                 }
                   5023:                      
1.918     raeburn  5024:                 my @pairs=split(/\&/,$rep);
                   5025:                 foreach my $item (@pairs) {
                   5026:                     my ($key,$value)=split(/\=/,$item,2);
                   5027:                     $key = &unescape($key);
                   5028:                     next if ($key =~ /^error: 2 /);
                   5029:                     my $result = &thaw_unescape($value);
                   5030:                     if (ref($result) eq 'HASH') {
                   5031:                         $returnhash{$key}=$result;
                   5032:                     } else {
1.921     raeburn  5033:                         my @responses = split(/:/,$value);
                   5034:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5035:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5036:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5037:                         }
1.1008    raeburn  5038:                     }
1.353     www      5039:                 }
                   5040:             }
                   5041:         }
                   5042:     }
                   5043:     return %returnhash;
                   5044: }
                   5045: 
1.1055    raeburn  5046: sub courselastaccess {
                   5047:     my ($cdom,$cnum,$hostidref) = @_;
                   5048:     my %returnhash;
                   5049:     if ($cdom && $cnum) {
                   5050:         my $chome = &homeserver($cnum,$cdom);
                   5051:         if ($chome ne 'no_host') {
                   5052:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5053:             &extract_lastaccess(\%returnhash,$rep);
                   5054:         }
                   5055:     } else {
                   5056:         if (!$cdom) { $cdom=''; }
                   5057:         my %libserv = &all_library();
                   5058:         foreach my $tryserver (keys(%libserv)) {
                   5059:             if (ref($hostidref) eq 'ARRAY') {
                   5060:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5061:             } 
                   5062:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5063:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5064:                 &extract_lastaccess(\%returnhash,$rep);
                   5065:             }
                   5066:         }
                   5067:     }
                   5068:     return %returnhash;
                   5069: }
                   5070: 
                   5071: sub extract_lastaccess {
                   5072:     my ($returnhash,$rep) = @_;
                   5073:     if (ref($returnhash) eq 'HASH') {
                   5074:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5075:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5076:                  $rep eq '') {
                   5077:             my @pairs=split(/\&/,$rep);
                   5078:             foreach my $item (@pairs) {
                   5079:                 my ($key,$value)=split(/\=/,$item,2);
                   5080:                 $key = &unescape($key);
                   5081:                 next if ($key =~ /^error: 2 /);
                   5082:                 $returnhash->{$key} = &thaw_unescape($value);
                   5083:             }
                   5084:         }
                   5085:     }
                   5086:     return;
                   5087: }
                   5088: 
1.658     raeburn  5089: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5090: 
                   5091: sub dcmailput {
1.685     raeburn  5092:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5093:     my $status = &Apache::lonnet::critical(
1.740     www      5094:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5095:        &escape($message),$server);
1.662     raeburn  5096:     return $status;
                   5097: }
                   5098: 
1.658     raeburn  5099: sub dcmaildump {
                   5100:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5101:     my %returnhash=();
1.846     albertel 5102: 
                   5103:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5104:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5105:                                                          &escape($enddate).':';
                   5106: 	my @esc_senders=map { &escape($_)} @$senders;
                   5107: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5108: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5109:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5110:             if (($key) && ($value)) {
                   5111:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5112:             }
                   5113:         }
                   5114:     }
                   5115:     return %returnhash;
                   5116: }
1.662     raeburn  5117: # ---------------------------------------------------------- Domain roles
                   5118: 
                   5119: sub get_domain_roles {
                   5120:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5121:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5122:         $startdate = '.';
                   5123:     }
1.1018    raeburn  5124:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5125:         $enddate = '.';
                   5126:     }
1.922     raeburn  5127:     my $rolelist;
                   5128:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5129:         $rolelist = join('&',@{$roles});
1.922     raeburn  5130:     }
1.662     raeburn  5131:     my %personnel = ();
1.841     albertel 5132: 
                   5133:     my %servers = &get_servers($dom,'library');
                   5134:     foreach my $tryserver (keys(%servers)) {
                   5135: 	%{$personnel{$tryserver}}=();
                   5136: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5137: 					    &escape($startdate).':'.
                   5138: 					    &escape($enddate).':'.
                   5139: 					    &escape($rolelist), $tryserver))) {
                   5140: 	    my ($key,$value) = split(/\=/,$line,2);
                   5141: 	    if (($key) && ($value)) {
                   5142: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5143: 	    }
                   5144: 	}
1.662     raeburn  5145:     }
                   5146:     return %personnel;
                   5147: }
1.658     raeburn  5148: 
1.1332    raeburn  5149: sub get_active_domroles {
                   5150:     my ($dom,$roles) = @_;
                   5151:     return () unless (ref($roles) eq 'ARRAY');
                   5152:     my $now = time;
                   5153:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5154:     my %domroles;
                   5155:     foreach my $server (keys(%dompersonnel)) {
                   5156:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5157:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5158:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5159:         }
                   5160:     }
                   5161:     return %domroles;
                   5162: }
                   5163: 
1.1057    www      5164: # ----------------------------------------------------------- Interval timing 
1.149     www      5165: 
1.1153    www      5166: {
                   5167: # Caches needed for speedup of navmaps
                   5168: # We don't want to cache this for very long at all (5 seconds at most)
                   5169: # 
                   5170: # The user for whom we cache
                   5171: my $cachedkey='';
                   5172: # The cached times for this user
                   5173: my %cachedtimes=();
                   5174: # When this was last done
1.1282    raeburn  5175: my $cachedtime='';
1.1153    www      5176: 
                   5177: sub load_all_first_access {
1.1308    raeburn  5178:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5179:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5180:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5181:         (!$ignorecache)) {
1.1154    raeburn  5182:         return;
                   5183:     }
                   5184:     $cachedtime=time;
                   5185:     $cachedkey=$uname.':'.$udom;
                   5186:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5187: }
                   5188: 
1.504     albertel 5189: sub get_first_access {
1.1308    raeburn  5190:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5191:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5192:     if ($argsymb) { $symb=$argsymb; }
                   5193:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5194:     if ($argmap) { $map = $argmap; }
1.926     albertel 5195:     if ($type eq 'course') {
                   5196: 	$res='course';
                   5197:     } elsif ($type eq 'map') {
1.588     albertel 5198: 	$res=&symbread($map);
                   5199:     } else {
                   5200: 	$res=$symb;
                   5201:     }
1.1308    raeburn  5202:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5203:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5204: }
                   5205: 
                   5206: sub set_first_access {
1.1162    raeburn  5207:     my ($type,$interval)=@_;
1.790     albertel 5208:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5209:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5210:     if ($type eq 'course') {
                   5211: 	$res='course';
                   5212:     } elsif ($type eq 'map') {
1.588     albertel 5213: 	$res=&symbread($map);
                   5214:     } else {
                   5215: 	$res=$symb;
                   5216:     }
1.1153    www      5217:     $cachedkey='';
1.1162    raeburn  5218:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 5219:     if (!$firstaccess) {
1.1162    raeburn  5220:         my $start = time;
                   5221: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5222:                           $udom,$uname);
                   5223:         if ($putres eq 'ok') {
                   5224:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5225:                  $udom,$uname); 
                   5226:             &appenv(
                   5227:                      {
                   5228:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5229:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5230:                      }
                   5231:                   );
1.1365    raeburn  5232:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5233:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5234:             }
1.1162    raeburn  5235:         }
                   5236:         return $putres;
1.505     albertel 5237:     }
                   5238:     return 'already_set';
1.504     albertel 5239: }
1.1153    www      5240: }
1.1282    raeburn  5241: 
1.110     www      5242: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5243: 
                   5244: sub expirespread {
                   5245:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5246:     my $cid=$env{'request.course.id'}; 
1.110     www      5247:     if ($cid) {
                   5248:        my $now=time;
                   5249:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5250:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5251:                             $env{'course.'.$cid.'.num'}.
1.110     www      5252: 	        	    ':nohist_expirationdates:'.
                   5253:                             &escape($key).'='.$now,
1.620     albertel 5254:                             $env{'course.'.$cid.'.home'})
1.110     www      5255:     }
                   5256:     return 'ok';
1.14      www      5257: }
                   5258: 
1.109     www      5259: # ----------------------------------------------------- Devalidate Spreadsheets
                   5260: 
                   5261: sub devalidate {
1.325     www      5262:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5263:     my $cid=$env{'request.course.id'}; 
1.109     www      5264:     if ($cid) {
1.391     matthew  5265:         # delete the stored spreadsheets for
                   5266:         # - the student level sheet of this user in course's homespace
                   5267:         # - the assessment level sheet for this resource 
                   5268:         #   for this user in user's homespace
1.553     albertel 5269: 	# - current conditional state info
1.325     www      5270: 	my $key=$uname.':'.$udom.':';
1.109     www      5271:         my $status=
1.299     matthew  5272: 	    &del('nohist_calculatedsheets',
1.391     matthew  5273: 		 [$key.'studentcalc:'],
1.620     albertel 5274: 		 $env{'course.'.$cid.'.domain'},
                   5275: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5276: 		.' '.
                   5277: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5278: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5279:         unless ($status eq 'ok ok') {
                   5280:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5281:                     $uname.' at '.$udom.' for '.
1.109     www      5282: 		    $symb.': '.$status);
1.133     albertel 5283:         }
1.553     albertel 5284: 	&delenv('user.state.'.$cid);
1.109     www      5285:     }
                   5286: }
                   5287: 
1.265     albertel 5288: sub get_scalar {
                   5289:     my ($string,$end) = @_;
                   5290:     my $value;
                   5291:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5292: 	$value = $1;
                   5293:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5294: 	$value = $1;
                   5295:     }
                   5296:     return &unescape($value);
                   5297: }
                   5298: 
                   5299: sub array2str {
                   5300:   my (@array) = @_;
                   5301:   my $result=&arrayref2str(\@array);
                   5302:   $result=~s/^__ARRAY_REF__//;
                   5303:   $result=~s/__END_ARRAY_REF__$//;
                   5304:   return $result;
                   5305: }
                   5306: 
1.204     albertel 5307: sub arrayref2str {
                   5308:   my ($arrayref) = @_;
1.265     albertel 5309:   my $result='__ARRAY_REF__';
1.204     albertel 5310:   foreach my $elem (@$arrayref) {
1.265     albertel 5311:     if(ref($elem) eq 'ARRAY') {
                   5312:       $result.=&arrayref2str($elem).'&';
                   5313:     } elsif(ref($elem) eq 'HASH') {
                   5314:       $result.=&hashref2str($elem).'&';
                   5315:     } elsif(ref($elem)) {
                   5316:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5317:     } else {
                   5318:       $result.=&escape($elem).'&';
                   5319:     }
                   5320:   }
                   5321:   $result=~s/\&$//;
1.265     albertel 5322:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5323:   return $result;
                   5324: }
                   5325: 
1.168     albertel 5326: sub hash2str {
1.204     albertel 5327:   my (%hash) = @_;
                   5328:   my $result=&hashref2str(\%hash);
1.265     albertel 5329:   $result=~s/^__HASH_REF__//;
                   5330:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5331:   return $result;
                   5332: }
                   5333: 
                   5334: sub hashref2str {
                   5335:   my ($hashref)=@_;
1.265     albertel 5336:   my $result='__HASH_REF__';
1.800     albertel 5337:   foreach my $key (sort(keys(%$hashref))) {
                   5338:     if (ref($key) eq 'ARRAY') {
                   5339:       $result.=&arrayref2str($key).'=';
                   5340:     } elsif (ref($key) eq 'HASH') {
                   5341:       $result.=&hashref2str($key).'=';
                   5342:     } elsif (ref($key)) {
1.265     albertel 5343:       $result.='=';
1.800     albertel 5344:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5345:     } else {
1.1132    raeburn  5346: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5347:     }
                   5348: 
1.800     albertel 5349:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5350:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5351:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5352:       $result.=&hashref2str($hashref->{$key}).'&';
                   5353:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5354:        $result.='&';
1.800     albertel 5355:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5356:     } else {
1.800     albertel 5357:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5358:     }
                   5359:   }
1.168     albertel 5360:   $result=~s/\&$//;
1.265     albertel 5361:   $result .= '__END_HASH_REF__';
1.168     albertel 5362:   return $result;
                   5363: }
                   5364: 
                   5365: sub str2hash {
1.265     albertel 5366:     my ($string)=@_;
                   5367:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5368:     return %$hash;
                   5369: }
                   5370: 
                   5371: sub str2hashref {
1.168     albertel 5372:   my ($string) = @_;
1.265     albertel 5373: 
                   5374:   my %hash;
                   5375: 
                   5376:   if($string !~ /^__HASH_REF__/) {
                   5377:       if (! ($string eq '' || !defined($string))) {
                   5378: 	  $hash{'error'}='Not hash reference';
                   5379:       }
                   5380:       return (\%hash, $string);
                   5381:   }
                   5382: 
                   5383:   $string =~ s/^__HASH_REF__//;
                   5384: 
                   5385:   while($string !~ /^__END_HASH_REF__/) {
                   5386:       #key
                   5387:       my $key='';
                   5388:       if($string =~ /^__HASH_REF__/) {
                   5389:           ($key, $string)=&str2hashref($string);
                   5390:           if(defined($key->{'error'})) {
                   5391:               $hash{'error'}='Bad data';
                   5392:               return (\%hash, $string);
                   5393:           }
                   5394:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5395:           ($key, $string)=&str2arrayref($string);
                   5396:           if($key->[0] eq 'Array reference error') {
                   5397:               $hash{'error'}='Bad data';
                   5398:               return (\%hash, $string);
                   5399:           }
                   5400:       } else {
                   5401:           $string =~ s/^(.*?)=//;
1.267     albertel 5402: 	  $key=&unescape($1);
1.265     albertel 5403:       }
                   5404:       $string =~ s/^=//;
                   5405: 
                   5406:       #value
                   5407:       my $value='';
                   5408:       if($string =~ /^__HASH_REF__/) {
                   5409:           ($value, $string)=&str2hashref($string);
                   5410:           if(defined($value->{'error'})) {
                   5411:               $hash{'error'}='Bad data';
                   5412:               return (\%hash, $string);
                   5413:           }
                   5414:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5415:           ($value, $string)=&str2arrayref($string);
                   5416:           if($value->[0] eq 'Array reference error') {
                   5417:               $hash{'error'}='Bad data';
                   5418:               return (\%hash, $string);
                   5419:           }
                   5420:       } else {
                   5421: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5422:       }
                   5423:       $string =~ s/^&//;
                   5424: 
                   5425:       $hash{$key}=$value;
1.204     albertel 5426:   }
1.265     albertel 5427: 
                   5428:   $string =~ s/^__END_HASH_REF__//;
                   5429: 
                   5430:   return (\%hash, $string);
1.204     albertel 5431: }
                   5432: 
                   5433: sub str2array {
1.265     albertel 5434:     my ($string)=@_;
                   5435:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5436:     return @$array;
                   5437: }
                   5438: 
                   5439: sub str2arrayref {
1.204     albertel 5440:   my ($string) = @_;
1.265     albertel 5441:   my @array;
                   5442: 
                   5443:   if($string !~ /^__ARRAY_REF__/) {
                   5444:       if (! ($string eq '' || !defined($string))) {
                   5445: 	  $array[0]='Array reference error';
                   5446:       }
                   5447:       return (\@array, $string);
                   5448:   }
                   5449: 
                   5450:   $string =~ s/^__ARRAY_REF__//;
                   5451: 
                   5452:   while($string !~ /^__END_ARRAY_REF__/) {
                   5453:       my $value='';
                   5454:       if($string =~ /^__HASH_REF__/) {
                   5455:           ($value, $string)=&str2hashref($string);
                   5456:           if(defined($value->{'error'})) {
                   5457:               $array[0] ='Array reference error';
                   5458:               return (\@array, $string);
                   5459:           }
                   5460:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5461:           ($value, $string)=&str2arrayref($string);
                   5462:           if($value->[0] eq 'Array reference error') {
                   5463:               $array[0] ='Array reference error';
                   5464:               return (\@array, $string);
                   5465:           }
                   5466:       } else {
                   5467: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5468:       }
                   5469:       $string =~ s/^&//;
                   5470: 
                   5471:       push(@array, $value);
1.191     harris41 5472:   }
1.265     albertel 5473: 
                   5474:   $string =~ s/^__END_ARRAY_REF__//;
                   5475: 
                   5476:   return (\@array, $string);
1.168     albertel 5477: }
                   5478: 
1.167     albertel 5479: # -------------------------------------------------------------------Temp Store
                   5480: 
1.168     albertel 5481: sub tmpreset {
                   5482:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5483:   if (!$symb) {
                   5484:     $symb=&symbread();
1.620     albertel 5485:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5486:   }
                   5487:   $symb=escape($symb);
                   5488: 
1.620     albertel 5489:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5490:   $namespace=~s/\//\_/g;
                   5491:   $namespace=~s/\W//g;
                   5492: 
1.620     albertel 5493:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5494:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5495:   if ($domain eq 'public' && $stuname eq 'public') {
                   5496:       $stuname=$ENV{'REMOTE_ADDR'};
                   5497:   }
1.1117    foxr     5498:   my $path=LONCAPA::tempdir();
1.168     albertel 5499:   my %hash;
                   5500:   if (tie(%hash,'GDBM_File',
                   5501: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5502: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5503:     foreach my $key (keys(%hash)) {
1.180     albertel 5504:       if ($key=~ /:$symb/) {
1.168     albertel 5505: 	delete($hash{$key});
                   5506:       }
                   5507:     }
                   5508:   }
                   5509: }
                   5510: 
1.167     albertel 5511: sub tmpstore {
1.168     albertel 5512:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5513: 
                   5514:   if (!$symb) {
                   5515:     $symb=&symbread();
1.620     albertel 5516:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5517:   }
                   5518:   $symb=escape($symb);
                   5519: 
                   5520:   if (!$namespace) {
                   5521:     # I don't think we would ever want to store this for a course.
                   5522:     # it seems this will only be used if we don't have a course.
1.620     albertel 5523:     #$namespace=$env{'request.course.id'};
1.168     albertel 5524:     #if (!$namespace) {
1.620     albertel 5525:       $namespace=$env{'request.state'};
1.168     albertel 5526:     #}
                   5527:   }
                   5528:   $namespace=~s/\//\_/g;
                   5529:   $namespace=~s/\W//g;
1.620     albertel 5530:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5531:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5532:   if ($domain eq 'public' && $stuname eq 'public') {
                   5533:       $stuname=$ENV{'REMOTE_ADDR'};
                   5534:   }
1.168     albertel 5535:   my $now=time;
                   5536:   my %hash;
1.1117    foxr     5537:   my $path=LONCAPA::tempdir();
1.168     albertel 5538:   if (tie(%hash,'GDBM_File',
                   5539: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5540: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5541:     $hash{"version:$symb"}++;
                   5542:     my $version=$hash{"version:$symb"};
                   5543:     my $allkeys=''; 
                   5544:     foreach my $key (keys(%$storehash)) {
                   5545:       $allkeys.=$key.':';
1.591     albertel 5546:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5547:     }
                   5548:     $hash{"$version:$symb:timestamp"}=$now;
                   5549:     $allkeys.='timestamp';
                   5550:     $hash{"$version:keys:$symb"}=$allkeys;
                   5551:     if (untie(%hash)) {
                   5552:       return 'ok';
                   5553:     } else {
                   5554:       return "error:$!";
                   5555:     }
                   5556:   } else {
                   5557:     return "error:$!";
                   5558:   }
                   5559: }
1.167     albertel 5560: 
1.168     albertel 5561: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5562: 
1.168     albertel 5563: sub tmprestore {
                   5564:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5565: 
1.168     albertel 5566:   if (!$symb) {
                   5567:     $symb=&symbread();
1.620     albertel 5568:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5569:   }
                   5570:   $symb=escape($symb);
                   5571: 
1.620     albertel 5572:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5573: 
1.620     albertel 5574:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5575:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5576:   if ($domain eq 'public' && $stuname eq 'public') {
                   5577:       $stuname=$ENV{'REMOTE_ADDR'};
                   5578:   }
1.168     albertel 5579:   my %returnhash;
                   5580:   $namespace=~s/\//\_/g;
                   5581:   $namespace=~s/\W//g;
                   5582:   my %hash;
1.1117    foxr     5583:   my $path=LONCAPA::tempdir();
1.168     albertel 5584:   if (tie(%hash,'GDBM_File',
                   5585: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5586: 	  &GDBM_READER(),0640)) {
1.168     albertel 5587:     my $version=$hash{"version:$symb"};
                   5588:     $returnhash{'version'}=$version;
                   5589:     my $scope;
                   5590:     for ($scope=1;$scope<=$version;$scope++) {
                   5591:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5592:       my @keys=split(/:/,$vkeys);
                   5593:       my $key;
                   5594:       $returnhash{"$scope:keys"}=$vkeys;
                   5595:       foreach $key (@keys) {
1.591     albertel 5596: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5597: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5598:       }
                   5599:     }
1.168     albertel 5600:     if (!(untie(%hash))) {
                   5601:       return "error:$!";
                   5602:     }
                   5603:   } else {
                   5604:     return "error:$!";
                   5605:   }
                   5606:   return %returnhash;
1.167     albertel 5607: }
                   5608: 
1.9       www      5609: # ----------------------------------------------------------------------- Store
                   5610: 
                   5611: sub store {
1.1269    raeburn  5612:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5613:     my $home='';
                   5614: 
1.168     albertel 5615:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5616: 
1.213     www      5617:     $symb=&symbclean($symb);
1.122     albertel 5618:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5619: 
1.620     albertel 5620:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5621:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5622: 
                   5623:     &devalidate($symb,$stuname,$domain);
1.109     www      5624: 
                   5625:     $symb=escape($symb);
1.187     www      5626:     if (!$namespace) { 
1.620     albertel 5627:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5628:           return ''; 
                   5629:        } 
                   5630:     }
1.620     albertel 5631:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5632: 
                   5633:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5634:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5635: 
1.12      www      5636:     my $namevalue='';
1.800     albertel 5637:     foreach my $key (keys(%$storehash)) {
                   5638:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5639:     }
1.12      www      5640:     $namevalue=~s/\&$//;
1.187     www      5641:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5642:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5643: }
                   5644: 
1.47      www      5645: # -------------------------------------------------------------- Critical Store
                   5646: 
                   5647: sub cstore {
1.1269    raeburn  5648:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5649:     my $home='';
                   5650: 
1.168     albertel 5651:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5652: 
1.213     www      5653:     $symb=&symbclean($symb);
1.122     albertel 5654:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5655: 
1.620     albertel 5656:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5657:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5658: 
                   5659:     &devalidate($symb,$stuname,$domain);
1.109     www      5660: 
                   5661:     $symb=escape($symb);
1.187     www      5662:     if (!$namespace) { 
1.620     albertel 5663:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5664:           return ''; 
                   5665:        } 
                   5666:     }
1.620     albertel 5667:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5668: 
                   5669:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5670:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5671: 
1.47      www      5672:     my $namevalue='';
1.800     albertel 5673:     foreach my $key (keys(%$storehash)) {
                   5674:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5675:     }
1.47      www      5676:     $namevalue=~s/\&$//;
1.187     www      5677:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5678:     return critical
1.1269    raeburn  5679:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5680: }
                   5681: 
1.9       www      5682: # --------------------------------------------------------------------- Restore
                   5683: 
                   5684: sub restore {
1.124     www      5685:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5686:     my $home='';
                   5687: 
1.168     albertel 5688:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5689: 
1.122     albertel 5690:     if (!$symb) {
1.1224    raeburn  5691:         return if ($namespace eq 'courserequests');
                   5692:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5693:     } else {
1.1224    raeburn  5694:         unless ($namespace eq 'courserequests') {
                   5695:             $symb=&escape(&symbclean($symb));
                   5696:         }
1.122     albertel 5697:     }
1.188     www      5698:     if (!$namespace) { 
1.620     albertel 5699:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5700:           return ''; 
                   5701:        } 
                   5702:     }
1.620     albertel 5703:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5704:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5705:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5706:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5707: 
1.12      www      5708:     my %returnhash=();
1.800     albertel 5709:     foreach my $line (split(/\&/,$answer)) {
                   5710: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5711:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5712:     }
1.75      www      5713:     my $version;
                   5714:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5715:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5716:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5717:        }
1.75      www      5718:     }
1.13      www      5719:     return %returnhash;
1.34      www      5720: }
                   5721: 
                   5722: # ---------------------------------------------------------- Course Description
1.1118    foxr     5723: #
                   5724: #  
1.34      www      5725: 
                   5726: sub coursedescription {
1.731     albertel 5727:     my ($courseid,$args)=@_;
1.34      www      5728:     $courseid=~s/^\///;
1.49      www      5729:     $courseid=~s/\_/\//g;
1.34      www      5730:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5731:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5732:     my $normalid=$cdomain.'_'.$cnum;
                   5733:     # need to always cache even if we get errors otherwise we keep 
                   5734:     # trying and trying and trying to get the course description.
                   5735:     my %envhash=();
                   5736:     my %returnhash=();
1.731     albertel 5737:     
                   5738:     my $expiretime=600;
                   5739:     if ($env{'request.course.id'} eq $normalid) {
                   5740: 	$expiretime=120;
                   5741:     }
                   5742: 
                   5743:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5744:     if (!$args->{'freshen_cache'}
                   5745: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5746: 	foreach my $key (keys(%env)) {
                   5747: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5748: 	    my ($setting) = $1;
                   5749: 	    $returnhash{$setting} = $env{$key};
                   5750: 	}
                   5751: 	return %returnhash;
                   5752:     }
                   5753: 
1.1118    foxr     5754:     # get the data again
                   5755: 
1.731     albertel 5756:     if (!$args->{'one_time'}) {
                   5757: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5758:     }
1.811     albertel 5759: 
1.34      www      5760:     if ($chome ne 'no_host') {
1.302     albertel 5761:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5762:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5763: 	   my $username = $env{'user.name'}; # Defult username
                   5764: 	   if(defined $args->{'user'}) {
                   5765: 	       $username = $args->{'user'};
                   5766: 	   }
1.129     albertel 5767:            $returnhash{'home'}= $chome;
                   5768: 	   $returnhash{'domain'} = $cdomain;
                   5769: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5770:            if (!defined($returnhash{'type'})) {
                   5771:                $returnhash{'type'} = 'Course';
                   5772:            }
1.130     albertel 5773:            while (my ($name,$value) = each %returnhash) {
1.53      www      5774:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5775:            }
1.270     www      5776:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5777:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5778: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5779:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5780:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5781:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5782:        }
                   5783:     }
1.731     albertel 5784:     if (!$args->{'one_time'}) {
1.949     raeburn  5785: 	&appenv(\%envhash);
1.731     albertel 5786:     }
1.302     albertel 5787:     return %returnhash;
1.461     www      5788: }
                   5789: 
1.1080    raeburn  5790: sub update_released_required {
                   5791:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5792:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5793:         $cid = $env{'request.course.id'};
                   5794:         $cdom = $env{'course.'.$cid.'.domain'};
                   5795:         $cnum = $env{'course.'.$cid.'.num'};
                   5796:         $chome = $env{'course.'.$cid.'.home'};
                   5797:     }
                   5798:     if ($needsrelease) {
                   5799:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5800:         my $needsupdate;
                   5801:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5802:             $needsupdate = 1;
                   5803:         } else {
                   5804:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5805:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5806:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5807:                 $needsupdate = 1;
                   5808:             }
                   5809:         }
                   5810:         if ($needsupdate) {
                   5811:             my %needshash = (
                   5812:                              'internal.releaserequired' => $needsrelease,
                   5813:                             );
                   5814:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5815:             if ($putresult eq 'ok') {
                   5816:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5817:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5818:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5819:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5820:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5821:                 }
                   5822:             }
                   5823:         }
                   5824:     }
                   5825:     return;
                   5826: }
                   5827: 
1.461     www      5828: # -------------------------------------------------See if a user is privileged
                   5829: 
                   5830: sub privileged {
1.1219    raeburn  5831:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5832:     my $now = time;
1.1219    raeburn  5833:     my $roles;
                   5834:     if (ref($possroles) eq 'ARRAY') {
                   5835:         $roles = $possroles; 
                   5836:     } else {
                   5837:         $roles = ['dc','su'];
                   5838:     }
                   5839:     if (ref($possdomains) eq 'ARRAY') {
                   5840:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5841:         foreach my $dom (@{$possdomains}) {
                   5842:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5843:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5844:                 foreach my $role (@{$roles}) {
                   5845:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5846:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5847:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5848:                             return 1 unless (($end && $end < $now) ||
                   5849:                                              ($start && $start > $now));
                   5850:                         }
                   5851:                     }
                   5852:                 }
                   5853:             }
                   5854:         }
                   5855:     } else {
                   5856:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5857:         my $now = time;
1.1170    droeschl 5858: 
1.1275    musolffc 5859:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5860:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5861:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5862:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5863:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5864:             }
1.1219    raeburn  5865:         }
                   5866:     }
                   5867:     return 0;
                   5868: }
1.1170    droeschl 5869: 
1.1219    raeburn  5870: sub privileged_by_domain {
                   5871:     my ($domains,$roles) = @_;
                   5872:     my %privileged = ();
                   5873:     my $cachetime = 60*60*24;
                   5874:     my $now = time;
                   5875:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5876:         return %privileged;
                   5877:     }
                   5878:     foreach my $dom (@{$domains}) {
                   5879:         next if (ref($privileged{$dom}) eq 'HASH');
                   5880:         my $needroles;
                   5881:         foreach my $role (@{$roles}) {
                   5882:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5883:             if (defined($cached)) {
                   5884:                 if (ref($result) eq 'HASH') {
                   5885:                     $privileged{$dom}{$role} = $result;
                   5886:                 }
                   5887:             } else {
                   5888:                 $needroles = 1;
                   5889:             }
                   5890:         }
                   5891:         if ($needroles) {
                   5892:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5893:             $privileged{$dom} = {};
                   5894:             foreach my $server (keys(%dompersonnel)) {
                   5895:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5896:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5897:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5898:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5899:                         next if ($end && $end < $now);
                   5900:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5901:                             $dompersonnel{$server}{$item};
                   5902:                     }
                   5903:                 }
                   5904:             }
                   5905:             if (ref($privileged{$dom}) eq 'HASH') {
                   5906:                 foreach my $role (@{$roles}) {
                   5907:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5908:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5909:                     } else {
                   5910:                         my %hash = ();
                   5911:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5912:                     }
                   5913:                 }
                   5914:             }
                   5915:         }
                   5916:     }
                   5917:     return %privileged;
1.9       www      5918: }
1.1       albertel 5919: 
1.103     harris41 5920: # -------------------------------------------------------- Get user privileges
1.11      www      5921: 
                   5922: sub rolesinit {
1.1169    droeschl 5923:     my ($domain, $username) = @_;
                   5924:     my %userroles = ('user.login.time' => time);
                   5925:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5926: 
                   5927:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5928:     # also, blocking can be triggered by an activating timer
                   5929:     # it's saved in the user's %env.
                   5930:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5931:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5932:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5933:         %timerintchk, %timerintenv);
                   5934: 
1.1162    raeburn  5935:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5936:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5937:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5938:     }
1.1169    droeschl 5939: 
1.1162    raeburn  5940:     foreach my $key (keys(%timerinterval)) {
                   5941:         my ($cid,$rest) = split(/\0/,$key);
                   5942:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5943:     }
1.1169    droeschl 5944: 
1.11      www      5945:     my %allroles=();
1.1162    raeburn  5946:     my %allgroups=();
1.11      www      5947: 
1.1274    raeburn  5948:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5949:         my $role = $rolesdump{$area};
                   5950:         $area =~ s/\_\w\w$//;
                   5951: 
                   5952:         my ($trole, $tend, $tstart, $group_privs);
                   5953: 
                   5954:         if ($role =~ /^cr/) {
                   5955:         # Custom role, defined by a user 
                   5956:         # e.g., user.role.cr/msu/smith/mynewrole
                   5957:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5958:                 $trole = $1;
                   5959:                 ($tend, $tstart) = split('_', $2);
                   5960:             } else {
                   5961:                 $trole = $role;
                   5962:             }
                   5963:         } elsif ($role =~ m|^gr/|) {
                   5964:         # Role of member in a group, defined within a course/community
                   5965:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5966:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5967:             next if $tstart eq '-1';
                   5968:             ($trole, $group_privs) = split(/\//, $trole);
                   5969:             $group_privs = &unescape($group_privs);
                   5970:         } else {
                   5971:         # Just a normal role, defined in roles.tab
                   5972:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5973:         }
                   5974: 
                   5975:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5976:                  $username);
                   5977:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5978: 
                   5979:         # role expired or not available yet?
                   5980:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5981:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5982: 
                   5983:         next if $area eq '' or $trole eq '';
                   5984: 
                   5985:         my $spec = "$trole.$area";
                   5986:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5987: 
                   5988:         if ($trole =~ /^cr\//) {
                   5989:         # Custom role, defined by a user
                   5990:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5991:         } elsif ($trole eq 'gr') {
                   5992:         # Role of a member in a group, defined within a course/community
                   5993:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5994:             next;
                   5995:         } else {
                   5996:         # Normal role, defined in roles.tab
                   5997:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5998:         }
                   5999: 
                   6000:         my $cid = $tdomain.'_'.$trest;
                   6001:         unless ($firstaccchk{$cid}) {
                   6002:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6003:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6004:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6005:                         $coursetimerstarts{$cid}{$item}; 
                   6006:                 }
                   6007:             }
                   6008:             $firstaccchk{$cid} = 1;
                   6009:         }
                   6010:         unless ($timerintchk{$cid}) {
                   6011:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6012:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6013:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6014:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6015:                 }
1.12      www      6016:             }
1.1169    droeschl 6017:             $timerintchk{$cid} = 1;
1.191     harris41 6018:         }
1.11      www      6019:     }
1.1169    droeschl 6020: 
1.1341    raeburn  6021:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6022:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6023:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6024:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6025: 
1.1162    raeburn  6026:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6027: }
                   6028: 
1.567     raeburn  6029: sub set_arearole {
1.1215    raeburn  6030:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6031:     unless ($nolog) {
1.567     raeburn  6032: # log the associated role with the area
1.1215    raeburn  6033:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6034:     }
1.743     albertel 6035:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6036: }
                   6037: 
                   6038: sub custom_roleprivs {
                   6039:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6040:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6041:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6042:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6043:         my ($rdummy,$roledef)=
                   6044:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6045:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6046:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6047:             if (defined($syspriv)) {
1.1043    raeburn  6048:                 if ($trest =~ /^$match_community$/) {
                   6049:                     $syspriv =~ s/bre\&S//; 
                   6050:                 }
1.567     raeburn  6051:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6052:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6053:             }
                   6054:             if ($tdomain ne '') {
                   6055:                 if (defined($dompriv)) {
                   6056:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6057:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6058:                 }
                   6059:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6060:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6061:                         my $rolename = $1;
                   6062:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6063:                     }
1.567     raeburn  6064:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6065:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6066:                 }
                   6067:             }
                   6068:         }
                   6069:     }
                   6070: }
                   6071: 
1.1332    raeburn  6072: sub course_adhocrole_privs {
                   6073:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6074:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6075:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6076:         my (%currprivs,%storeprivs);
                   6077:         foreach my $item (split(/:/,$coursepriv)) {
                   6078:             my ($priv,$restrict) = split(/\&/,$item);
                   6079:             $currprivs{$priv} = $restrict;
                   6080:         }
                   6081:         my (%possadd,%possremove,%full);
                   6082:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6083:             my ($priv,$restrict)=split(/\&/,$item);
                   6084:             $full{$priv} = $restrict;
                   6085:         }
                   6086:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6087:              next if ($item eq '');
                   6088:              my ($rule,$rest) = split(/=/,$item);
                   6089:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6090:              foreach my $priv (split(/:/,$rest)) {
                   6091:                  if ($priv ne '') {
                   6092:                      if ($rule eq 'off') {
                   6093:                          $possremove{$priv} = 1;
                   6094:                      } else {
                   6095:                          $possadd{$priv} = 1;
                   6096:                      }
                   6097:                  }
                   6098:              }
                   6099:          }
                   6100:          foreach my $priv (sort(keys(%full))) {
                   6101:              if (exists($currprivs{$priv})) {
                   6102:                  unless (exists($possremove{$priv})) {
                   6103:                      $storeprivs{$priv} = $currprivs{$priv};
                   6104:                  }
                   6105:              } elsif (exists($possadd{$priv})) {
                   6106:                  $storeprivs{$priv} = $full{$priv};
                   6107:              }
                   6108:          }
                   6109:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6110:      }
                   6111:      return $coursepriv;
                   6112: }
                   6113: 
1.678     raeburn  6114: sub group_roleprivs {
                   6115:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6116:     my $access = 1;
                   6117:     my $now = time;
                   6118:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6119:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6120:     if ($access) {
1.811     albertel 6121:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6122:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6123:     }
                   6124: }
1.567     raeburn  6125: 
                   6126: sub standard_roleprivs {
                   6127:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6128:     if (defined($pr{$trole.':s'})) {
                   6129:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6130:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6131:     }
                   6132:     if ($tdomain ne '') {
                   6133:         if (defined($pr{$trole.':d'})) {
                   6134:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6135:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6136:         }
                   6137:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6138:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6139:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6140:         }
                   6141:     }
                   6142: }
                   6143: 
                   6144: sub set_userprivs {
1.1064    raeburn  6145:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6146:     my $author=0;
                   6147:     my $adv=0;
1.1341    raeburn  6148:     my $rar=0;
1.678     raeburn  6149:     my %grouproles = ();
                   6150:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6151:         my @groupkeys; 
1.1000    raeburn  6152:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6153:             push(@groupkeys,$role);
                   6154:         }
                   6155:         if (ref($groups_roles) eq 'HASH') {
                   6156:             foreach my $key (keys(%{$groups_roles})) {
                   6157:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6158:                     push(@groupkeys,$key);
                   6159:                 }
                   6160:             }
                   6161:         }
                   6162:         if (@groupkeys > 0) {
                   6163:             foreach my $role (@groupkeys) {
                   6164:                 my ($trole,$area,$sec,$extendedarea);
                   6165:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6166:                     $trole = $1;
                   6167:                     $area = $2;
                   6168:                     $sec = $3;
                   6169:                     $extendedarea = $area.$sec;
                   6170:                     if (exists($$allgroups{$area})) {
                   6171:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6172:                             my $spec = $trole.'.'.$extendedarea;
                   6173:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6174:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6175:                         }
1.678     raeburn  6176:                     }
                   6177:                 }
                   6178:             }
                   6179:         }
                   6180:     }
1.800     albertel 6181:     foreach my $group (keys(%grouproles)) {
                   6182:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6183:     }
1.800     albertel 6184:     foreach my $role (keys(%{$allroles})) {
                   6185:         my %thesepriv;
1.941     raeburn  6186:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6187:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6188:             if ($item ne '') {
                   6189:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6190:                 if ($restrictions eq '') {
                   6191:                     $thesepriv{$privilege}='F';
                   6192:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6193:                     $thesepriv{$privilege}.=$restrictions;
                   6194:                 }
                   6195:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6196:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6197:             }
                   6198:         }
                   6199:         my $thesestr='';
1.1104    raeburn  6200:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6201: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6202: 	}
                   6203:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6204:     }
1.1341    raeburn  6205:     return ($author,$adv,$rar);
1.567     raeburn  6206: }
                   6207: 
1.994     raeburn  6208: sub role_status {
1.1104    raeburn  6209:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6210:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6211:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6212:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6213:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6214:             $$where = '/'.$two;
1.994     raeburn  6215:             $$trolecode=$$role.'.'.$$where;
                   6216:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6217:             $$tstatus='is';
1.1104    raeburn  6218:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6219:                 $$tstatus='future';
1.1034    raeburn  6220:                 if ($$tstart<$now) {
                   6221:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6222:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6223:                             my (%allroles,%allgroups,$group_privs,
                   6224:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6225:                             my %userroles = (
                   6226:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6227:                             );
1.1064    raeburn  6228:                             @rolecodes = ('cm'); 
1.1002    raeburn  6229:                             my $spec=$$role.'.'.$$where;
                   6230:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6231:                             if ($$role =~ /^cr\//) {
                   6232:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6233:                                 push(@rolecodes,'cr');
1.1002    raeburn  6234:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6235:                                 push(@rolecodes,$$role);
1.1002    raeburn  6236:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6237:                                                     $env{'user.name'});
1.1064    raeburn  6238:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6239:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6240:                                 $group_privs = &unescape($group_privs);
                   6241:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6242:                                 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  6243:                                 &get_groups_roles($tdomain,$trest,
                   6244:                                                   \%course_roles,\@rolecodes,
                   6245:                                                   \%groups_roles);
1.1002    raeburn  6246:                             } else {
1.1064    raeburn  6247:                                 push(@rolecodes,$$role);
1.1002    raeburn  6248:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6249:                             }
1.1341    raeburn  6250:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6251:                                                                    \%groups_roles);
1.1064    raeburn  6252:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6253:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6254:                         }
                   6255:                     }
1.1034    raeburn  6256:                     $$tstatus = 'is';
1.1002    raeburn  6257:                 }
1.994     raeburn  6258:             }
                   6259:             if ($$tend) {
1.1104    raeburn  6260:                 if ($$tend<$update) {
1.994     raeburn  6261:                     $$tstatus='expired';
                   6262:                 } elsif ($$tend<$now) {
                   6263:                     $$tstatus='will_not';
                   6264:                 }
                   6265:             }
                   6266:         }
                   6267:     }
                   6268: }
                   6269: 
1.1104    raeburn  6270: sub get_groups_roles {
                   6271:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6272:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6273:                   (ref($rolecodes) eq 'ARRAY') && 
                   6274:                   (ref($groups_roles) eq 'HASH')); 
                   6275:     if (keys(%{$cdom_courseroles}) > 0) {
                   6276:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6277:         if ($cdom ne '' && $cnum ne '') {
                   6278:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6279:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6280:                     my $crsrole = $1;
                   6281:                     my $crssec = $2;
                   6282:                     if ($crsrole =~ /^cr/) {
                   6283:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6284:                             push(@{$rolecodes},'cr');
                   6285:                         }
                   6286:                     } else {
                   6287:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6288:                             push(@{$rolecodes},$crsrole);
                   6289:                         }
                   6290:                     }
                   6291:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6292:                     if ($crssec ne '') {
                   6293:                         $rolekey .= "/$crssec";
                   6294:                     }
                   6295:                     $rolekey .= './';
                   6296:                     $groups_roles->{$rolekey} = $rolecodes;
                   6297:                 }
                   6298:             }
                   6299:         }
                   6300:     }
                   6301:     return;
                   6302: }
                   6303: 
                   6304: sub delete_env_groupprivs {
                   6305:     my ($where,$courseroles,$possroles) = @_;
                   6306:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6307:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6308:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6309:         %{$courseroles->{$udom}} =
                   6310:             &get_my_roles('','','userroles',['active'],
                   6311:                           $possroles,[$udom],1);
                   6312:     }
                   6313:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6314:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6315:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6316:             my $area = '/'.$cdom.'/'.$cnum;
                   6317:             my $privkey = "user.priv.$crsrole.$area";
                   6318:             if ($crssec ne '') {
                   6319:                 $privkey .= '/'.$crssec;
                   6320:             }
                   6321:             $privkey .= ".$area/$group";
                   6322:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6323:         }
                   6324:     }
                   6325:     return;
                   6326: }
                   6327: 
1.994     raeburn  6328: sub check_adhoc_privs {
1.1329    raeburn  6329:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6330:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6331:     if ($sec) {
                   6332:         $cckey .= '/'.$sec;
                   6333:     } 
1.1185    raeburn  6334:     my $setprivs;
1.994     raeburn  6335:     if ($env{$cckey}) {
                   6336:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6337:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6338:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6339:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6340:             $setprivs = 1;
1.994     raeburn  6341:         }
                   6342:     } else {
1.1330    raeburn  6343:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6344:         $setprivs = 1;
1.994     raeburn  6345:     }
1.1185    raeburn  6346:     return $setprivs;
1.994     raeburn  6347: }
                   6348: 
                   6349: sub set_adhoc_privileges {
1.1326    raeburn  6350: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6351:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6352:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6353:     if ($sec ne '') {
                   6354:         $area .= '/'.$sec;
                   6355:     }
1.994     raeburn  6356:     my $spec = $role.'.'.$area;
                   6357:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6358:                                   $env{'user.name'},1);
1.1326    raeburn  6359:     my %rolehash = ();
1.1332    raeburn  6360:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6361:         my $rolename = $1;
1.1326    raeburn  6362:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6363:         my %domdef = &get_domain_defaults($dcdom);
                   6364:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6365:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6366:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6367:             }
                   6368:         }
1.1326    raeburn  6369:     } else {
                   6370:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6371:     }
1.1341    raeburn  6372:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6373:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6374:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6375:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6376:         &appenv( {'request.role'        => $spec,
                   6377:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6378:                   'request.course.sec'  => $sec,
1.1088    raeburn  6379:                  }
                   6380:                );
                   6381:         my $tadv=0;
                   6382:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6383:         &appenv({'request.role.adv'    => $tadv});
                   6384:     }
1.994     raeburn  6385: }
                   6386: 
1.12      www      6387: # --------------------------------------------------------------- get interface
                   6388: 
                   6389: sub get {
1.131     albertel 6390:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6391:    my $items='';
1.800     albertel 6392:    foreach my $item (@$storearr) {
                   6393:        $items.=&escape($item).'&';
1.191     harris41 6394:    }
1.12      www      6395:    $items=~s/\&$//;
1.620     albertel 6396:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6397:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6398:    my $uhome=&homeserver($uname,$udomain);
                   6399: 
1.133     albertel 6400:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6401:    my @pairs=split(/\&/,$rep);
1.273     albertel 6402:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6403:      return @pairs;
                   6404:    }
1.15      www      6405:    my %returnhash=();
1.42      www      6406:    my $i=0;
1.800     albertel 6407:    foreach my $item (@$storearr) {
                   6408:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6409:       $i++;
1.191     harris41 6410:    }
1.15      www      6411:    return %returnhash;
1.27      www      6412: }
                   6413: 
                   6414: # --------------------------------------------------------------- del interface
                   6415: 
                   6416: sub del {
1.133     albertel 6417:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6418:    my $items='';
1.800     albertel 6419:    foreach my $item (@$storearr) {
                   6420:        $items.=&escape($item).'&';
1.191     harris41 6421:    }
1.984     neumanie 6422: 
1.27      www      6423:    $items=~s/\&$//;
1.620     albertel 6424:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6425:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6426:    my $uhome=&homeserver($uname,$udomain);
                   6427:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6428: }
                   6429: 
                   6430: # -------------------------------------------------------------- dump interface
                   6431: 
1.1180    droeschl 6432: sub unserialize {
                   6433:     my ($rep, $escapedkeys) = @_;
                   6434: 
                   6435:     return {} if $rep =~ /^error/;
                   6436: 
                   6437:     my %returnhash=();
1.1252    raeburn  6438: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6439: 	    my ($key, $value) = split(/=/, $item, 2);
                   6440: 	    $key = unescape($key) unless $escapedkeys;
                   6441: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6442: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6443: 	}
                   6444:     #return %returnhash;
                   6445:     return \%returnhash;
                   6446: }        
                   6447: 
                   6448: # see Lond::dump_with_regexp
                   6449: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6450: sub dump {
1.1180    droeschl 6451:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6452:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6453:     if (!$uname) { $uname=$env{'user.name'}; }
                   6454:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6455: 
1.1266    raeburn  6456:     if ($regexp) {
                   6457:         $regexp=&escape($regexp);
                   6458:     } else {
                   6459:         $regexp='.';
                   6460:     }
1.1180    droeschl 6461:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6462:         # user is hosted on this machine
1.1266    raeburn  6463:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6464:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6465:         return %{unserialize($reply, $escapedkeys)};
                   6466:     }
1.1166    raeburn  6467:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6468:     my @pairs=split(/\&/,$rep);
                   6469:     my %returnhash=();
1.1098    foxr     6470:     if (!($rep =~ /^error/ )) {
                   6471: 	foreach my $item (@pairs) {
                   6472: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6473:         $key = unescape($key) unless $escapedkeys;
                   6474:         #$key = &unescape($key);
1.1098    foxr     6475: 	    next if ($key =~ /^error: 2 /);
                   6476: 	    $returnhash{$key}=&thaw_unescape($value);
                   6477: 	}
1.755     albertel 6478:     }
                   6479:     return %returnhash;
1.407     www      6480: }
                   6481: 
1.1098    foxr     6482: 
1.717     albertel 6483: # --------------------------------------------------------- dumpstore interface
                   6484: 
                   6485: sub dumpstore {
                   6486:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6487:    # same as dump but keys must be escaped. They may contain colon separated
                   6488:    # lists of values that may themself contain colons (e.g. symbs).
                   6489:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6490: }
                   6491: 
1.407     www      6492: # -------------------------------------------------------------- keys interface
                   6493: 
                   6494: sub getkeys {
                   6495:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6496:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6497:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6498:    my $uhome=&homeserver($uname,$udomain);
                   6499:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6500:    my @keyarray=();
1.800     albertel 6501:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6502:       next if ($key =~ /^error: 2 /);
1.800     albertel 6503:       push(@keyarray,&unescape($key));
1.407     www      6504:    }
                   6505:    return @keyarray;
1.318     matthew  6506: }
                   6507: 
1.319     matthew  6508: # --------------------------------------------------------------- currentdump
                   6509: sub currentdump {
1.328     matthew  6510:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6511:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6512:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6513:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6514:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6515:    my $rep;
                   6516: 
                   6517:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6518:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6519:                    $courseid)));
                   6520:    } else {
                   6521:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6522:    }
                   6523: 
1.318     matthew  6524:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6525:    #
1.318     matthew  6526:    my %returnhash=();
1.319     matthew  6527:    #
1.1343    raeburn  6528:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6529:        # an old lond will not know currentdump
                   6530:        # Do a dump and make it look like a currentdump
1.822     albertel 6531:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6532:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6533:        my %hash = @tmp;
                   6534:        @tmp=();
1.424     matthew  6535:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6536:    } else {
                   6537:        my @pairs=split(/\&/,$rep);
1.800     albertel 6538:        foreach my $pair (@pairs) {
                   6539:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6540:            my ($symb,$param) = split(/:/,$key);
                   6541:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6542:                                                         &thaw_unescape($value);
1.319     matthew  6543:        }
1.191     harris41 6544:    }
1.12      www      6545:    return %returnhash;
1.424     matthew  6546: }
                   6547: 
                   6548: sub convert_dump_to_currentdump{
                   6549:     my %hash = %{shift()};
                   6550:     my %returnhash;
                   6551:     # Code ripped from lond, essentially.  The only difference
                   6552:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6553:     # we might run in to problems with parameter names =~ /^v\./
                   6554:     while (my ($key,$value) = each(%hash)) {
                   6555:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6556: 	$symb  = &unescape($symb);
                   6557: 	$param = &unescape($param);
1.424     matthew  6558:         next if ($v eq 'version' || $symb eq 'keys');
                   6559:         next if (exists($returnhash{$symb}) &&
                   6560:                  exists($returnhash{$symb}->{$param}) &&
                   6561:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6562:         $returnhash{$symb}->{$param}=$value;
                   6563:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6564:     }
                   6565:     #
                   6566:     # Remove all of the keys in the hashes which keep track of
                   6567:     # the version of the parameter.
                   6568:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6569:         # use a foreach because we are going to delete from the hash.
                   6570:         foreach my $key (keys(%$param_hash)) {
                   6571:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6572:         }
                   6573:     }
                   6574:     return \%returnhash;
1.12      www      6575: }
                   6576: 
1.627     albertel 6577: # ------------------------------------------------------ critical inc interface
                   6578: 
                   6579: sub cinc {
                   6580:     return &inc(@_,'critical');
                   6581: }
                   6582: 
1.449     matthew  6583: # --------------------------------------------------------------- inc interface
                   6584: 
                   6585: sub inc {
1.627     albertel 6586:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6587:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6588:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6589:     my $uhome=&homeserver($uname,$udomain);
                   6590:     my $items='';
                   6591:     if (! ref($store)) {
                   6592:         # got a single value, so use that instead
                   6593:         $items = &escape($store).'=&';
                   6594:     } elsif (ref($store) eq 'SCALAR') {
                   6595:         $items = &escape($$store).'=&';        
                   6596:     } elsif (ref($store) eq 'ARRAY') {
                   6597:         $items = join('=&',map {&escape($_);} @{$store});
                   6598:     } elsif (ref($store) eq 'HASH') {
                   6599:         while (my($key,$value) = each(%{$store})) {
                   6600:             $items.= &escape($key).'='.&escape($value).'&';
                   6601:         }
                   6602:     }
                   6603:     $items=~s/\&$//;
1.627     albertel 6604:     if ($critical) {
                   6605: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6606:     } else {
                   6607: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6608:     }
1.449     matthew  6609: }
                   6610: 
1.12      www      6611: # --------------------------------------------------------------- put interface
                   6612: 
                   6613: sub put {
1.134     albertel 6614:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6615:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6616:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6617:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6618:    my $items='';
1.800     albertel 6619:    foreach my $item (keys(%$storehash)) {
                   6620:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6621:    }
1.12      www      6622:    $items=~s/\&$//;
1.134     albertel 6623:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6624: }
                   6625: 
1.631     albertel 6626: # ------------------------------------------------------------ newput interface
                   6627: 
                   6628: sub newput {
                   6629:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6630:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6631:    if (!$uname) { $uname=$env{'user.name'}; }
                   6632:    my $uhome=&homeserver($uname,$udomain);
                   6633:    my $items='';
                   6634:    foreach my $key (keys(%$storehash)) {
                   6635:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6636:    }
                   6637:    $items=~s/\&$//;
                   6638:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6639: }
                   6640: 
                   6641: # ---------------------------------------------------------  putstore interface
                   6642: 
1.524     raeburn  6643: sub putstore {
1.1269    raeburn  6644:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6645:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6646:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6647:    my $uhome=&homeserver($uname,$udomain);
                   6648:    my $items='';
1.715     albertel 6649:    foreach my $key (keys(%$storehash)) {
                   6650:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6651:    }
1.715     albertel 6652:    $items=~s/\&$//;
1.716     albertel 6653:    my $esc_symb=&escape($symb);
                   6654:    my $esc_v=&escape($version);
1.715     albertel 6655:    my $reply =
1.716     albertel 6656:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6657: 	      $uhome);
1.1269    raeburn  6658:    if (($tolog) && ($reply eq 'ok')) {
                   6659:        my $namevalue='';
                   6660:        foreach my $key (keys(%{$storehash})) {
                   6661:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6662:        }
                   6663:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6664:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6665:                      '&version='.$esc_v.
                   6666:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6667:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6668:    }
1.715     albertel 6669:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6670:        # gfall back to way things use to be done
1.715     albertel 6671:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6672: 			    $uname);
1.524     raeburn  6673:    }
1.715     albertel 6674:    return $reply;
                   6675: }
                   6676: 
                   6677: sub old_putstore {
1.716     albertel 6678:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6679:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6680:     if (!$uname) { $uname=$env{'user.name'}; }
                   6681:     my $uhome=&homeserver($uname,$udomain);
                   6682:     my %newstorehash;
1.800     albertel 6683:     foreach my $item (keys(%$storehash)) {
                   6684: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6685: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6686:     }
                   6687:     my $items='';
                   6688:     my %allitems = ();
1.800     albertel 6689:     foreach my $item (keys(%newstorehash)) {
                   6690: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6691: 	    my $key = $1.':keys:'.$2;
                   6692: 	    $allitems{$key} .= $3.':';
                   6693: 	}
1.800     albertel 6694: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6695:     }
1.800     albertel 6696:     foreach my $item (keys(%allitems)) {
                   6697: 	$allitems{$item} =~ s/\:$//;
                   6698: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6699:     }
                   6700:     $items=~s/\&$//;
                   6701:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6702: }
                   6703: 
1.47      www      6704: # ------------------------------------------------------ critical put interface
                   6705: 
                   6706: sub cput {
1.134     albertel 6707:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6708:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6709:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6710:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6711:    my $items='';
1.800     albertel 6712:    foreach my $item (keys(%$storehash)) {
                   6713:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6714:    }
1.47      www      6715:    $items=~s/\&$//;
1.134     albertel 6716:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6717: }
                   6718: 
                   6719: # -------------------------------------------------------------- eget interface
                   6720: 
                   6721: sub eget {
1.133     albertel 6722:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6723:    my $items='';
1.800     albertel 6724:    foreach my $item (@$storearr) {
                   6725:        $items.=&escape($item).'&';
1.191     harris41 6726:    }
1.12      www      6727:    $items=~s/\&$//;
1.620     albertel 6728:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6729:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6730:    my $uhome=&homeserver($uname,$udomain);
                   6731:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6732:    my @pairs=split(/\&/,$rep);
                   6733:    my %returnhash=();
1.42      www      6734:    my $i=0;
1.800     albertel 6735:    foreach my $item (@$storearr) {
                   6736:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6737:       $i++;
1.191     harris41 6738:    }
1.12      www      6739:    return %returnhash;
                   6740: }
                   6741: 
1.667     albertel 6742: # ------------------------------------------------------------ tmpput interface
                   6743: sub tmpput {
1.802     raeburn  6744:     my ($storehash,$server,$context)=@_;
1.667     albertel 6745:     my $items='';
1.800     albertel 6746:     foreach my $item (keys(%$storehash)) {
                   6747: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6748:     }
                   6749:     $items=~s/\&$//;
1.802     raeburn  6750:     if (defined($context)) {
                   6751:         $items .= ':'.&escape($context);
                   6752:     }
1.667     albertel 6753:     return &reply("tmpput:$items",$server);
                   6754: }
                   6755: 
                   6756: # ------------------------------------------------------------ tmpget interface
                   6757: sub tmpget {
1.688     albertel 6758:     my ($token,$server)=@_;
                   6759:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6760:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6761:     my %returnhash;
1.1328    raeburn  6762:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6763:         return %returnhash;
                   6764:     }
1.667     albertel 6765:     foreach my $item (split(/\&/,$rep)) {
                   6766: 	my ($key,$value)=split(/=/,$item);
                   6767: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6768:     }
                   6769:     return %returnhash;
                   6770: }
                   6771: 
1.1113    raeburn  6772: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6773: sub tmpdel {
                   6774:     my ($token,$server)=@_;
                   6775:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6776:     return &reply("tmpdel:$token",$server);
                   6777: }
                   6778: 
1.1198    raeburn  6779: # ------------------------------------------------------------ get_timebased_id 
                   6780: 
                   6781: sub get_timebased_id {
                   6782:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6783:         $maxtries) = @_;
                   6784:     my ($newid,$error,$dellock);
                   6785:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6786:         return ('','ok','invalid call to get suffix');
                   6787:     }
                   6788: 
                   6789: # set defaults for any optional args for which values were not supplied
                   6790:     if ($who eq '') {
                   6791:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6792:     }
                   6793:     if (!$locktries) {
                   6794:         $locktries = 3;
                   6795:     }
                   6796:     if (!$maxtries) {
                   6797:         $maxtries = 10;
                   6798:     }
                   6799:     
                   6800:     if (($cdom eq '') || ($cnum eq '')) {
                   6801:         if ($env{'request.course.id'}) {
                   6802:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6803:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6804:         }
                   6805:         if (($cdom eq '') || ($cnum eq '')) {
                   6806:             return ('','ok','call to get suffix not in course context');
                   6807:         }
                   6808:     }
                   6809: 
                   6810: # construct locking item
                   6811:     my $lockhash = {
                   6812:                       $prefix."\0".'locked_'.$keyid => $who,
                   6813:                    };
                   6814:     my $tries = 0;
                   6815: 
                   6816: # attempt to get lock on nohist_$namespace file
                   6817:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6818:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6819:         $tries ++;
                   6820:         sleep 1;
                   6821:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6822:     }
                   6823: 
                   6824: # attempt to get unique identifier, based on current timestamp
                   6825:     if ($gotlock eq 'ok') {
                   6826:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6827:         my $id = time;
                   6828:         $newid = $id;
1.1268    raeburn  6829:         if ($idtype eq 'addcode') {
                   6830:             $newid .= &sixnum_code();
                   6831:         }
1.1198    raeburn  6832:         my $idtries = 0;
                   6833:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6834:             if ($idtype eq 'concat') {
                   6835:                 $newid = $id.$idtries;
1.1268    raeburn  6836:             } elsif ($idtype eq 'addcode') {
                   6837:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6838:             } else {
                   6839:                 $newid ++;
                   6840:             }
                   6841:             $idtries ++;
                   6842:         }
                   6843:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6844:             my %new_item =  (
                   6845:                               $prefix."\0".$newid => $who,
                   6846:                             );
                   6847:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6848:                                                  $cdom,$cnum);
                   6849:             if ($putresult ne 'ok') {
                   6850:                 undef($newid);
                   6851:                 $error = 'error saving new item: '.$putresult;
                   6852:             }
                   6853:         } else {
1.1268    raeburn  6854:              undef($newid);
1.1198    raeburn  6855:              $error = ('error: no unique suffix available for the new item ');
                   6856:         }
                   6857: #  remove lock
                   6858:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6859:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6860:     } else {
                   6861:         $error = "error: could not obtain lockfile\n";
                   6862:         $dellock = 'ok';
1.1276    raeburn  6863:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6864:             $dellock = 'nolock';
                   6865:         }
1.1198    raeburn  6866:     }
                   6867:     return ($newid,$dellock,$error);
                   6868: }
                   6869: 
1.1268    raeburn  6870: sub sixnum_code {
                   6871:     my $code;
                   6872:     for (0..6) {
                   6873:         $code .= int( rand(9) );
                   6874:     }
                   6875:     return $code;
                   6876: }
                   6877: 
1.765     albertel 6878: # -------------------------------------------------- portfolio access checking
                   6879: 
                   6880: sub portfolio_access {
1.1270    raeburn  6881:     my ($requrl,$clientip) = @_;
1.765     albertel 6882:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6883:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6884:     if ($result) {
                   6885:         my %setters;
                   6886:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6887:             my ($startblock,$endblock) =
                   6888:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6889:             if ($startblock && $endblock) {
                   6890:                 return 'B';
                   6891:             }
                   6892:         } else {
                   6893:             my ($startblock,$endblock) =
                   6894:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6895:             if ($startblock && $endblock) {
                   6896:                 return 'B';
                   6897:             }
                   6898:         }
                   6899:     }
1.765     albertel 6900:     if ($result eq 'ok') {
1.766     albertel 6901:        return 'F';
1.765     albertel 6902:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6903:        return 'A';
1.765     albertel 6904:     }
1.766     albertel 6905:     return '';
1.765     albertel 6906: }
                   6907: 
                   6908: sub get_portfolio_access {
1.1270    raeburn  6909:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6910: 
                   6911:     if (!ref($access_hash)) {
                   6912: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6913: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6914: 						   $file_name);
                   6915: 	$access_hash = $access_controls{$file_name};
                   6916:     }
                   6917: 
1.1270    raeburn  6918:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6919:     my $now = time;
                   6920:     if (ref($access_hash) eq 'HASH') {
                   6921:         foreach my $key (keys(%{$access_hash})) {
                   6922:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6923:             if ($start > $now) {
                   6924:                 next;
                   6925:             }
                   6926:             if ($end && $end<$now) {
                   6927:                 next;
                   6928:             }
                   6929:             if ($scope eq 'public') {
                   6930:                 $public = $key;
                   6931:                 last;
                   6932:             } elsif ($scope eq 'guest') {
                   6933:                 $guest = $key;
                   6934:             } elsif ($scope eq 'domains') {
                   6935:                 push(@domains,$key);
                   6936:             } elsif ($scope eq 'users') {
                   6937:                 push(@users,$key);
                   6938:             } elsif ($scope eq 'course') {
                   6939:                 push(@courses,$key);
                   6940:             } elsif ($scope eq 'group') {
                   6941:                 push(@groups,$key);
1.1270    raeburn  6942:             } elsif ($scope eq 'ip') {
                   6943:                 push(@ips,$key);
1.765     albertel 6944:             }
                   6945:         }
                   6946:         if ($public) {
                   6947:             return 'ok';
1.1270    raeburn  6948:         } elsif (@ips > 0) {
                   6949:             my $allowed;
                   6950:             foreach my $ipkey (@ips) {
                   6951:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6952:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6953:                         $allowed = 1;
                   6954:                         last; 
                   6955:                     }
                   6956:                 }
                   6957:             }
                   6958:             if ($allowed) {
                   6959:                 return 'ok';
                   6960:             }
1.765     albertel 6961:         }
                   6962:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6963:             if ($guest) {
                   6964:                 return $guest;
                   6965:             }
                   6966:         } else {
                   6967:             if (@domains > 0) {
                   6968:                 foreach my $domkey (@domains) {
                   6969:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6970:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6971:                             return 'ok';
                   6972:                         }
                   6973:                     }
                   6974:                 }
                   6975:             }
                   6976:             if (@users > 0) {
                   6977:                 foreach my $userkey (@users) {
1.865     raeburn  6978:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6979:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6980:                             if (ref($item) eq 'HASH') {
                   6981:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6982:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6983:                                     return 'ok';
                   6984:                                 }
                   6985:                             }
                   6986:                         }
                   6987:                     } 
1.765     albertel 6988:                 }
                   6989:             }
                   6990:             my %roleshash;
                   6991:             my @courses_and_groups = @courses;
                   6992:             push(@courses_and_groups,@groups); 
                   6993:             if (@courses_and_groups > 0) {
                   6994:                 my (%allgroups,%allroles); 
                   6995:                 my ($start,$end,$role,$sec,$group);
                   6996:                 foreach my $envkey (%env) {
1.1060    raeburn  6997:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6998:                         my $cid = $2.'_'.$3; 
                   6999:                         if ($1 eq 'gr') {
                   7000:                             $group = $4;
                   7001:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7002:                         } else {
                   7003:                             if ($4 eq '') {
                   7004:                                 $sec = 'none';
                   7005:                             } else {
                   7006:                                 $sec = $4;
                   7007:                             }
                   7008:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7009:                         }
1.811     albertel 7010:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7011:                         my $cid = $2.'_'.$3;
                   7012:                         if ($4 eq '') {
                   7013:                             $sec = 'none';
                   7014:                         } else {
                   7015:                             $sec = $4;
                   7016:                         }
                   7017:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7018:                     }
                   7019:                 }
                   7020:                 if (keys(%allroles) == 0) {
                   7021:                     return;
                   7022:                 }
                   7023:                 foreach my $key (@courses_and_groups) {
                   7024:                     my %content = %{$$access_hash{$key}};
                   7025:                     my $cnum = $content{'number'};
                   7026:                     my $cdom = $content{'domain'};
                   7027:                     my $cid = $cdom.'_'.$cnum;
                   7028:                     if (!exists($allroles{$cid})) {
                   7029:                         next;
                   7030:                     }    
                   7031:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7032:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7033:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7034:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7035:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7036:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7037:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7038:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7039:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7040:                                         if (grep/^all$/,@sections) {
                   7041:                                             return 'ok';
                   7042:                                         } else {
                   7043:                                             if (grep/^$sec$/,@sections) {
                   7044:                                                 return 'ok';
                   7045:                                             }
                   7046:                                         }
                   7047:                                     }
                   7048:                                 }
                   7049:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7050:                                     if (grep/^none$/,@groups) {
                   7051:                                         return 'ok';
                   7052:                                     }
                   7053:                                 } else {
                   7054:                                     if (grep/^all$/,@groups) {
                   7055:                                         return 'ok';
                   7056:                                     } 
                   7057:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7058:                                         if (grep/^$group$/,@groups) {
                   7059:                                             return 'ok';
                   7060:                                         }
                   7061:                                     }
                   7062:                                 } 
                   7063:                             }
                   7064:                         }
                   7065:                     }
                   7066:                 }
                   7067:             }
                   7068:             if ($guest) {
                   7069:                 return $guest;
                   7070:             }
                   7071:         }
                   7072:     }
                   7073:     return;
                   7074: }
                   7075: 
                   7076: sub course_group_datechecker {
                   7077:     my ($dates,$now,$status) = @_;
                   7078:     my ($start,$end) = split(/\./,$dates);
                   7079:     if (!$start && !$end) {
                   7080:         return 'ok';
                   7081:     }
                   7082:     if (grep/^active$/,@{$status}) {
                   7083:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7084:             return 'ok';
                   7085:         }
                   7086:     }
                   7087:     if (grep/^previous$/,@{$status}) {
                   7088:         if ($end > $now ) {
                   7089:             return 'ok';
                   7090:         }
                   7091:     }
                   7092:     if (grep/^future$/,@{$status}) {
                   7093:         if ($start > $now) {
                   7094:             return 'ok';
                   7095:         }
                   7096:     }
                   7097:     return; 
                   7098: }
                   7099: 
                   7100: sub parse_portfolio_url {
                   7101:     my ($url) = @_;
                   7102: 
                   7103:     my ($type,$udom,$unum,$group,$file_name);
                   7104:     
1.823     albertel 7105:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7106: 	$type = 1;
                   7107:         $udom = $1;
                   7108:         $unum = $2;
                   7109:         $file_name = $3;
1.823     albertel 7110:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7111: 	$type = 2;
                   7112:         $udom = $1;
                   7113:         $unum = $2;
                   7114:         $group = $3;
                   7115:         $file_name = $3.'/'.$4;
                   7116:     }
                   7117:     if (wantarray) {
                   7118: 	return ($type,$udom,$unum,$file_name,$group);
                   7119:     }
                   7120:     return $type;
                   7121: }
                   7122: 
                   7123: sub is_portfolio_url {
                   7124:     my ($url) = @_;
                   7125:     return scalar(&parse_portfolio_url($url));
                   7126: }
                   7127: 
1.798     raeburn  7128: sub is_portfolio_file {
                   7129:     my ($file) = @_;
1.820     raeburn  7130:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7131:         return 1;
                   7132:     }
                   7133:     return;
                   7134: }
                   7135: 
1.976     raeburn  7136: sub usertools_access {
1.1084    raeburn  7137:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7138:     my ($access,%tools);
                   7139:     if ($context eq '') {
                   7140:         $context = 'tools';
                   7141:     }
                   7142:     if ($context eq 'requestcourses') {
                   7143:         %tools = (
                   7144:                       official   => 1,
                   7145:                       unofficial => 1,
1.1006    raeburn  7146:                       community  => 1,
1.1246    raeburn  7147:                       textbook   => 1,
1.1305    raeburn  7148:                       placement  => 1,
1.1368    raeburn  7149:                       lti        => 1,
1.985     raeburn  7150:                  );
1.1183    raeburn  7151:     } elsif ($context eq 'requestauthor') {
                   7152:         %tools = (
                   7153:                       requestauthor => 1,
                   7154:                  );
1.985     raeburn  7155:     } else {
                   7156:         %tools = (
                   7157:                       aboutme   => 1,
                   7158:                       blog      => 1,
1.1177    raeburn  7159:                       webdav    => 1,
1.985     raeburn  7160:                       portfolio => 1,
                   7161:                  );
                   7162:     }
1.976     raeburn  7163:     return if (!defined($tools{$tool}));
                   7164: 
1.1242    raeburn  7165:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7166:         $udom = $env{'user.domain'};
                   7167:         $uname = $env{'user.name'};
                   7168:     }
                   7169: 
1.978     raeburn  7170:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7171:         if ($action ne 'reload') {
1.985     raeburn  7172:             if ($context eq 'requestcourses') {
                   7173:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7174:             } elsif ($context eq 'requestauthor') {
                   7175:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7176:             } else {
                   7177:                 return $env{'environment.availabletools.'.$tool};
                   7178:             }
                   7179:         }
1.976     raeburn  7180:     }
                   7181: 
1.1183    raeburn  7182:     my ($toolstatus,$inststatus,$envkey);
                   7183:     if ($context eq 'requestauthor') {
                   7184:         $envkey = $context; 
                   7185:     } else {
                   7186:         $envkey = $context.'.'.$tool;
                   7187:     }
1.976     raeburn  7188: 
1.985     raeburn  7189:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7190:          ($action ne 'reload')) {
1.1183    raeburn  7191:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7192:         $inststatus = $env{'environment.inststatus'};
                   7193:     } else {
1.1084    raeburn  7194:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7195:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7196:             $inststatus = $userenvref->{'inststatus'};
                   7197:         } else {
1.1183    raeburn  7198:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7199:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7200:             $inststatus = $userenv{'inststatus'};
                   7201:         }
1.976     raeburn  7202:     }
                   7203: 
                   7204:     if ($toolstatus ne '') {
                   7205:         if ($toolstatus) {
                   7206:             $access = 1;
                   7207:         } else {
                   7208:             $access = 0;
                   7209:         }
                   7210:         return $access;
                   7211:     }
                   7212: 
1.1084    raeburn  7213:     my ($is_adv,%domdef);
                   7214:     if (ref($is_advref) eq 'HASH') {
                   7215:         $is_adv = $is_advref->{'is_adv'};
                   7216:     } else {
                   7217:         $is_adv = &is_advanced_user($udom,$uname);
                   7218:     }
                   7219:     if (ref($domdefref) eq 'HASH') {
                   7220:         %domdef = %{$domdefref};
                   7221:     } else {
                   7222:         %domdef = &get_domain_defaults($udom);
                   7223:     }
1.976     raeburn  7224:     if (ref($domdef{$tool}) eq 'HASH') {
                   7225:         if ($is_adv) {
                   7226:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7227:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7228:                     $access = 1;
                   7229:                 } else {
                   7230:                     $access = 0;
                   7231:                 }
                   7232:                 return $access;
                   7233:             }
                   7234:         }
                   7235:         if ($inststatus ne '') {
                   7236:             my ($hasaccess,$hasnoaccess);
                   7237:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7238:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7239:                     if ($domdef{$tool}{$affiliation}) {
                   7240:                         $hasaccess = 1;
                   7241:                     } else {
                   7242:                         $hasnoaccess = 1;
                   7243:                     }
                   7244:                 }
                   7245:             }
                   7246:             if ($hasaccess || $hasnoaccess) {
                   7247:                 if ($hasaccess) {
                   7248:                     $access = 1;
                   7249:                 } elsif ($hasnoaccess) {
                   7250:                     $access = 0; 
                   7251:                 }
                   7252:                 return $access;
                   7253:             }
                   7254:         } else {
                   7255:             if ($domdef{$tool}{'default'} ne '') {
                   7256:                 if ($domdef{$tool}{'default'}) {
                   7257:                     $access = 1;
                   7258:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7259:                     $access = 0;
                   7260:                 }
                   7261:                 return $access;
                   7262:             }
                   7263:         }
                   7264:     } else {
1.1177    raeburn  7265:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7266:             $access = 1;
                   7267:         } else {
                   7268:             $access = 0;
                   7269:         }
1.976     raeburn  7270:         return $access;
                   7271:     }
                   7272: }
                   7273: 
1.1050    raeburn  7274: sub is_course_owner {
                   7275:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7276:     if (($udom eq '') || ($uname eq '')) {
                   7277:         $udom = $env{'user.domain'};
                   7278:         $uname = $env{'user.name'};
                   7279:     }
                   7280:     unless (($udom eq '') || ($uname eq '')) {
                   7281:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7282:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7283:                 return 1;
                   7284:             } else {
                   7285:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7286:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7287:                     return 1;
                   7288:                 }
                   7289:             }
                   7290:         }
                   7291:     }
                   7292:     return;
                   7293: }
                   7294: 
1.976     raeburn  7295: sub is_advanced_user {
                   7296:     my ($udom,$uname) = @_;
1.1085    raeburn  7297:     if ($udom ne '' && $uname ne '') {
                   7298:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7299:             if (wantarray) {
                   7300:                 return ($env{'user.adv'},$env{'user.author'});
                   7301:             } else {
                   7302:                 return $env{'user.adv'};
                   7303:             }
1.1085    raeburn  7304:         }
                   7305:     }
1.976     raeburn  7306:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7307:     my %allroles;
1.1128    raeburn  7308:     my ($is_adv,$is_author);
1.976     raeburn  7309:     foreach my $role (keys(%roleshash)) {
                   7310:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7311:         my $area = '/'.$tdomain.'/'.$trest;
                   7312:         if ($sec ne '') {
                   7313:             $area .= '/'.$sec;
                   7314:         }
                   7315:         if (($area ne '') && ($trole ne '')) {
                   7316:             my $spec=$trole.'.'.$area;
                   7317:             if ($trole =~ /^cr\//) {
                   7318:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7319:             } elsif ($trole ne 'gr') {
                   7320:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7321:             }
1.1128    raeburn  7322:             if ($trole eq 'au') {
                   7323:                 $is_author = 1;
                   7324:             }
1.976     raeburn  7325:         }
                   7326:     }
                   7327:     foreach my $role (keys(%allroles)) {
                   7328:         last if ($is_adv);
                   7329:         foreach my $item (split(/:/,$allroles{$role})) {
                   7330:             if ($item ne '') {
                   7331:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7332:                 if ($privilege eq 'adv') {
                   7333:                     $is_adv = 1;
                   7334:                     last;
                   7335:                 }
                   7336:             }
                   7337:         }
                   7338:     }
1.1128    raeburn  7339:     if (wantarray) {
                   7340:         return ($is_adv,$is_author);
                   7341:     }
1.976     raeburn  7342:     return $is_adv;
                   7343: }
1.798     raeburn  7344: 
1.1035    raeburn  7345: sub check_can_request {
1.1368    raeburn  7346:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7347:     my $canreq = 0;
1.1368    raeburn  7348:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7349:         $uname = $env{'user.name'};
                   7350:         $udom = $env{'user.domain'};
                   7351:     }
1.1035    raeburn  7352:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7353:     my @options = ('approval','validate','autolimit');
                   7354:     my $optregex = join('|',@options);
                   7355:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7356:         foreach my $type (@{$types}) {
1.1368    raeburn  7357:             if (&usertools_access($uname,$udom,$type,undef,
                   7358:                                   'requestcourses')) {
1.1035    raeburn  7359:                 $canreq ++;
1.1036    raeburn  7360:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7361:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7362:                 }
1.1368    raeburn  7363:                 if ($dom eq $udom) {
1.1035    raeburn  7364:                     $can_request->{$type} = 1;
                   7365:                 }
                   7366:             }
1.1368    raeburn  7367:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7368:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7369:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7370:                 if (@curr > 0) {
1.1036    raeburn  7371:                     foreach my $item (@curr) {
                   7372:                         if (ref($request_domains) eq 'HASH') {
                   7373:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7374:                             if ($otherdom ne '') {
                   7375:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7376:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7377:                                         push(@{$request_domains->{$type}},$otherdom);
                   7378:                                     }
                   7379:                                 } else {
                   7380:                                     push(@{$request_domains->{$type}},$otherdom);
                   7381:                                 }
                   7382:                             }
                   7383:                         }
                   7384:                     }
1.1368    raeburn  7385:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7386:                         $canreq ++;
1.1035    raeburn  7387:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7388:                             $can_request->{$type} = 1;
                   7389:                         }
                   7390:                     }
                   7391:                 }
                   7392:             }
                   7393:         }
                   7394:     }
                   7395:     return $canreq;
                   7396: }
                   7397: 
1.341     www      7398: # ---------------------------------------------- Custom access rule evaluation
                   7399: 
                   7400: sub customaccess {
                   7401:     my ($priv,$uri)=@_;
1.807     albertel 7402:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7403:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7404:     $udom = &LONCAPA::clean_domain($udom);
                   7405:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7406:     my $access=0;
1.800     albertel 7407:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7408: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7409: 	if ($type eq 'user') {
                   7410: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7411: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7412: 		if ($tdom) {
                   7413: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7414: 		}
1.896     albertel 7415: 		if ($tuname) {
                   7416: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7417: 		}
                   7418: 		$access=($effect eq 'allow');
                   7419: 		last;
                   7420: 	    }
                   7421: 	} else {
                   7422: 	    if ($role) {
                   7423: 		if ($role ne $urole) { next; }
                   7424: 	    }
                   7425: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7426: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7427: 		if ($tdom) {
                   7428: 		    if ($tdom ne $udom) { next; }
                   7429: 		}
                   7430: 		if ($tcrs) {
                   7431: 		    if ($tcrs ne $ucrs) { next; }
                   7432: 		}
                   7433: 		if ($tsec) {
                   7434: 		    if ($tsec ne $usec) { next; }
                   7435: 		}
                   7436: 		$access=($effect eq 'allow');
                   7437: 		last;
                   7438: 	    }
                   7439: 	    if ($realm eq '' && $role eq '') {
                   7440: 		$access=($effect eq 'allow');
                   7441: 	    }
1.402     bowersj2 7442: 	}
1.341     www      7443:     }
                   7444:     return $access;
                   7445: }
                   7446: 
1.103     harris41 7447: # ------------------------------------------------- Check for a user privilege
1.12      www      7448: 
                   7449: sub allowed {
1.1281    raeburn  7450:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7451:     my $ver_orguri=$uri;
1.439     www      7452:     $uri=&deversion($uri);
1.152     www      7453:     my $orguri=$uri;
1.52      www      7454:     $uri=&declutter($uri);
1.809     raeburn  7455: 
1.810     raeburn  7456:     if ($priv eq 'evb') {
                   7457: # Evade communication block restrictions for specified role in a course
                   7458:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7459:             return $1;
                   7460:         } else {
                   7461:             return;
                   7462:         }
                   7463:     }
                   7464: 
1.620     albertel 7465:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7466: # Free bre access to adm and meta resources
1.1343    raeburn  7467:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7468: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7469: 	&& ($priv eq 'bre')) {
1.14      www      7470: 	return 'F';
1.159     www      7471:     }
                   7472: 
1.545     banghart 7473: # Free bre access to user's own portfolio contents
1.714     raeburn  7474:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7475:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7476: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7477:         my %setters;
                   7478:         my ($startblock,$endblock) = 
                   7479:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7480:         if ($startblock && $endblock) {
                   7481:             return 'B';
                   7482:         } else {
                   7483:             return 'F';
                   7484:         }
1.545     banghart 7485:     }
                   7486: 
1.762     raeburn  7487: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7488:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7489:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7490:         if (exists($env{'request.course.id'})) {
                   7491:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7492:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7493:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7494:                 my $courseprivid=$env{'request.course.id'};
                   7495:                 $courseprivid=~s/\_/\//;
                   7496:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7497:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7498:                     return $1; 
1.762     raeburn  7499:                 } else {
                   7500:                     if ($env{'request.course.sec'}) {
                   7501:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7502:                     }
                   7503:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7504:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7505:                         return $2;
                   7506:                     }
1.714     raeburn  7507:                 }
                   7508:             }
                   7509:         }
                   7510:     }
                   7511: 
1.159     www      7512: # Free bre to public access
                   7513: 
                   7514:     if ($priv eq 'bre') {
1.1362    raeburn  7515:         my $copyright;
                   7516:         unless ($uri =~ /ext\.tool/) {
                   7517:             $copyright=&metadata($uri,'copyright');
                   7518:         }
1.620     albertel 7519: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7520:            return 'F'; 
                   7521:         }
1.238     www      7522:         if ($copyright eq 'priv') {
                   7523:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7524: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7525: 		return '';
                   7526:             }
                   7527:         }
                   7528:         if ($copyright eq 'domain') {
                   7529:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7530: 	    unless (($env{'user.domain'} eq $1) ||
                   7531:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7532: 		return '';
                   7533:             }
1.262     matthew  7534:         }
1.620     albertel 7535:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7536:             # Library role, so allow browsing of resources in this domain.
                   7537:             return 'F';
1.238     www      7538:         }
1.341     www      7539:         if ($copyright eq 'custom') {
                   7540: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7541:         }
1.14      www      7542:     }
1.264     matthew  7543:     # Domain coordinator is trying to create a course
1.620     albertel 7544:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7545:         # uri is the requested domain in this case.
                   7546:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7547:         # a role of dc for the domain in question.
1.620     albertel 7548:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7549:     }
1.29      www      7550: 
1.52      www      7551:     my $thisallowed='';
                   7552:     my $statecond=0;
                   7553:     my $courseprivid='';
                   7554: 
1.1039    raeburn  7555:     my $ownaccess;
1.1043    raeburn  7556:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7557:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7558:         if ($uri eq '') {
                   7559:             $ownaccess = 1;
                   7560:         } else {
                   7561:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7562:                 my $udom = $env{'user.domain'};
                   7563:                 my $uname = $env{'user.name'};
                   7564:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7565:                     $ownaccess = 1;
1.1040    raeburn  7566:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7567:                     unless ($uri =~ m{\.\./}) {
                   7568:                         $ownaccess = 1;
                   7569:                     }
                   7570:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7571:                     my $now = time;
                   7572:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7573:                         my $adom = $1;
                   7574:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7575:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7576:                                 my ($start,$end) = split('.',$env{$key});
                   7577:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7578:                                     $ownaccess = 1;
                   7579:                                     last;
                   7580:                                 }
                   7581:                             }
                   7582:                         }
                   7583:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7584:                         my $adom = $1;
                   7585:                         my $aname = $2;
1.1042    raeburn  7586:                         foreach my $role ('ca','aa') { 
                   7587:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7588:                                 my ($start,$end) =
                   7589:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7590:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7591:                                     $ownaccess = 1;
                   7592:                                     last;
                   7593:                                 }
1.1039    raeburn  7594:                             }
                   7595:                         }
                   7596:                     }
                   7597:                 }
                   7598:             }
                   7599:         }
                   7600:     }
                   7601: 
1.52      www      7602: # Course
                   7603: 
1.620     albertel 7604:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7605:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7606:             $thisallowed.=$1;
                   7607:         }
1.52      www      7608:     }
1.29      www      7609: 
1.52      www      7610: # Domain
                   7611: 
1.620     albertel 7612:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7613:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7614:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7615:             $thisallowed.=$1;
                   7616:         }
1.12      www      7617:     }
1.52      www      7618: 
1.1141    raeburn  7619: # User who is not author or co-author might still be able to edit
                   7620: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7621:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7622:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7623:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7624:             $thisallowed.=$1;
                   7625:         }
                   7626:     }
                   7627: 
1.52      www      7628: # Course: uri itself is a course
1.66      www      7629:     my $courseuri=$uri;
                   7630:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7631:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7632: 
1.620     albertel 7633:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7634:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7635:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7636:             $thisallowed.=$1;
                   7637:         }
1.12      www      7638:     }
1.29      www      7639: 
1.665     albertel 7640: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7641: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7642:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7643: 	$thisallowed='';
1.671     raeburn  7644:         my ($match)=&is_on_map($uri);
                   7645:         if ($match) {
                   7646:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7647:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7648:                 my $value = $1;
                   7649:                 if ($noblockcheck) {
                   7650:                     $thisallowed.=$value;
1.1162    raeburn  7651:                 } else {
1.1281    raeburn  7652:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7653:                     if (@blockers > 0) {
                   7654:                         $thisallowed = 'B';
                   7655:                     } else {
                   7656:                         $thisallowed.=$value;
                   7657:                     }
1.1162    raeburn  7658:                 }
1.671     raeburn  7659:             }
                   7660:         } else {
1.705     albertel 7661:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7662:             if ($refuri) {
                   7663:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7664:                     $thisallowed='F';
1.671     raeburn  7665:                 } else {
                   7666:                     $refuri=&declutter($refuri);
                   7667:                     my ($match) = &is_on_map($refuri);
                   7668:                     if ($match) {
1.1281    raeburn  7669:                         if ($noblockcheck) {
                   7670:                             $thisallowed='F';
1.1162    raeburn  7671:                         } else {
1.1281    raeburn  7672:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7673:                             if (@blockers > 0) {
                   7674:                                 $thisallowed = 'B';
                   7675:                             } else {
                   7676:                                 $thisallowed='F';
                   7677:                             }
1.1162    raeburn  7678:                         }
1.671     raeburn  7679:                     }
1.669     raeburn  7680:                 }
1.671     raeburn  7681:             }
                   7682:         }
1.314     www      7683:     }
1.492     albertel 7684: 
1.766     albertel 7685:     if ($priv eq 'bre'
                   7686: 	&& $thisallowed ne 'F' 
                   7687: 	&& $thisallowed ne '2'
                   7688: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7689: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7690:     }
1.1250    raeburn  7691: 
1.52      www      7692: # Full access at system, domain or course-wide level? Exit.
1.29      www      7693:     if ($thisallowed=~/F/) {
                   7694: 	return 'F';
                   7695:     }
                   7696: 
1.52      www      7697: # If this is generating or modifying users, exit with special codes
1.29      www      7698: 
1.643     www      7699:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7700: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7701: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7702: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7703: 	    unless ($auname) { return $thisallowed; }
                   7704: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7705: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7706: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7707: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7708: 	}
1.52      www      7709: 	return $thisallowed;
                   7710:     }
                   7711: #
1.103     harris41 7712: # Gathered so far: system, domain and course wide privileges
1.52      www      7713: #
                   7714: # Course: See if uri or referer is an individual resource that is part of 
                   7715: # the course
                   7716: 
1.620     albertel 7717:     if ($env{'request.course.id'}) {
1.232     www      7718: 
1.620     albertel 7719:        $courseprivid=$env{'request.course.id'};
                   7720:        if ($env{'request.course.sec'}) {
                   7721:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7722:        }
                   7723:        $courseprivid=~s/\_/\//;
                   7724:        my $checkreferer=1;
1.232     www      7725:        my ($match,$cond)=&is_on_map($uri);
                   7726:        if ($match) {
                   7727:            $statecond=$cond;
1.620     albertel 7728:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7729:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7730:                my $value = $1;
                   7731:                if ($priv eq 'bre') {
1.1281    raeburn  7732:                    if ($noblockcheck) {
                   7733:                        $thisallowed.=$value;
1.1162    raeburn  7734:                    } else {
1.1281    raeburn  7735:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7736:                        if (@blockers > 0) {
                   7737:                            $thisallowed = 'B';
                   7738:                        } else {
                   7739:                            $thisallowed.=$value;
                   7740:                        }
1.1162    raeburn  7741:                    }
                   7742:                } else {
                   7743:                    $thisallowed.=$value;
                   7744:                }
1.52      www      7745:                $checkreferer=0;
                   7746:            }
1.29      www      7747:        }
1.83      www      7748:        
1.148     www      7749:        if ($checkreferer) {
1.620     albertel 7750: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7751:             unless ($refuri) {
1.800     albertel 7752:                 foreach my $key (keys(%env)) {
                   7753: 		    if ($key=~/^httpref\..*\*/) {
                   7754: 			my $pattern=$key;
1.156     www      7755:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7756:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7757:                         $pattern=~s/\//\\\//g;
1.152     www      7758:                         if ($orguri=~/$pattern/) {
1.800     albertel 7759: 			    $refuri=$env{$key};
1.148     www      7760:                         }
                   7761:                     }
1.191     harris41 7762:                 }
1.148     www      7763:             }
1.232     www      7764: 
1.148     www      7765:          if ($refuri) { 
1.152     www      7766: 	  $refuri=&declutter($refuri);
1.232     www      7767:           my ($match,$cond)=&is_on_map($refuri);
                   7768:             if ($match) {
                   7769:               my $refstatecond=$cond;
1.620     albertel 7770:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7771:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7772:                   my $value = $1;
                   7773:                   if ($priv eq 'bre') {
1.1281    raeburn  7774:                       if ($noblockcheck) {
                   7775:                           $thisallowed.=$value;
1.1162    raeburn  7776:                       } else {
1.1281    raeburn  7777:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7778:                           if (@blockers > 0) {
                   7779:                               $thisallowed = 'B';
                   7780:                           } else {
                   7781:                               $thisallowed.=$value;
                   7782:                           }
1.1162    raeburn  7783:                       }
                   7784:                   } else {
                   7785:                       $thisallowed.=$value;
                   7786:                   }
1.53      www      7787:                   $uri=$refuri;
                   7788:                   $statecond=$refstatecond;
1.52      www      7789:               }
                   7790:           }
1.148     www      7791:         }
1.29      www      7792:        }
1.52      www      7793:    }
1.29      www      7794: 
1.52      www      7795: #
1.103     harris41 7796: # Gathered now: all privileges that could apply, and condition number
1.52      www      7797: # 
                   7798: #
                   7799: # Full or no access?
                   7800: #
1.29      www      7801: 
1.52      www      7802:     if ($thisallowed=~/F/) {
                   7803: 	return 'F';
                   7804:     }
1.29      www      7805: 
1.52      www      7806:     unless ($thisallowed) {
                   7807:         return '';
                   7808:     }
1.29      www      7809: 
1.52      www      7810: # Restrictions exist, deal with them
                   7811: #
                   7812: #   C:according to course preferences
                   7813: #   R:according to resource settings
                   7814: #   L:unless locked
                   7815: #   X:according to user session state
                   7816: #
                   7817: 
                   7818: # Possibly locked functionality, check all courses
1.54      www      7819: # Locks might take effect only after 10 minutes cache expiration for other
                   7820: # courses, and 2 minutes for current course
1.52      www      7821: 
                   7822:     my $envkey;
                   7823:     if ($thisallowed=~/L/) {
1.1000    raeburn  7824:         foreach $envkey (keys(%env)) {
1.54      www      7825:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7826:                my $courseid=$2;
                   7827:                my $roleid=$1.'.'.$2;
1.92      www      7828:                $courseid=~s/^\///;
1.54      www      7829:                my $expiretime=600;
1.620     albertel 7830:                if ($env{'request.role'} eq $roleid) {
1.54      www      7831: 		  $expiretime=120;
                   7832:                }
                   7833: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7834:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7835:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7836: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7837:                }
1.620     albertel 7838:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7839:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7840: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7841:                        &log($env{'user.domain'},$env{'user.name'},
                   7842:                             $env{'user.home'},
1.57      www      7843:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7844:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7845:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7846: 		       return '';
                   7847:                    }
                   7848:                }
1.620     albertel 7849:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7850:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7851: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7852:                        &log($env{'user.domain'},$env{'user.name'},
                   7853:                             $env{'user.home'},
1.57      www      7854:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7855:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7856:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7857: 		       return '';
                   7858:                    }
                   7859:                }
                   7860: 	   }
1.29      www      7861:        }
1.52      www      7862:     }
                   7863:    
                   7864: #
                   7865: # Rest of the restrictions depend on selected course
                   7866: #
                   7867: 
1.620     albertel 7868:     unless ($env{'request.course.id'}) {
1.766     albertel 7869: 	if ($thisallowed eq 'A') {
                   7870: 	    return 'A';
1.814     raeburn  7871:         } elsif ($thisallowed eq 'B') {
                   7872:             return 'B';
1.766     albertel 7873: 	} else {
                   7874: 	    return '1';
                   7875: 	}
1.52      www      7876:     }
1.29      www      7877: 
1.52      www      7878: #
                   7879: # Now user is definitely in a course
                   7880: #
1.53      www      7881: 
                   7882: 
                   7883: # Course preferences
                   7884: 
                   7885:    if ($thisallowed=~/C/) {
1.620     albertel 7886:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7887:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7888:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7889: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7890: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7891: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7892: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7893: 			$env{'request.course.id'});
                   7894: 	   }
1.237     www      7895:            return '';
                   7896:        }
                   7897: 
1.620     albertel 7898:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7899: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7900: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7901: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7902: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7903: 			$env{'request.course.id'});
                   7904: 	   }
1.54      www      7905:            return '';
                   7906:        }
1.53      www      7907:    }
                   7908: 
                   7909: # Resource preferences
                   7910: 
                   7911:    if ($thisallowed=~/R/) {
1.620     albertel 7912:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7913:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7914: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7915: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7916: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7917: 	   }
                   7918: 	   return '';
1.54      www      7919:        }
1.53      www      7920:    }
1.30      www      7921: 
1.246     www      7922: # Restricted by state or randomout?
1.30      www      7923: 
1.52      www      7924:    if ($thisallowed=~/X/) {
1.620     albertel 7925:       if ($env{'acc.randomout'}) {
1.579     albertel 7926: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7927:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7928:             return ''; 
                   7929:          }
1.247     www      7930:       }
                   7931:       if (&condval($statecond)) {
1.52      www      7932: 	 return '2';
                   7933:       } else {
                   7934:          return '';
                   7935:       }
                   7936:    }
1.30      www      7937: 
1.766     albertel 7938:     if ($thisallowed eq 'A') {
                   7939: 	return 'A';
1.814     raeburn  7940:     } elsif ($thisallowed eq 'B') {
                   7941:         return 'B';
1.766     albertel 7942:     }
1.52      www      7943:    return 'F';
1.232     www      7944: }
1.1162    raeburn  7945: 
1.1192    raeburn  7946: # ------------------------------------------- Check construction space access
                   7947: 
                   7948: sub constructaccess {
                   7949:     my ($url,$setpriv)=@_;
                   7950: 
                   7951: # We do not allow editing of previous versions of files
                   7952:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7953: 
                   7954: # Get username and domain from URL
                   7955:     my ($ownername,$ownerdomain,$ownerhome);
                   7956: 
                   7957:     ($ownerdomain,$ownername) =
1.1325    raeburn  7958:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7959: 
                   7960: # The URL does not really point to any authorspace, forget it
                   7961:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7962: 
                   7963: # Now we need to see if the user has access to the authorspace of
                   7964: # $ownername at $ownerdomain
                   7965: 
                   7966:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7967: # Real author for this?
                   7968:        $ownerhome = $env{'user.home'};
                   7969:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7970:           return ($ownername,$ownerdomain,$ownerhome);
                   7971:        }
                   7972:     } else {
                   7973: # Co-author for this?
                   7974:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7975:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7976:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7977:             return ($ownername,$ownerdomain,$ownerhome);
                   7978:         }
1.1312    raeburn  7979:         if ($env{'request.course.id'}) {
                   7980:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7981:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7982:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7983:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7984:                     return ($ownername,$ownerdomain,$ownerhome);
                   7985:                 }
                   7986:             }
                   7987:         }
1.1192    raeburn  7988:     }
                   7989: 
                   7990: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7991: # we might as well leave
                   7992:    unless ($setpriv) { return ''; }
                   7993: 
                   7994: # Backdoor access?
                   7995:     my $allowed=&allowed('eco',$ownerdomain);
                   7996: # Nope
                   7997:     unless ($allowed) { return ''; }
                   7998: # Looks like we may have access, but could be locked by the owner of the construction space
                   7999:     if ($allowed eq 'U') {
                   8000:         my %blocked=&get('environment',['domcoord.author'],
                   8001:                          $ownerdomain,$ownername);
                   8002: # Is blocked by owner
                   8003:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8004:     }
                   8005:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8006: # Grant temporary access
                   8007:         my $then=$env{'user.login.time'};
1.1209    raeburn  8008:         my $update=$env{'user.update.time'};
1.1192    raeburn  8009:         if (!$update) { $update = $then; }
                   8010:         my $refresh=$env{'user.refresh.time'};
                   8011:         if (!$refresh) { $refresh = $update; }
                   8012:         my $now = time;
                   8013:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8014:                            $now,'ca','constructaccess');
                   8015:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8016:         return($ownername,$ownerdomain,$ownerhome);
                   8017:     }
                   8018: # No business here
                   8019:     return '';
                   8020: }
                   8021: 
1.1282    raeburn  8022: # ----------------------------------------------------------- Content Blocking
                   8023: 
                   8024: {
                   8025: # Caches for faster Course Contents display where content blocking
                   8026: # is in operation (i.e., interval param set) for timed quiz.
                   8027: #
                   8028: # User for whom data are being temporarily cached.
                   8029: my $cacheduser='';
                   8030: # Cached blockers for this user (a hash of blocking items). 
                   8031: my %cachedblockers=();
                   8032: # When the data were last cached.
                   8033: my $cachedlast='';
                   8034: 
                   8035: sub load_all_blockers {
                   8036:     my ($uname,$udom,$blocks)=@_;
                   8037:     if (($uname ne '') && ($udom ne '')) { 
                   8038:         if (($cacheduser eq $uname.':'.$udom) &&
                   8039:             (abs($cachedlast-time)<5)) {
                   8040:             return;
                   8041:         }
                   8042:     }
                   8043:     $cachedlast=time;
                   8044:     $cacheduser=$uname.':'.$udom;
                   8045:     %cachedblockers = &get_commblock_resources($blocks);
                   8046: }
                   8047: 
1.1162    raeburn  8048: sub get_comm_blocks {
                   8049:     my ($cdom,$cnum) = @_;
                   8050:     if ($cdom eq '' || $cnum eq '') {
                   8051:         return unless ($env{'request.course.id'});
                   8052:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8053:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8054:     }
                   8055:     my %commblocks;
                   8056:     my $hashid=$cdom.'_'.$cnum;
                   8057:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8058:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8059:         %commblocks = %{$blocksref};
                   8060:     } else {
                   8061:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8062:         my $cachetime = 600;
                   8063:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8064:     }
                   8065:     return %commblocks;
                   8066: }
                   8067: 
1.1282    raeburn  8068: sub get_commblock_resources {
                   8069:     my ($blocks) = @_;
                   8070:     my %blockers = ();
                   8071:     return %blockers unless ($env{'request.course.id'});
                   8072:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8073:     my %commblocks;
                   8074:     if (ref($blocks) eq 'HASH') {
                   8075:         %commblocks = %{$blocks};
                   8076:     } else {
                   8077:         %commblocks = &get_comm_blocks();
                   8078:     }
1.1282    raeburn  8079:     return %blockers unless (keys(%commblocks) > 0); 
                   8080:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8081:     return %blockers unless (ref($navmap));
1.1162    raeburn  8082:     my $now = time;
                   8083:     foreach my $block (keys(%commblocks)) {
                   8084:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8085:             my ($start,$end) = ($1,$2);
                   8086:             if ($start <= $now && $end >= $now) {
                   8087:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8088:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8089:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8090:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8091:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8092:                             }
                   8093:                         }
                   8094:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8095:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8096:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8097:                             }
                   8098:                         }
                   8099:                     }
                   8100:                 }
                   8101:             }
                   8102:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8103:             my $item = $1;
1.1163    raeburn  8104:             my @to_test;
1.1162    raeburn  8105:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8106:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8107:                     my @interval;
                   8108:                     my $type = 'map';
                   8109:                     if ($item eq 'course') {
                   8110:                         $type = 'course';
                   8111:                         @interval=&EXT("resource.0.interval");
                   8112:                     } else {
                   8113:                         if ($item =~ /___\d+___/) {
                   8114:                             $type = 'resource';
                   8115:                             @interval=&EXT("resource.0.interval",$item);
                   8116:                             if (ref($navmap)) {                        
                   8117:                                 my $res = $navmap->getBySymb($item); 
                   8118:                                 push(@to_test,$res);
                   8119:                             }
1.1162    raeburn  8120:                         } else {
1.1282    raeburn  8121:                             my $mapsymb = &symbread($item,1);
                   8122:                             if ($mapsymb) {
                   8123:                                 if (ref($navmap)) {
                   8124:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8125:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8126:                                     foreach my $res (@to_test) {
                   8127:                                         my $symb = $res->symb();
                   8128:                                         next if ($symb eq $mapsymb);
                   8129:                                         if ($symb ne '') {
                   8130:                                             @interval=&EXT("resource.0.interval",$symb);
                   8131:                                             if ($interval[1] eq 'map') {
                   8132:                                                 last;
1.1162    raeburn  8133:                                             }
                   8134:                                         }
                   8135:                                     }
                   8136:                                 }
                   8137:                             }
                   8138:                         }
1.1282    raeburn  8139:                     }
1.1310    raeburn  8140:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8141:                         my $timelimit = $1; 
1.1282    raeburn  8142:                         my $first_access;
                   8143:                         if ($type eq 'resource') {
                   8144:                             $first_access=&get_first_access($interval[1],$item);
                   8145:                         } elsif ($type eq 'map') {
                   8146:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8147:                         } else {
                   8148:                             $first_access=&get_first_access($interval[1]);
                   8149:                         }
                   8150:                         if ($first_access) {
1.1292    raeburn  8151:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8152:                             if ($timesup > $now) {
                   8153:                                 my $activeblock;
                   8154:                                 foreach my $res (@to_test) {
1.1283    raeburn  8155:                                     if ($res->answerable()) {
1.1282    raeburn  8156:                                         $activeblock = 1;
                   8157:                                         last;
                   8158:                                     }
                   8159:                                 }
                   8160:                                 if ($activeblock) {
                   8161:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8162:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8163:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8164:                                          }
                   8165:                                     }
                   8166:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8167:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8168:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8169:                                         }
1.1162    raeburn  8170:                                     }
                   8171:                                 }
                   8172:                             }
                   8173:                         }
                   8174:                     }
                   8175:                 }
                   8176:             }
                   8177:         }
                   8178:     }
1.1282    raeburn  8179:     return %blockers;
1.1162    raeburn  8180: }
                   8181: 
1.1282    raeburn  8182: sub has_comm_blocking {
                   8183:     my ($priv,$symb,$uri,$blocks) = @_;
                   8184:     my @blockers;
                   8185:     return unless ($env{'request.course.id'});
                   8186:     return unless ($priv eq 'bre');
                   8187:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8188:     return if ($env{'request.state'} eq 'construct');
                   8189:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8190:     return unless (keys(%cachedblockers) > 0);
                   8191:     my (%possibles,@symbs);
                   8192:     if (!$symb) {
                   8193:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8194:     }
1.1282    raeburn  8195:     if ($symb) {
                   8196:         @symbs = ($symb);
                   8197:     } elsif (keys(%possibles)) { 
                   8198:         @symbs = keys(%possibles);
                   8199:     }
                   8200:     my $noblock;
                   8201:     foreach my $symb (@symbs) {
                   8202:         last if ($noblock);
                   8203:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8204:         foreach my $block (keys(%cachedblockers)) {
                   8205:             if ($block =~ /^firstaccess____(.+)$/) {
                   8206:                 my $item = $1;
                   8207:                 if (($item eq $map) || ($item eq $symb)) {
                   8208:                     $noblock = 1;
                   8209:                     last;
                   8210:                 }
                   8211:             }
                   8212:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8213:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8214:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8215:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8216:                             push(@blockers,$block);
                   8217:                         }
                   8218:                     }
                   8219:                 }
1.1162    raeburn  8220:             }
1.1282    raeburn  8221:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8222:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8223:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8224:                         push(@blockers,$block);
                   8225:                     }
                   8226:                 }
1.1162    raeburn  8227:             }
                   8228:         }
                   8229:     }
1.1282    raeburn  8230:     return if ($noblock);
                   8231:     return @blockers;
                   8232: }
1.1162    raeburn  8233: }
                   8234: 
1.1282    raeburn  8235: # -------------------------------- Deversion and split uri into path an filename   
                   8236: 
1.1133    foxr     8237: #
1.1282    raeburn  8238: #   Removes the version from a URI and
1.1133    foxr     8239: #   splits it in to its filename and path to the filename.
                   8240: #   Seems like File::Basename could have done this more clearly.
                   8241: #   Parameters:
                   8242: #      $uri   - input URI
                   8243: #   Returns:
                   8244: #     Two element list consisting of 
                   8245: #     $pathname  - the URI up to and excluding the trailing /
                   8246: #     $filename  - The part of the URI following the last /
                   8247: #  NOTE:
                   8248: #    Another realization of this is simply:
                   8249: #    use File::Basename;
                   8250: #    ...
                   8251: #    $uri = shift;
                   8252: #    $filename = basename($uri);
                   8253: #    $path     = dirname($uri);
                   8254: #    return ($filename, $path);
                   8255: #
                   8256: #     The implementation below is probably faster however.
                   8257: #
1.710     albertel 8258: sub split_uri_for_cond {
                   8259:     my $uri=&deversion(&declutter(shift));
                   8260:     my @uriparts=split(/\//,$uri);
                   8261:     my $filename=pop(@uriparts);
                   8262:     my $pathname=join('/',@uriparts);
                   8263:     return ($pathname,$filename);
                   8264: }
1.232     www      8265: # --------------------------------------------------- Is a resource on the map?
                   8266: 
                   8267: sub is_on_map {
1.710     albertel 8268:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8269:     #Trying to find the conditional for the file
1.620     albertel 8270:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8271: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8272:     if ($match) {
1.289     bowersj2 8273: 	return (1,$1);
                   8274:     } else {
1.434     www      8275: 	return (0,0);
1.289     bowersj2 8276:     }
1.12      www      8277: }
                   8278: 
1.427     www      8279: # --------------------------------------------------------- Get symb from alias
                   8280: 
                   8281: sub get_symb_from_alias {
                   8282:     my $symb=shift;
                   8283:     my ($map,$resid,$url)=&decode_symb($symb);
                   8284: # Already is a symb
                   8285:     if ($url) { return $symb; }
                   8286: # Must be an alias
                   8287:     my $aliassymb='';
                   8288:     my %bighash;
1.620     albertel 8289:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8290:                             &GDBM_READER(),0640)) {
                   8291:         my $rid=$bighash{'mapalias_'.$symb};
                   8292: 	if ($rid) {
                   8293: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8294: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8295: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8296: 	}
                   8297:         untie %bighash;
                   8298:     }
                   8299:     return $aliassymb;
                   8300: }
                   8301: 
1.12      www      8302: # ----------------------------------------------------------------- Define Role
                   8303: 
                   8304: sub definerole {
                   8305:   if (allowed('mcr','/')) {
1.1326    raeburn  8306:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8307:     foreach my $role (split(':',$sysrole)) {
                   8308: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8309:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8310:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8311: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8312:                return "refused:s:$crole&$cqual"; 
                   8313:             }
                   8314:         }
1.191     harris41 8315:     }
1.800     albertel 8316:     foreach my $role (split(':',$domrole)) {
                   8317: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8318:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8319:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8320: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8321:                return "refused:d:$crole&$cqual"; 
                   8322:             }
                   8323:         }
1.191     harris41 8324:     }
1.800     albertel 8325:     foreach my $role (split(':',$courole)) {
                   8326: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8327:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8328:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8329: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8330:                return "refused:c:$crole&$cqual"; 
                   8331:             }
                   8332:         }
1.191     harris41 8333:     }
1.1326    raeburn  8334:     my $uhome;
                   8335:     if (($uname ne '') && ($udom ne '')) {
                   8336:         $uhome = &homeserver($uname,$udom);
                   8337:         return $uhome if ($uhome eq 'no_host');
                   8338:     } else {
                   8339:         $uname = $env{'user.name'};
                   8340:         $udom = $env{'user.domain'};
                   8341:         $uhome = $env{'user.home'};
                   8342:     }
1.620     albertel 8343:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8344:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8345:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8346:     return reply($command,$uhome);
1.12      www      8347:   } else {
                   8348:     return 'refused';
                   8349:   }
1.105     harris41 8350: }
                   8351: 
                   8352: # ---------------- Make a metadata query against the network of library servers
                   8353: 
                   8354: sub metadata_query {
1.1237    raeburn  8355:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8356:     my %rhash;
1.845     albertel 8357:     my %libserv = &all_library();
1.244     matthew  8358:     my @server_list = (defined($server_array) ? @$server_array
                   8359:                                               : keys(%libserv) );
                   8360:     for my $server (@server_list) {
1.1237    raeburn  8361:         my $domains = ''; 
                   8362:         if (ref($domains_hash) eq 'HASH') {
                   8363:             $domains = $domains_hash->{$server}; 
                   8364:         }
1.118     harris41 8365: 	unless ($custom or $customshow) {
1.1237    raeburn  8366: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8367: 	    $rhash{$server}=$reply;
                   8368: 	}
                   8369: 	else {
                   8370: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8371: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8372: 			     $server);
                   8373: 	    $rhash{$server}=$reply;
                   8374: 	}
1.112     harris41 8375:     }
1.118     harris41 8376:     return \%rhash;
1.240     www      8377: }
                   8378: 
                   8379: # ----------------------------------------- Send log queries and wait for reply
                   8380: 
                   8381: sub log_query {
                   8382:     my ($uname,$udom,$query,%filters)=@_;
                   8383:     my $uhome=&homeserver($uname,$udom);
                   8384:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8385:     my $uhost=&hostname($uhome);
1.800     albertel 8386:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8387:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8388:                        $uhome);
1.479     albertel 8389:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8390:     return get_query_reply($queryid);
                   8391: }
                   8392: 
1.818     raeburn  8393: # -------------------------- Update MySQL table for portfolio file
                   8394: 
                   8395: sub update_portfolio_table {
1.821     raeburn  8396:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8397:     if ($group ne '') {
                   8398:         $file_name =~s /^\Q$group\E//;
                   8399:     }
1.818     raeburn  8400:     my $homeserver = &homeserver($uname,$udom);
                   8401:     my $queryid=
1.821     raeburn  8402:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8403:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8404:     my $reply = &get_query_reply($queryid);
                   8405:     return $reply;
                   8406: }
                   8407: 
1.899     raeburn  8408: # -------------------------- Update MySQL allusers table
                   8409: 
                   8410: sub update_allusers_table {
                   8411:     my ($uname,$udom,$names) = @_;
                   8412:     my $homeserver = &homeserver($uname,$udom);
                   8413:     my $queryid=
                   8414:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8415:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8416:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8417:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8418:                'generation='.&escape($names->{'generation'}).'%%'.
                   8419:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8420:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8421:     return;
1.899     raeburn  8422: }
                   8423: 
1.508     raeburn  8424: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8425: 
                   8426: sub fetch_enrollment_query {
1.511     raeburn  8427:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8428:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8429:     my $maxtries = 1;
1.508     raeburn  8430:     if ($context eq 'automated') {
                   8431:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8432:         $sleep = 2;
                   8433:         $loopmax = 100;
1.547     raeburn  8434:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8435:     } else {
                   8436:         $homeserver = &homeserver($cnum,$dom);
                   8437:     }
1.838     albertel 8438:     my $host=&hostname($homeserver);
1.506     raeburn  8439:     my $cmd = '';
1.1000    raeburn  8440:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8441:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8442:     }
                   8443:     $cmd =~ s/%%$//;
                   8444:     $cmd = &escape($cmd);
                   8445:     my $query = 'fetchenrollment';
1.620     albertel 8446:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8447:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8448:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8449:         return 'error: '.$queryid;
                   8450:     }
1.1317    raeburn  8451:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8452:     my $tries = 1;
                   8453:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8454:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8455:         $tries ++;
                   8456:     }
1.526     raeburn  8457:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8458:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8459:     } else {
1.901     albertel 8460:         my @responses = split(/:/,$reply);
1.1322    raeburn  8461:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8462:             foreach my $line (@responses) {
                   8463:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8464:                 $$replyref{$key} = $value;
                   8465:             }
                   8466:         } else {
1.1117    foxr     8467:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8468:             foreach my $line (@responses) {
                   8469:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8470:                 $$replyref{$key} = $value;
                   8471:                 if ($value > 0) {
1.800     albertel 8472:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8473:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8474:                         my $destname = $pathname.'/'.$filename;
                   8475:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8476:                         if ($xml_classlist =~ /^error/) {
                   8477:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8478:                         } else {
1.1359    raeburn  8479:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8480:                                 print FILE &unescape($xml_classlist);
                   8481:                                 close(FILE);
1.526     raeburn  8482:                             } else {
                   8483:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8484:                             }
                   8485:                         }
                   8486:                     }
                   8487:                 }
                   8488:             }
                   8489:         }
                   8490:         return 'ok';
                   8491:     }
                   8492:     return 'error';
                   8493: }
                   8494: 
1.242     www      8495: sub get_query_reply {
1.1317    raeburn  8496:     my ($queryid,$sleep,$loopmax) = @_;;
                   8497:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8498:         $sleep = 0.2;
                   8499:     }
                   8500:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8501:         $loopmax = 100;
                   8502:     }
1.1117    foxr     8503:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8504:     my $reply='';
1.1317    raeburn  8505:     for (1..$loopmax) {
                   8506: 	sleep($sleep);
1.240     www      8507:         if (-e $replyfile.'.end') {
1.1359    raeburn  8508: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8509: 		$reply = join('',<$fh>);
                   8510: 		close($fh);
1.240     www      8511: 	   } else { return 'error: reply_file_error'; }
1.242     www      8512:            return &unescape($reply);
                   8513: 	}
1.240     www      8514:     }
1.242     www      8515:     return 'timeout:'.$queryid;
1.240     www      8516: }
                   8517: 
                   8518: sub courselog_query {
1.241     www      8519: #
                   8520: # possible filters:
                   8521: # url: url or symb
                   8522: # username
                   8523: # domain
                   8524: # action: view, submit, grade
                   8525: # start: timestamp
                   8526: # end: timestamp
                   8527: #
1.240     www      8528:     my (%filters)=@_;
1.620     albertel 8529:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8530:     if ($filters{'url'}) {
                   8531: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8532:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8533:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8534:     }
1.620     albertel 8535:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8536:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8537:     return &log_query($cname,$cdom,'courselog',%filters);
                   8538: }
                   8539: 
                   8540: sub userlog_query {
1.858     raeburn  8541: #
                   8542: # possible filters:
                   8543: # action: log check role
                   8544: # start: timestamp
                   8545: # end: timestamp
                   8546: #
1.240     www      8547:     my ($uname,$udom,%filters)=@_;
                   8548:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8549: }
                   8550: 
1.506     raeburn  8551: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8552: 
                   8553: sub auto_run {
1.508     raeburn  8554:     my ($cnum,$cdom) = @_;
1.876     raeburn  8555:     my $response = 0;
                   8556:     my $settings;
                   8557:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8558:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8559:         $settings = $domconfig{'autoenroll'};
                   8560:         if ($settings->{'run'} eq '1') {
                   8561:             $response = 1;
                   8562:         }
                   8563:     } else {
1.934     raeburn  8564:         my $homeserver;
                   8565:         if (&is_course($cdom,$cnum)) {
                   8566:             $homeserver = &homeserver($cnum,$cdom);
                   8567:         } else {
                   8568:             $homeserver = &domain($cdom,'primary');
                   8569:         }
                   8570:         if ($homeserver ne 'no_host') {
                   8571:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8572:         }
1.876     raeburn  8573:     }
1.506     raeburn  8574:     return $response;
                   8575: }
1.776     albertel 8576: 
1.506     raeburn  8577: sub auto_get_sections {
1.508     raeburn  8578:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8579:     my $homeserver;
                   8580:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8581:         $homeserver = &homeserver($cnum,$cdom);
                   8582:     }
                   8583:     if (!defined($homeserver)) { 
                   8584:         if ($cdom =~ /^$match_domain$/) {
                   8585:             $homeserver = &domain($cdom,'primary');
                   8586:         }
                   8587:     }
                   8588:     my @secs;
                   8589:     if (defined($homeserver)) {
                   8590:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8591:         unless ($response eq 'refused') {
                   8592:             @secs = split(/:/,$response);
                   8593:         }
1.506     raeburn  8594:     }
                   8595:     return @secs;
                   8596: }
1.776     albertel 8597: 
1.506     raeburn  8598: sub auto_new_course {
1.1099    raeburn  8599:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8600:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8601:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8602:     return $response;
                   8603: }
1.776     albertel 8604: 
1.506     raeburn  8605: sub auto_validate_courseID {
1.508     raeburn  8606:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8607:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8608:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8609:     return $response;
                   8610: }
1.776     albertel 8611: 
1.1007    raeburn  8612: sub auto_validate_instcode {
1.1020    raeburn  8613:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8614:     my ($homeserver,$response);
                   8615:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8616:         $homeserver = &homeserver($cnum,$cdom);
                   8617:     }
                   8618:     if (!defined($homeserver)) {
                   8619:         if ($cdom =~ /^$match_domain$/) {
                   8620:             $homeserver = &domain($cdom,'primary');
                   8621:         }
                   8622:     }
1.1065    raeburn  8623:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8624:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8625:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8626:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8627: }
                   8628: 
1.506     raeburn  8629: sub auto_create_password {
1.873     raeburn  8630:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8631:     my ($homeserver,$response);
1.506     raeburn  8632:     my $create_passwd = 0;
                   8633:     my $authchk = '';
1.873     raeburn  8634:     if ($udom =~ /^$match_domain$/) {
                   8635:         $homeserver = &domain($udom,'primary');
                   8636:     }
                   8637:     if ($homeserver eq '') {
                   8638:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8639:             $homeserver = &homeserver($cnum,$cdom);
                   8640:         }
                   8641:     }
                   8642:     if ($homeserver eq '') {
                   8643:         $authchk = 'nodomain';
1.506     raeburn  8644:     } else {
1.873     raeburn  8645:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8646:         if ($response eq 'refused') {
                   8647:             $authchk = 'refused';
                   8648:         } else {
1.901     albertel 8649:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8650:         }
1.506     raeburn  8651:     }
                   8652:     return ($authparam,$create_passwd,$authchk);
                   8653: }
                   8654: 
1.706     raeburn  8655: sub auto_photo_permission {
                   8656:     my ($cnum,$cdom,$students) = @_;
                   8657:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8658:     my ($outcome,$perm_reqd,$conditions) = 
                   8659: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8660:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8661: 	return (undef,undef);
                   8662:     }
1.706     raeburn  8663:     return ($outcome,$perm_reqd,$conditions);
                   8664: }
                   8665: 
                   8666: sub auto_checkphotos {
                   8667:     my ($uname,$udom,$pid) = @_;
                   8668:     my $homeserver = &homeserver($uname,$udom);
                   8669:     my ($result,$resulttype);
                   8670:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8671: 				   &escape($uname).':'.&escape($pid),
                   8672: 				   $homeserver));
1.709     albertel 8673:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8674: 	return (undef,undef);
                   8675:     }
1.706     raeburn  8676:     if ($outcome) {
                   8677:         ($result,$resulttype) = split(/:/,$outcome);
                   8678:     } 
                   8679:     return ($result,$resulttype);
                   8680: }
                   8681: 
                   8682: sub auto_photochoice {
                   8683:     my ($cnum,$cdom) = @_;
                   8684:     my $homeserver = &homeserver($cnum,$cdom);
                   8685:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8686: 						       &escape($cdom),
                   8687: 						       $homeserver)));
1.709     albertel 8688:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8689: 	return (undef,undef);
                   8690:     }
1.706     raeburn  8691:     return ($update,$comment);
                   8692: }
                   8693: 
                   8694: sub auto_photoupdate {
                   8695:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8696:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8697:     my $host=&hostname($homeserver);
1.706     raeburn  8698:     my $cmd = '';
                   8699:     my $maxtries = 1;
1.800     albertel 8700:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8701:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8702:     }
                   8703:     $cmd =~ s/%%$//;
                   8704:     $cmd = &escape($cmd);
                   8705:     my $query = 'institutionalphotos';
                   8706:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8707:     unless ($queryid=~/^\Q$host\E\_/) {
                   8708:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8709:         return 'error: '.$queryid;
                   8710:     }
                   8711:     my $reply = &get_query_reply($queryid);
                   8712:     my $tries = 1;
                   8713:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8714:         $reply = &get_query_reply($queryid);
                   8715:         $tries ++;
                   8716:     }
                   8717:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8718:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8719:     } else {
                   8720:         my @responses = split(/:/,$reply);
                   8721:         my $outcome = shift(@responses); 
                   8722:         foreach my $item (@responses) {
                   8723:             my ($key,$value) = split(/=/,$item);
                   8724:             $$photo{$key} = $value;
                   8725:         }
                   8726:         return $outcome;
                   8727:     }
                   8728:     return 'error';
                   8729: }
                   8730: 
1.521     raeburn  8731: sub auto_instcode_format {
1.793     albertel 8732:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8733: 	$cat_order) = @_;
1.521     raeburn  8734:     my $courses = '';
1.772     raeburn  8735:     my @homeservers;
1.521     raeburn  8736:     if ($caller eq 'global') {
1.841     albertel 8737: 	my %servers = &get_servers($codedom,'library');
                   8738: 	foreach my $tryserver (keys(%servers)) {
                   8739: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8740: 		push(@homeservers,$tryserver);
                   8741: 	    }
1.584     raeburn  8742:         }
1.1022    raeburn  8743:     } elsif ($caller eq 'requests') {
                   8744:         if ($codedom =~ /^$match_domain$/) {
                   8745:             my $chome = &domain($codedom,'primary');
                   8746:             unless ($chome eq 'no_host') {
                   8747:                 push(@homeservers,$chome);
                   8748:             }
                   8749:         }
1.521     raeburn  8750:     } else {
1.772     raeburn  8751:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8752:     }
1.793     albertel 8753:     foreach my $code (keys(%{$instcodes})) {
                   8754:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8755:     }
                   8756:     chop($courses);
1.772     raeburn  8757:     my $ok_response = 0;
                   8758:     my $response;
                   8759:     while (@homeservers > 0 && $ok_response == 0) {
                   8760:         my $server = shift(@homeservers); 
                   8761:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8762:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8763:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8764: 		split(/:/,$response);
1.772     raeburn  8765:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8766:             push(@{$codetitles},&str2array($codetitles_str));
                   8767:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8768:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8769:             $ok_response = 1;
                   8770:         }
                   8771:     }
                   8772:     if ($ok_response) {
1.521     raeburn  8773:         return 'ok';
1.772     raeburn  8774:     } else {
                   8775:         return $response;
1.521     raeburn  8776:     }
                   8777: }
                   8778: 
1.792     raeburn  8779: sub auto_instcode_defaults {
                   8780:     my ($domain,$returnhash,$code_order) = @_;
                   8781:     my @homeservers;
1.841     albertel 8782: 
                   8783:     my %servers = &get_servers($domain,'library');
                   8784:     foreach my $tryserver (keys(%servers)) {
                   8785: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8786: 	    push(@homeservers,$tryserver);
                   8787: 	}
1.792     raeburn  8788:     }
1.841     albertel 8789: 
1.792     raeburn  8790:     my $response;
1.841     albertel 8791:     foreach my $server (@homeservers) {
1.792     raeburn  8792:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8793:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8794: 	
                   8795: 	foreach my $pair (split(/\&/,$response)) {
                   8796: 	    my ($name,$value)=split(/\=/,$pair);
                   8797: 	    if ($name eq 'code_order') {
                   8798: 		@{$code_order} = split(/\&/,&unescape($value));
                   8799: 	    } else {
                   8800: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8801: 	    }
                   8802: 	}
                   8803: 	return 'ok';
1.792     raeburn  8804:     }
1.841     albertel 8805: 
                   8806:     return $response;
1.1003    raeburn  8807: }
                   8808: 
                   8809: sub auto_possible_instcodes {
1.1007    raeburn  8810:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8811:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8812:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8813:         return;
                   8814:     }
1.1003    raeburn  8815:     my (@homeservers,$uhome);
                   8816:     if (defined(&domain($domain,'primary'))) {
                   8817:         $uhome=&domain($domain,'primary');
                   8818:         push(@homeservers,&domain($domain,'primary'));
                   8819:     } else {
                   8820:         my %servers = &get_servers($domain,'library');
                   8821:         foreach my $tryserver (keys(%servers)) {
                   8822:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8823:                 push(@homeservers,$tryserver);
                   8824:             }
                   8825:         }
                   8826:     }
                   8827:     my $response;
                   8828:     foreach my $server (@homeservers) {
                   8829:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8830:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8831:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8832:             split(':',$response);
                   8833:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8834:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8835:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8836:             my ($name,$value)=split('=',$item);
                   8837:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8838:         }
                   8839:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8840:             my ($name,$value)=split('=',$item);
                   8841:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8842:         }
                   8843:         return 'ok';
                   8844:     }
                   8845:     return $response;
                   8846: }
1.792     raeburn  8847: 
1.1010    raeburn  8848: sub auto_courserequest_checks {
                   8849:     my ($dom) = @_;
1.1020    raeburn  8850:     my ($homeserver,%validations);
                   8851:     if ($dom =~ /^$match_domain$/) {
                   8852:         $homeserver = &domain($dom,'primary');
                   8853:     }
                   8854:     unless ($homeserver eq 'no_host') {
                   8855:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8856:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8857:             my @items = split(/&/,$response);
                   8858:             foreach my $item (@items) {
                   8859:                 my ($key,$value) = split('=',$item);
                   8860:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8861:             }
                   8862:         }
                   8863:     }
1.1010    raeburn  8864:     return %validations; 
                   8865: }
                   8866: 
1.1020    raeburn  8867: sub auto_courserequest_validation {
1.1255    raeburn  8868:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8869:     my ($homeserver,$response);
                   8870:     if ($dom =~ /^$match_domain$/) {
                   8871:         $homeserver = &domain($dom,'primary');
                   8872:     }
1.1255    raeburn  8873:     unless ($homeserver eq 'no_host') {
                   8874:         my $customdata;
                   8875:         if (ref($custominfo) eq 'HASH') {
                   8876:             $customdata = &freeze_escape($custominfo);
                   8877:         }
1.1020    raeburn  8878:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8879:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8880:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8881:                                     $customdata,$homeserver));
1.1020    raeburn  8882:     }
                   8883:     return $response;
                   8884: }
                   8885: 
1.777     albertel 8886: sub auto_validate_class_sec {
1.918     raeburn  8887:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8888:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8889:     my $ownerlist;
                   8890:     if (ref($owners) eq 'ARRAY') {
                   8891:         $ownerlist = join(',',@{$owners});
                   8892:     } else {
                   8893:         $ownerlist = $owners;
                   8894:     }
1.773     raeburn  8895:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8896:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8897:     return $response;
                   8898: }
                   8899: 
1.1367    raeburn  8900: sub auto_validate_instclasses {
                   8901:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8902:     my ($homeserver,%validations);
                   8903:     $homeserver = &homeserver($cnum,$cdom);
                   8904:     unless ($homeserver eq 'no_host') {
                   8905:         my $ownerlist;
                   8906:         if (ref($owners) eq 'ARRAY') {
                   8907:             $ownerlist = join(',',@{$owners});
                   8908:         } else {
                   8909:             $ownerlist = $owners;
                   8910:         }
                   8911:         if (ref($classesref) eq 'HASH') {
                   8912:             my $classes = &freeze_escape($classesref);
                   8913:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8914:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8915:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8916:                 my @items = split(/&/,$response);
                   8917:                 foreach my $item (@items) {
                   8918:                     my ($key,$value) = split('=',$item);
                   8919:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8920:                 }
                   8921:             }
                   8922:         }
                   8923:     }
                   8924:     return %validations;
                   8925: }
                   8926: 
1.1248    raeburn  8927: sub auto_crsreq_update {
                   8928:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8929:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8930:     my ($homeserver,%crsreqresponse);
                   8931:     if ($cdom =~ /^$match_domain$/) {
                   8932:         $homeserver = &domain($cdom,'primary');
                   8933:     }
                   8934:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8935:         my $info;
                   8936:         if (ref($inbound) eq 'HASH') {
                   8937:             $info = &freeze_escape($inbound);
                   8938:         }
                   8939:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8940:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8941:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8942:                             &escape($title).':'.&escape($code).':'.
                   8943:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8944:                             $homeserver);
1.1248    raeburn  8945:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8946:             my @items = split(/&/,$response);
                   8947:             foreach my $item (@items) {
                   8948:                 my ($key,$value) = split('=',$item);
                   8949:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8950:             }
                   8951:         }
                   8952:     }
                   8953:     return \%crsreqresponse;
                   8954: }
                   8955: 
1.1305    raeburn  8956: sub auto_export_grades {
1.1309    raeburn  8957:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8958:     my ($homeserver,%exportresponse);
                   8959:     if ($cdom =~ /^$match_domain$/) {
                   8960:         $homeserver = &domain($cdom,'primary');
                   8961:     }
                   8962:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8963:         my $info;
                   8964:         if (ref($inforef) eq 'HASH') {
                   8965:             $info = &freeze_escape($inforef);
                   8966:         }
                   8967:         if (ref($gradesref) eq 'HASH') {
                   8968:             my $grades = &freeze_escape($gradesref);
                   8969:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8970:                                 $info.':'.$grades,$homeserver);
                   8971:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8972:                 my @items = split(/&/,$response);
                   8973:                 foreach my $item (@items) {
                   8974:                     my ($key,$value) = split('=',$item);
                   8975:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8976:                 }
                   8977:             }
                   8978:         }
                   8979:     }
                   8980:     return \%exportresponse;
1.1305    raeburn  8981: }
                   8982: 
1.1287    raeburn  8983: sub check_instcode_cloning {
                   8984:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8985:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8986:         return;
                   8987:     }
                   8988:     my $canclone;
                   8989:     if (@{$code_order} > 0) {
                   8990:         my $instcoderegexp ='^';
                   8991:         my @clonecodes = split(/\&/,$cloner);
                   8992:         foreach my $item (@{$code_order}) {
                   8993:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8994:                 foreach my $pair (@clonecodes) {
                   8995:                     my ($key,$val) = split(/\=/,$pair,2);
                   8996:                     $val = &unescape($val);
                   8997:                     if ($key eq $item) {
                   8998:                         $instcoderegexp .= '('.$val.')';
                   8999:                         last;
                   9000:                     }
                   9001:                 }
                   9002:             } else {
                   9003:                 $instcoderegexp .= $codedefaults->{$item};
                   9004:             }
                   9005:         }
                   9006:         $instcoderegexp .= '$';
                   9007:         my (@from,@to);
                   9008:         eval {
                   9009:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9010:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9011:         };
                   9012:         if ((@from > 0) && (@to > 0)) {
                   9013:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9014:             if (!@diffs) {
                   9015:                 $canclone = 1;
                   9016:             }
                   9017:         }
                   9018:     }
                   9019:     return $canclone;
                   9020: }
                   9021: 
                   9022: sub default_instcode_cloning {
                   9023:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9024:     my (%codedefaults,@code_order,$canclone);
                   9025:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9026:         %codedefaults = %{$codedefaultsref};
                   9027:         @code_order = @{$codeorderref};
                   9028:     } elsif ($clonedom) {
                   9029:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9030:     }
                   9031:     if (($domdefclone) && (@code_order)) {
                   9032:         my @clonecodes = split(/\+/,$domdefclone);
                   9033:         my $instcoderegexp ='^';
                   9034:         foreach my $item (@code_order) {
                   9035:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9036:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9037:             } else {
                   9038:                 $instcoderegexp .= $codedefaults{$item};
                   9039:             }
                   9040:         }
                   9041:         $instcoderegexp .= '$';
                   9042:         my (@from,@to);
                   9043:         eval {
                   9044:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9045:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9046:         };
                   9047:         if ((@from > 0) && (@to > 0)) {
                   9048:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9049:             if (!@diffs) {
                   9050:                 $canclone = 1;
                   9051:             }
                   9052:         }
                   9053:     }
                   9054:     return $canclone;
                   9055: }
                   9056: 
1.679     raeburn  9057: # ------------------------------------------------------- Course Group routines
                   9058: 
                   9059: sub get_coursegroups {
1.809     raeburn  9060:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9061:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9062: }
                   9063: 
1.679     raeburn  9064: sub modify_coursegroup {
                   9065:     my ($cdom,$cnum,$groupsettings) = @_;
                   9066:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9067: }
                   9068: 
1.809     raeburn  9069: sub toggle_coursegroup_status {
                   9070:     my ($cdom,$cnum,$group,$action) = @_;
                   9071:     my ($from_namespace,$to_namespace);
                   9072:     if ($action eq 'delete') {
                   9073:         $from_namespace = 'coursegroups';
                   9074:         $to_namespace = 'deleted_groups';
                   9075:     } else {
                   9076:         $from_namespace = 'deleted_groups';
                   9077:         $to_namespace = 'coursegroups';
                   9078:     }
                   9079:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9080:     if (my $tmp = &error(%curr_group)) {
                   9081:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9082:         return ('read error',$tmp);
                   9083:     } else {
                   9084:         my %savedsettings = %curr_group; 
1.809     raeburn  9085:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9086:         my $deloutcome;
                   9087:         if ($result eq 'ok') {
1.809     raeburn  9088:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9089:         } else {
                   9090:             return ('write error',$result);
                   9091:         }
                   9092:         if ($deloutcome eq 'ok') {
                   9093:             return 'ok';
                   9094:         } else {
                   9095:             return ('delete error',$deloutcome);
                   9096:         }
                   9097:     }
                   9098: }
                   9099: 
1.679     raeburn  9100: sub modify_group_roles {
1.957     raeburn  9101:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9102:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9103:     my $role = 'gr/'.&escape($userprivs);
                   9104:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9105:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9106:     if ($result eq 'ok') {
                   9107:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9108:     }
1.679     raeburn  9109:     return $result;
                   9110: }
                   9111: 
                   9112: sub modify_coursegroup_membership {
                   9113:     my ($cdom,$cnum,$membership) = @_;
                   9114:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9115:     return $result;
                   9116: }
                   9117: 
1.682     raeburn  9118: sub get_active_groups {
                   9119:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9120:     my $now = time;
                   9121:     my %groups = ();
                   9122:     foreach my $key (keys(%env)) {
1.811     albertel 9123:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9124:             my ($start,$end) = split(/\./,$env{$key});
                   9125:             if (($end!=0) && ($end<$now)) { next; }
                   9126:             if (($start!=0) && ($start>$now)) { next; }
                   9127:             if ($1 eq $cdom && $2 eq $cnum) {
                   9128:                 $groups{$3} = $env{$key} ;
                   9129:             }
                   9130:         }
                   9131:     }
                   9132:     return %groups;
                   9133: }
                   9134: 
1.683     raeburn  9135: sub get_group_membership {
                   9136:     my ($cdom,$cnum,$group) = @_;
                   9137:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9138: }
                   9139: 
                   9140: sub get_users_groups {
                   9141:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9142:     my @usersgroups;
1.683     raeburn  9143:     my $cachetime=1800;
                   9144: 
                   9145:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9146:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9147:     if (defined($cached)) {
1.734     albertel 9148:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9149:     } else {  
                   9150:         $grouplist = '';
1.816     raeburn  9151:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9152:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9153:         my $access_end = $env{'course.'.$courseid.
                   9154:                               '.default_enrollment_end_date'};
                   9155:         my $now = time;
                   9156:         foreach my $key (keys(%roleshash)) {
                   9157:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9158:                 my $group = $1;
                   9159:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9160:                     my $start = $2;
                   9161:                     my $end = $1;
                   9162:                     if ($start == -1) { next; } # deleted from group
                   9163:                     if (($start!=0) && ($start>$now)) { next; }
                   9164:                     if (($end!=0) && ($end<$now)) {
                   9165:                         if ($access_end && $access_end < $now) {
                   9166:                             if ($access_end - $end < 86400) {
                   9167:                                 push(@usersgroups,$group);
1.733     raeburn  9168:                             }
                   9169:                         }
1.817     raeburn  9170:                         next;
1.733     raeburn  9171:                     }
1.817     raeburn  9172:                     push(@usersgroups,$group);
1.683     raeburn  9173:                 }
                   9174:             }
                   9175:         }
1.817     raeburn  9176:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9177:         $grouplist = join(':',@usersgroups);
                   9178:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9179:     }
1.733     raeburn  9180:     return @usersgroups;
1.683     raeburn  9181: }
                   9182: 
                   9183: sub devalidate_getgroups_cache {
                   9184:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9185:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9186: 
1.683     raeburn  9187:     my $hashid="$udom:$uname:$courseid";
                   9188:     &devalidate_cache_new('getgroups',$hashid);
                   9189: }
                   9190: 
1.12      www      9191: # ------------------------------------------------------------------ Plain Text
                   9192: 
                   9193: sub plaintext {
1.988     raeburn  9194:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9195:     if ($short =~ m{^cr/}) {
1.758     albertel 9196: 	return (split('/',$short))[-1];
                   9197:     }
1.742     raeburn  9198:     if (!defined($cid)) {
                   9199:         $cid = $env{'request.course.id'};
                   9200:     }
                   9201:     my %rolenames = (
1.1008    raeburn  9202:                       Course    => 'std',
                   9203:                       Community => 'alt1',
1.1305    raeburn  9204:                       Placement => 'std',
1.742     raeburn  9205:                     );
1.1037    raeburn  9206:     if ($cid ne '') {
                   9207:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9208:             unless ($forcedefault) {
                   9209:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9210:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9211:                 return &Apache::lonlocal::mt($roletext);
                   9212:             }
                   9213:         }
                   9214:     }
                   9215:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9216:         (defined($rolenames{$type})) && 
                   9217:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9218:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9219:     } elsif ($cid ne '') {
                   9220:         my $crstype = $env{'course.'.$cid.'.type'};
                   9221:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9222:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9223:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9224:         }
1.742     raeburn  9225:     }
1.1037    raeburn  9226:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9227: }
                   9228: 
                   9229: # ----------------------------------------------------------------- Assign Role
                   9230: 
                   9231: sub assignrole {
1.957     raeburn  9232:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9233:         $context)=@_;
1.21      www      9234:     my $mrole;
                   9235:     if ($role =~ /^cr\//) {
1.393     www      9236:         my $cwosec=$url;
1.811     albertel 9237:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9238: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9239:            my $refused = 1;
                   9240:            if ($context eq 'requestcourses') {
                   9241:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9242:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9243:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9244:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9245:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9246:                            if ($crsenv{'internal.courseowner'} eq
                   9247:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9248:                                $refused = '';
                   9249:                            }
                   9250:                        }
                   9251:                    }
                   9252:                }
                   9253:            }
                   9254:            if ($refused) {
                   9255:                &logthis('Refused custom assignrole: '.
                   9256:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9257:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9258:                return 'refused';
                   9259:            }
1.104     www      9260:         }
1.21      www      9261:         $mrole='cr';
1.678     raeburn  9262:     } elsif ($role =~ /^gr\//) {
                   9263:         my $cwogrp=$url;
1.811     albertel 9264:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9265:         unless (&allowed('mdg',$cwogrp)) {
                   9266:             &logthis('Refused group assignrole: '.
                   9267:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9268:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9269:             return 'refused';
                   9270:         }
                   9271:         $mrole='gr';
1.21      www      9272:     } else {
1.82      www      9273:         my $cwosec=$url;
1.811     albertel 9274:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9275:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9276:             my $refused;
                   9277:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9278:                 if (!(&allowed('c'.$role,$url))) {
                   9279:                     $refused = 1;
                   9280:                 }
                   9281:             } else {
                   9282:                 $refused = 1;
                   9283:             }
1.947     raeburn  9284:             if ($refused) {
1.1045    raeburn  9285:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9286:                 if (!$selfenroll && $context eq 'course') {
                   9287:                     my %crsenv;
                   9288:                     if ($role eq 'cc' || $role eq 'co') {
                   9289:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9290:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9291:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9292:                                 if ($crsenv{'internal.courseowner'} eq 
                   9293:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9294:                                     $refused = '';
                   9295:                                 }
                   9296:                             }
                   9297:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9298:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9299:                                 if ($crsenv{'internal.courseowner'} eq 
                   9300:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9301:                                     $refused = '';
                   9302:                                 }
                   9303:                             }
                   9304:                         }
                   9305:                     }
1.1368    raeburn  9306:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9307:                     if ($role eq 'st') {
                   9308:                         $refused = '';
                   9309:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti'})) {
                   9310:                         $refused = '';
                   9311:                     }
1.1017    raeburn  9312:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9313:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9314:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9315:                         my $wrongcc;
                   9316:                         if ($cnum =~ /^$match_community$/) {
                   9317:                             $wrongcc = 1 if ($role eq 'cc');
                   9318:                         } else {
                   9319:                             $wrongcc = 1 if ($role eq 'co');
                   9320:                         }
                   9321:                         unless ($wrongcc) {
                   9322:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9323:                             if ($crsenv{'internal.courseowner'} eq 
                   9324:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9325:                                 $refused = '';
                   9326:                             }
1.1017    raeburn  9327:                         }
                   9328:                     }
1.1183    raeburn  9329:                 } elsif ($context eq 'requestauthor') {
                   9330:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9331:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9332:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9333:                             $refused = '';
                   9334:                         } else {
                   9335:                             my %domdefaults = &get_domain_defaults($udom);
                   9336:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9337:                                 my $checkbystatus;
                   9338:                                 if ($env{'user.adv'}) { 
                   9339:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9340:                                     if ($disposition eq 'automatic') {
                   9341:                                         $refused = '';
                   9342:                                     } elsif ($disposition eq '') {
                   9343:                                         $checkbystatus = 1;
                   9344:                                     } 
                   9345:                                 } else {
                   9346:                                     $checkbystatus = 1;
                   9347:                                 }
                   9348:                                 if ($checkbystatus) {
                   9349:                                     if ($env{'environment.inststatus'}) {
                   9350:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9351:                                         foreach my $type (@inststatuses) {
                   9352:                                             if (($type ne '') &&
                   9353:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9354:                                                 $refused = '';
                   9355:                                             }
                   9356:                                         }
                   9357:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9358:                                         $refused = '';
                   9359:                                     }
                   9360:                                 }
                   9361:                             }
                   9362:                         }
                   9363:                     }
1.1017    raeburn  9364:                 }
                   9365:                 if ($refused) {
1.947     raeburn  9366:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9367:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9368: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9369:                     return 'refused';
                   9370:                 }
1.932     raeburn  9371:             }
1.1131    raeburn  9372:         } elsif ($role eq 'au') {
                   9373:             if ($url ne '/'.$udom.'/') {
                   9374:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9375:                          ' to assign author role for '.$uname.':'.$udom.
                   9376:                          ' in domain: '.$url.' refused (wrong domain).');
                   9377:                 return 'refused';
                   9378:             }
1.104     www      9379:         }
1.21      www      9380:         $mrole=$role;
                   9381:     }
1.620     albertel 9382:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9383:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9384:     if ($end) { $command.='_'.$end; }
1.21      www      9385:     if ($start) {
                   9386: 	if ($end) { 
1.81      www      9387:            $command.='_'.$start; 
1.21      www      9388:         } else {
1.81      www      9389:            $command.='_0_'.$start;
1.21      www      9390:         }
                   9391:     }
1.739     raeburn  9392:     my $origstart = $start;
                   9393:     my $origend = $end;
1.957     raeburn  9394:     my $delflag;
1.357     www      9395: # actually delete
                   9396:     if ($deleteflag) {
1.373     www      9397: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9398: # modify command to delete the role
1.620     albertel 9399:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9400:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9401: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9402: # set start and finish to negative values for userrolelog
                   9403:            $start=-1;
                   9404:            $end=-1;
1.957     raeburn  9405:            $delflag = 1;
1.357     www      9406:         }
                   9407:     }
                   9408: # send command
1.349     www      9409:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9410: # log new user role if status is ok
1.349     www      9411:     if ($answer eq 'ok') {
1.663     raeburn  9412: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9413:         if (($role eq 'cc') || ($role eq 'in') ||
                   9414:             ($role eq 'ep') || ($role eq 'ad') ||
                   9415:             ($role eq 'ta') || ($role eq 'st') ||
                   9416:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9417:             ($role eq 'co')) {
1.1200    raeburn  9418: # for course roles, perform group memberships changes triggered by role change.
                   9419:             unless ($role =~ /^gr/) {
                   9420:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9421:                                                  $origstart,$selfenroll,$context);
                   9422:             }
1.1184    raeburn  9423:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9424:                            $selfenroll,$context);
                   9425:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9426:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9427:                  ($role eq 'da')) {
1.1184    raeburn  9428:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9429:                            $context);
                   9430:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9431:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9432:                              $context); 
                   9433:         }
1.1053    raeburn  9434:         if ($role eq 'cc') {
                   9435:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9436:         }
1.349     www      9437:     }
                   9438:     return $answer;
1.169     harris41 9439: }
                   9440: 
1.1053    raeburn  9441: sub autoupdate_coowners {
                   9442:     my ($url,$end,$start,$uname,$udom) = @_;
                   9443:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9444:     if (($cdom ne '') && ($cnum ne '')) {
                   9445:         my $now = time;
                   9446:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9447:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9448:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9449:             my $instcode = $coursehash{'internal.coursecode'};
                   9450:             if ($instcode ne '') {
1.1056    raeburn  9451:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9452:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9453:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9454:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9455:                         if ($result eq 'valid') {
                   9456:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9457:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9458:                                     push(@newcoowners,$coowner);
                   9459:                                 }
                   9460:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9461:                                     push(@newcoowners,$uname.':'.$udom);
                   9462:                                 }
                   9463:                                 @newcoowners = sort(@newcoowners);
                   9464:                             } else {
                   9465:                                 push(@newcoowners,$uname.':'.$udom);
                   9466:                             }
                   9467:                         } else {
                   9468:                             if ($coursehash{'internal.co-owners'}) {
                   9469:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9470:                                     unless ($coowner eq $uname.':'.$udom) {
                   9471:                                         push(@newcoowners,$coowner);
                   9472:                                     }
                   9473:                                 }
                   9474:                                 unless (@newcoowners > 0) {
                   9475:                                     $delcoowners = 1;
                   9476:                                     $coowners = '';
                   9477:                                 }
                   9478:                             }
                   9479:                         }
                   9480:                         if (@newcoowners || $delcoowners) {
                   9481:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9482:                                             $delcoowners,@newcoowners);
                   9483:                         }
                   9484:                     }
                   9485:                 }
                   9486:             }
                   9487:         }
                   9488:     }
                   9489: }
                   9490: 
                   9491: sub store_coowners {
                   9492:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9493:     my $cid = $cdom.'_'.$cnum;
                   9494:     my ($coowners,$delresult,$putresult);
                   9495:     if (@newcoowners) {
                   9496:         $coowners = join(',',@newcoowners);
                   9497:         my %coownershash = (
                   9498:                             'internal.co-owners' => $coowners,
                   9499:                            );
                   9500:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9501:         if ($putresult eq 'ok') {
                   9502:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9503:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9504:             }
                   9505:         }
                   9506:     }
                   9507:     if ($delcoowners) {
                   9508:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9509:         if ($delresult eq 'ok') {
                   9510:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9511:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9512:             }
                   9513:         }
                   9514:     }
                   9515:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9516:         my %crsinfo =
                   9517:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9518:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9519:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9520:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9521:         }
                   9522:     }
                   9523: }
                   9524: 
1.169     harris41 9525: # -------------------------------------------------- Modify user authentication
1.197     www      9526: # Overrides without validation
                   9527: 
1.169     harris41 9528: sub modifyuserauth {
                   9529:     my ($udom,$uname,$umode,$upass)=@_;
                   9530:     my $uhome=&homeserver($uname,$udom);
1.197     www      9531:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9532:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9533:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9534:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9535:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9536: 		     &escape($upass),$uhome);
1.620     albertel 9537:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9538:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9539:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9540:     &log($udom,,$uname,$uhome,
1.620     albertel 9541:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9542:                                      $env{'user.name'}.', '.$umode.
1.197     www      9543:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9544:     unless ($reply eq 'ok') {
1.197     www      9545:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9546: 	return 'error: '.$reply;
                   9547:     }   
1.170     harris41 9548:     return 'ok';
1.80      www      9549: }
                   9550: 
1.81      www      9551: # --------------------------------------------------------------- Modify a user
1.80      www      9552: 
1.81      www      9553: sub modifyuser {
1.206     matthew  9554:     my ($udom,    $uname, $uid,
                   9555:         $umode,   $upass, $first,
                   9556:         $middle,  $last,  $gene,
1.1058    raeburn  9557:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9558:     $udom= &LONCAPA::clean_domain($udom);
                   9559:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9560:     my $showcandelete = 'none';
                   9561:     if (ref($candelete) eq 'ARRAY') {
                   9562:         if (@{$candelete} > 0) {
                   9563:             $showcandelete = join(', ',@{$candelete});
                   9564:         }
                   9565:     }
1.81      www      9566:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9567:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9568: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9569:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9570:                                      ' desiredhome not specified'). 
1.620     albertel 9571:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9572:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9573:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9574:     my $newuser;
                   9575:     if ($uhome eq 'no_host') {
                   9576:         $newuser = 1;
1.1368    raeburn  9577:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9578:                 ($umode eq 'lti')) {
                   9579:             return 'error: more information needed to create new user';
                   9580:         }
1.1075    raeburn  9581:     }
1.80      www      9582: # ----------------------------------------------------------------- Create User
1.406     albertel 9583:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9584: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9585:         my $unhome='';
1.844     albertel 9586:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9587:             $unhome = $desiredhome;
1.620     albertel 9588: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9589: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9590:         } else { # load balancing routine for determining $unhome
1.81      www      9591:             my $loadm=10000000;
1.841     albertel 9592: 	    my %servers = &get_servers($udom,'library');
                   9593: 	    foreach my $tryserver (keys(%servers)) {
                   9594: 		my $answer=reply('load',$tryserver);
                   9595: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9596: 		    $loadm=$answer;
                   9597: 		    $unhome=$tryserver;
                   9598: 		}
1.80      www      9599: 	    }
                   9600:         }
                   9601:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9602: 	    return 'error: unable to find a home server for '.$uname.
                   9603:                    ' in domain '.$udom;
1.80      www      9604:         }
                   9605:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9606:                          &escape($upass),$unhome);
                   9607: 	unless ($reply eq 'ok') {
                   9608:             return 'error: '.$reply;
                   9609:         }   
1.230     stredwic 9610:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9611:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9612: 	    return 'error: unable verify users home machine.';
1.80      www      9613:         }
1.209     matthew  9614:     }   # End of creation of new user
1.80      www      9615: # ---------------------------------------------------------------------- Add ID
                   9616:     if ($uid) {
                   9617:        $uid=~tr/A-Z/a-z/;
                   9618:        my %uidhash=&idrget($udom,$uname);
1.196     www      9619:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9620:          && (!$forceid)) {
1.80      www      9621: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9622: 	      return 'error: user id "'.$uid.'" does not match '.
                   9623:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9624:           }
                   9625:        } else {
1.1300    raeburn  9626: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9627:        }
                   9628:     }
                   9629: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9630:     my @tmp=&get('environment',
1.899     raeburn  9631: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9632:                     'permanentemail','inststatus'],
1.134     albertel 9633: 		   $udom,$uname);
1.1075    raeburn  9634:     my (%names,%oldnames);
1.313     matthew  9635:     if ($tmp[0] =~ m/^error:.*/) { 
                   9636:         %names=(); 
                   9637:     } else {
                   9638:         %names = @tmp;
1.1075    raeburn  9639:         %oldnames = %names;
1.313     matthew  9640:     }
1.388     www      9641: #
1.1058    raeburn  9642: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9643: # of users did not contain them), do not overwrite existing values
                   9644: # unless field is in $candelete array ref.  
                   9645: #
                   9646: 
                   9647:     my @fields = ('firstname','middlename','lastname','generation',
                   9648:                   'permanentemail','id');
                   9649:     my %newvalues;
                   9650:     if (ref($candelete) eq 'ARRAY') {
                   9651:         foreach my $field (@fields) {
                   9652:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9653:                 if ($field eq 'firstname') {
                   9654:                     $names{$field} = $first;
                   9655:                 } elsif ($field eq 'middlename') {
                   9656:                     $names{$field} = $middle;
                   9657:                 } elsif ($field eq 'lastname') {
                   9658:                     $names{$field} = $last;
                   9659:                 } elsif ($field eq 'generation') { 
                   9660:                     $names{$field} = $gene;
                   9661:                 } elsif ($field eq 'permanentemail') {
                   9662:                     $names{$field} = $email;
                   9663:                 } elsif ($field eq 'id') {
                   9664:                     $names{$field}  = $uid;
                   9665:                 }
                   9666:             }
                   9667:         }
                   9668:     }
1.388     www      9669:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9670:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9671:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9672:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9673:     if ($email) {
                   9674:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9675:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9676:     }
1.899     raeburn  9677:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9678:     if (defined($inststatus)) {
                   9679:         $names{'inststatus'} = '';
                   9680:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9681:         if (ref($usertypes) eq 'HASH') {
                   9682:             my @okstatuses; 
                   9683:             foreach my $item (split(/:/,$inststatus)) {
                   9684:                 if (defined($usertypes->{$item})) {
                   9685:                     push(@okstatuses,$item);  
                   9686:                 }
                   9687:             }
                   9688:             if (@okstatuses) {
                   9689:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9690:             }
                   9691:         }
                   9692:     }
1.1075    raeburn  9693:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9694:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9695:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9696:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9697:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9698:     } else {
                   9699:         $logmsg .= ' during self creation';
                   9700:     }
1.1075    raeburn  9701:     my $changed;
                   9702:     if ($newuser) {
                   9703:         $changed = 1;
                   9704:     } else {
                   9705:         foreach my $field (@fields) {
                   9706:             if ($names{$field} ne $oldnames{$field}) {
                   9707:                 $changed = 1;
                   9708:                 last;
                   9709:             }
                   9710:         }
                   9711:     }
                   9712:     unless ($changed) {
                   9713:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9714:         &logthis($logmsg);
                   9715:         return 'ok';
                   9716:     }
                   9717:     my $reply = &put('environment', \%names, $udom,$uname);
                   9718:     if ($reply ne 'ok') { 
                   9719:         return 'error: '.$reply;
                   9720:     }
1.1087    raeburn  9721:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9722:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9723:     }
1.1075    raeburn  9724:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9725:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9726:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9727:     &logthis($logmsg);
1.134     albertel 9728:     return 'ok';
1.80      www      9729: }
                   9730: 
1.81      www      9731: # -------------------------------------------------------------- Modify student
1.80      www      9732: 
1.81      www      9733: sub modifystudent {
                   9734:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9735:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9736:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9737:     if (!$cid) {
1.620     albertel 9738: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9739: 	    return 'not_in_class';
                   9740: 	}
1.80      www      9741:     }
                   9742: # --------------------------------------------------------------- Make the user
1.81      www      9743:     my $reply=&modifyuser
1.209     matthew  9744: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9745:          $desiredhome,$email,$inststatus);
1.80      www      9746:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9747:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9748:     # student's environment
1.297     matthew  9749:     $uid = undef if (!$forceid);
1.455     albertel 9750:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9751:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9752:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9753:     return $reply;
                   9754: }
                   9755: 
                   9756: sub modify_student_enrollment {
1.1216    raeburn  9757:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9758:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9759:     my ($cdom,$cnum,$chome);
                   9760:     if (!$cid) {
1.620     albertel 9761: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9762: 	    return 'not_in_class';
                   9763: 	}
1.620     albertel 9764: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9765: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9766:     } else {
                   9767: 	($cdom,$cnum)=split(/_/,$cid);
                   9768:     }
1.620     albertel 9769:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9770:     if (!$chome) {
1.457     raeburn  9771: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9772:     }
1.455     albertel 9773:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9774:     # Make sure the user exists
1.81      www      9775:     my $uhome=&homeserver($uname,$udom);
                   9776:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9777: 	return 'error: no such user';
                   9778:     }
1.297     matthew  9779:     # Get student data if we were not given enough information
                   9780:     if (!defined($first)  || $first  eq '' || 
                   9781:         !defined($last)   || $last   eq '' || 
                   9782:         !defined($uid)    || $uid    eq '' || 
                   9783:         !defined($middle) || $middle eq '' || 
                   9784:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9785:         # They did not supply us with enough data to enroll the student, so
                   9786:         # we need to pick up more information.
1.297     matthew  9787:         my %tmp = &get('environment',
1.294     matthew  9788:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9789:                        ,$udom,$uname);
                   9790: 
1.800     albertel 9791:         #foreach my $key (keys(%tmp)) {
                   9792:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9793:         #}
1.294     matthew  9794:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9795:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9796:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9797:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9798:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9799:     }
1.556     albertel 9800:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9801:     my $user = "$uname:$udom";
                   9802:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9803:     my $reply=cput('classlist',
1.1148    raeburn  9804: 		   {$user => 
1.1314    raeburn  9805: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9806: 		   $cdom,$cnum);
1.1148    raeburn  9807:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9808:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9809:     } else { 
1.81      www      9810: 	return 'error: '.$reply;
                   9811:     }
1.297     matthew  9812:     # Add student role to user
1.83      www      9813:     my $uurl='/'.$cid;
1.81      www      9814:     $uurl=~s/\_/\//g;
                   9815:     if ($usec) {
                   9816: 	$uurl.='/'.$usec;
                   9817:     }
1.1148    raeburn  9818:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9819:                              $selfenroll,$context);
                   9820:     if ($result ne 'ok') {
                   9821:         if ($old_entry{$user} ne '') {
                   9822:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9823:         } else {
                   9824:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9825:         }
                   9826:     }
                   9827:     return $result; 
1.21      www      9828: }
                   9829: 
1.556     albertel 9830: sub format_name {
                   9831:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9832:     my $name;
                   9833:     if ($first ne 'lastname') {
                   9834: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9835:     } else {
                   9836: 	if ($lastname=~/\S/) {
                   9837: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9838: 	    $name=~s/\s+,/,/;
                   9839: 	} else {
                   9840: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9841: 	}
                   9842:     }
                   9843:     $name=~s/^\s+//;
                   9844:     $name=~s/\s+$//;
                   9845:     $name=~s/\s+/ /g;
                   9846:     return $name;
                   9847: }
                   9848: 
1.84      www      9849: # ------------------------------------------------- Write to course preferences
                   9850: 
                   9851: sub writecoursepref {
                   9852:     my ($courseid,%prefs)=@_;
                   9853:     $courseid=~s/^\///;
                   9854:     $courseid=~s/\_/\//g;
                   9855:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9856:     my $chome=homeserver($cnum,$cdomain);
                   9857:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9858: 	return 'error: no such course';
                   9859:     }
                   9860:     my $cstring='';
1.800     albertel 9861:     foreach my $pref (keys(%prefs)) {
                   9862: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9863:     }
1.84      www      9864:     $cstring=~s/\&$//;
                   9865:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9866: }
                   9867: 
                   9868: # ---------------------------------------------------------- Make/modify course
                   9869: 
                   9870: sub createcourse {
1.741     raeburn  9871:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9872:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9873:     $url=&declutter($url);
                   9874:     my $cid='';
1.1028    raeburn  9875:     if ($context eq 'requestcourses') {
                   9876:         my $can_create = 0;
                   9877:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9878:         if ($udom eq $ownerdom) {
                   9879:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9880:                                   $context)) {
                   9881:                 $can_create = 1;
                   9882:             }
                   9883:         } else {
                   9884:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9885:                                            $category);
                   9886:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9887:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9888:                 if (@curr > 0) {
                   9889:                     my @options = qw(approval validate autolimit);
                   9890:                     my $optregex = join('|',@options);
                   9891:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9892:                         $can_create = 1;
                   9893:                     }
                   9894:                 }
                   9895:             }
                   9896:         }
                   9897:         if ($can_create) {
                   9898:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9899:                 unless (&allowed('ccc',$udom)) {
                   9900:                     return 'refused'; 
                   9901:                 }
1.1017    raeburn  9902:             }
                   9903:         } else {
                   9904:             return 'refused';
                   9905:         }
1.1028    raeburn  9906:     } elsif (!&allowed('ccc',$udom)) {
                   9907:         return 'refused';
1.84      www      9908:     }
1.1011    raeburn  9909: # --------------------------------------------------------------- Get Unique ID
                   9910:     my $uname;
                   9911:     if ($cnum =~ /^$match_courseid$/) {
                   9912:         my $chome=&homeserver($cnum,$udom,'true');
                   9913:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9914:             $uname = $cnum;
                   9915:         } else {
1.1038    raeburn  9916:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9917:         }
                   9918:     } else {
1.1038    raeburn  9919:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9920:     }
                   9921:     return $uname if ($uname =~ /^error/);
                   9922: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9923:     if (!defined($course_server)) {
                   9924:         if (defined(&domain($udom,'primary'))) {
                   9925:             $course_server = &domain($udom,'primary');
                   9926:         } else {
                   9927:             $course_server = $env{'user.home'}; 
                   9928:         }
                   9929:     }
                   9930:     my %host_servers =
                   9931:         &Apache::lonnet::get_servers($udom,'library');
                   9932:     unless ($host_servers{$course_server}) {
                   9933:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9934:     }
1.84      www      9935: # ------------------------------------------------------------- Make the course
                   9936:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9937:                       $course_server);
1.84      www      9938:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9939:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9940:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9941: 	return 'error: no such course';
                   9942:     }
1.271     www      9943: # ----------------------------------------------------------------- Course made
1.516     raeburn  9944: # log existence
1.1029    raeburn  9945:     my $now = time;
1.918     raeburn  9946:     my $newcourse = {
                   9947:                     $udom.'_'.$uname => {
1.921     raeburn  9948:                                      description => $description,
                   9949:                                      inst_code   => $inst_code,
                   9950:                                      owner       => $course_owner,
                   9951:                                      type        => $crstype,
1.1029    raeburn  9952:                                      creator     => $env{'user.name'}.':'.
                   9953:                                                     $env{'user.domain'},
                   9954:                                      created     => $now,
                   9955:                                      context     => $context,
1.918     raeburn  9956:                                                 },
                   9957:                     };
1.921     raeburn  9958:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9959: # set toplevel url
1.271     www      9960:     my $topurl=$url;
                   9961:     unless ($nonstandard) {
                   9962: # ------------------------------------------ For standard courses, make top url
                   9963:         my $mapurl=&clutter($url);
1.278     www      9964:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9965:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9966: <map>
                   9967: <resource id="1" type="start"></resource>
                   9968: <resource id="2" src="$mapurl"></resource>
                   9969: <resource id="3" type="finish"></resource>
                   9970: <link index="1" from="1" to="2"></link>
                   9971: <link index="2" from="2" to="3"></link>
                   9972: </map>
                   9973: ENDINITMAP
                   9974:         $topurl=&declutter(
1.638     albertel 9975:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9976:                           );
                   9977:     }
                   9978: # ----------------------------------------------------------- Write preferences
1.84      www      9979:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9980:                      ('description'              => $description,
                   9981:                       'url'                      => $topurl,
                   9982:                       'internal.creator'         => $env{'user.name'}.':'.
                   9983:                                                     $env{'user.domain'},
                   9984:                       'internal.created'         => $now,
                   9985:                       'internal.creationcontext' => $context)
                   9986:                     );
1.84      www      9987:     return '/'.$udom.'/'.$uname;
                   9988: }
                   9989: 
1.1011    raeburn  9990: # ------------------------------------------------------------------- Create ID
                   9991: sub generate_coursenum {
1.1038    raeburn  9992:     my ($udom,$crstype) = @_;
1.1011    raeburn  9993:     my $domdesc = &domain($udom);
                   9994:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9995:     my $first;
                   9996:     if ($crstype eq 'Community') {
                   9997:         $first = '0';
                   9998:     } else {
                   9999:         $first = int(1+rand(9)); 
                   10000:     } 
                   10001:     my $uname=$first.
1.1011    raeburn  10002:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10003:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10004:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10005: # ----------------------------------------------- Make sure that does not exist
                   10006:     my $uhome=&homeserver($uname,$udom,'true');
                   10007:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10008:         if ($crstype eq 'Community') {
                   10009:             $first = '0';
                   10010:         } else {
                   10011:             $first = int(1+rand(9));
                   10012:         }
                   10013:         $uname=$first.
1.1011    raeburn  10014:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10015:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10016:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10017:         $uhome=&homeserver($uname,$udom,'true');
                   10018:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10019:             return 'error: unable to generate unique course-ID';
                   10020:         }
                   10021:     }
                   10022:     return $uname;
                   10023: }
                   10024: 
1.813     albertel 10025: sub is_course {
1.1167    droeschl 10026:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10027:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10028: 
                   10029:     return unless $cdom and $cnum;
                   10030: 
                   10031:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   10032:         '.');
                   10033: 
1.1219    raeburn  10034:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 10035:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10036: }
                   10037: 
1.1015    raeburn  10038: sub store_userdata {
                   10039:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10040:     my $result;
1.1016    raeburn  10041:     if ($datakey ne '') {
1.1013    raeburn  10042:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10043:             if ($udom eq '' || $uname eq '') {
                   10044:                 $udom = $env{'user.domain'};
                   10045:                 $uname = $env{'user.name'};
                   10046:             }
                   10047:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10048:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10049:                 $result = 'error: no_host';
                   10050:             } else {
                   10051:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10052:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10053: 
                   10054:                 my $namevalue='';
                   10055:                 foreach my $key (keys(%{$storehash})) {
                   10056:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10057:                 }
                   10058:                 $namevalue=~s/\&$//;
1.1224    raeburn  10059:                 unless ($namespace eq 'courserequests') {
                   10060:                     $datakey = &escape($datakey);
                   10061:                 }
1.1105    raeburn  10062:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10063:                                   $namevalue,$uhome);
1.1013    raeburn  10064:             }
                   10065:         } else {
                   10066:             $result = 'error: data to store was not a hash reference'; 
                   10067:         }
                   10068:     } else {
                   10069:         $result= 'error: invalid requestkey'; 
                   10070:     }
                   10071:     return $result;
                   10072: }
                   10073: 
1.21      www      10074: # ---------------------------------------------------------- Assign Custom Role
                   10075: 
                   10076: sub assigncustomrole {
1.957     raeburn  10077:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10078:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10079:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10080: }
                   10081: 
                   10082: # ----------------------------------------------------------------- Revoke Role
                   10083: 
                   10084: sub revokerole {
1.957     raeburn  10085:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10086:     my $now=time;
1.965     raeburn  10087:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10088: }
                   10089: 
                   10090: # ---------------------------------------------------------- Revoke Custom Role
                   10091: 
                   10092: sub revokecustomrole {
1.957     raeburn  10093:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10094:     my $now=time;
1.357     www      10095:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10096:            $deleteflag,$selfenroll,$context);
1.17      www      10097: }
                   10098: 
1.533     banghart 10099: # ------------------------------------------------------------ Disk usage
1.535     albertel 10100: sub diskusage {
1.955     raeburn  10101:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10102:     $directorypath =~ s/\/$//;
                   10103:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10104:                        .&escape($getpropath).':'.&escape($uname).':'
                   10105:                        .&escape($udom),homeserver($uname,$udom));
                   10106:     if ($listing eq 'unknown_cmd') {
                   10107:         if ($getpropath) {
                   10108:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10109:         }
                   10110:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10111:     }
1.514     albertel 10112:     return $listing;
1.512     banghart 10113: }
                   10114: 
1.566     banghart 10115: sub is_locked {
1.1096    raeburn  10116:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10117:     my @check;
                   10118:     my $is_locked;
1.1093    raeburn  10119:     push (@check,$file_name);
1.613     albertel 10120:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10121: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10122:     my ($tmp)=keys(%locked);
                   10123:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10124:     
1.566     banghart 10125:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10126:         $is_locked = 'false';
                   10127:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10128:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10129:                $is_locked = 'true';
1.1096    raeburn  10130:                if (ref($which) eq 'ARRAY') {
                   10131:                    push(@{$which},$entry);
                   10132:                } else {
                   10133:                    last;
                   10134:                }
1.745     raeburn  10135:            }
                   10136:        }
1.566     banghart 10137:     } else {
                   10138:         $is_locked = 'false';
                   10139:     }
1.1093    raeburn  10140:     return $is_locked;
1.566     banghart 10141: }
                   10142: 
1.759     albertel 10143: sub declutter_portfile {
                   10144:     my ($file) = @_;
1.833     albertel 10145:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10146:     return $file;
                   10147: }
                   10148: 
1.559     banghart 10149: # ------------------------------------------------------------- Mark as Read Only
                   10150: 
                   10151: sub mark_as_readonly {
                   10152:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10153:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10154:     my ($tmp)=keys(%current_permissions);
                   10155:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10156:     foreach my $file (@{$files}) {
1.759     albertel 10157: 	$file = &declutter_portfile($file);
1.561     banghart 10158:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10159:     }
1.613     albertel 10160:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10161:     return;
                   10162: }
                   10163: 
1.572     banghart 10164: # ------------------------------------------------------------Save Selected Files
                   10165: 
                   10166: sub save_selected_files {
                   10167:     my ($user, $path, @files) = @_;
                   10168:     my $filename = $user."savedfiles";
1.573     banghart 10169:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10170:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10171:     foreach my $file (@files) {
1.620     albertel 10172:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10173:     }
                   10174:     foreach my $file (@other_files) {
1.574     banghart 10175:         print (OUT $file."\n");
1.572     banghart 10176:     }
1.574     banghart 10177:     close (OUT);
1.572     banghart 10178:     return 'ok';
                   10179: }
                   10180: 
1.574     banghart 10181: sub clear_selected_files {
                   10182:     my ($user) = @_;
                   10183:     my $filename = $user."savedfiles";
1.1359    raeburn  10184:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10185:     print (OUT undef);
                   10186:     close (OUT);
                   10187:     return ("ok");    
                   10188: }
                   10189: 
1.572     banghart 10190: sub files_in_path {
                   10191:     my ($user, $path) = @_;
                   10192:     my $filename = $user."savedfiles";
                   10193:     my %return_files;
1.1359    raeburn  10194:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10195:     while (my $line_in = <IN>) {
1.574     banghart 10196:         chomp ($line_in);
                   10197:         my @paths_and_file = split (m!/!, $line_in);
                   10198:         my $file_part = pop (@paths_and_file);
                   10199:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10200:         $path_part.='/';
                   10201:         my $path_and_file = $path_part.$file_part;
                   10202:         if ($path_part eq $path) {
                   10203:             $return_files{$file_part}= 'selected';
                   10204:         }
                   10205:     }
1.574     banghart 10206:     close (IN);
                   10207:     return (\%return_files);
1.572     banghart 10208: }
                   10209: 
                   10210: # called in portfolio select mode, to show files selected NOT in current directory
                   10211: sub files_not_in_path {
                   10212:     my ($user, $path) = @_;
                   10213:     my $filename = $user."savedfiles";
                   10214:     my @return_files;
                   10215:     my $path_part;
1.1359    raeburn  10216:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10217:     while (my $line = <IN>) {
1.572     banghart 10218:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10219:         my @paths_and_file = split(m|/|, $line);
                   10220:         my $file_part = pop(@paths_and_file);
                   10221:         chomp($file_part);
                   10222:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10223:         $path_part .= '/';
                   10224:         my $path_and_file = $path_part.$file_part;
                   10225:         if ($path_part ne $path) {
1.800     albertel 10226:             push(@return_files, ($path_and_file));
1.572     banghart 10227:         }
                   10228:     }
1.800     albertel 10229:     close(OUT);
1.574     banghart 10230:     return (@return_files);
1.572     banghart 10231: }
                   10232: 
1.1273    raeburn  10233: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10234:  
                   10235: sub portfiles_versioning {
                   10236:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10237:     my $portfolio_root = '/userfiles/portfolio';
                   10238:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10239:     foreach my $file (@{$portfiles}) {
                   10240:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10241:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10242:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10243:         my $getpropath = 1;
                   10244:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10245:                                              $stu_name,$getpropath);
                   10246:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10247:         my $new_answer = 
                   10248:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10249:         if ($new_answer ne 'problem getting file') {
                   10250:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10251:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10252:                               [$symb,$env{'request.course.id'},'graded']);
                   10253:         }
                   10254:     }
                   10255: }
                   10256: 
                   10257: sub get_next_version {
                   10258:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10259:     my $version;
                   10260:     if (ref($dir_list) eq 'ARRAY') {
                   10261:         foreach my $row (@{$dir_list}) {
                   10262:             my ($file) = split(/\&/,$row,2);
                   10263:             my ($file_name,$file_version,$file_ext) =
                   10264:                 &file_name_version_ext($file);
                   10265:             if (($file_name eq $answer_name) &&
                   10266:                 ($file_ext eq $answer_ext)) {
                   10267:                      # gets here if filename and extension match,
                   10268:                      # regardless of version
                   10269:                 if ($file_version ne '') {
                   10270:                     # a versioned file is found  so save it for later
                   10271:                     if ($file_version > $version) {
                   10272:                         $version = $file_version;
                   10273:                     }
                   10274:                 }
                   10275:             }
                   10276:         }
                   10277:     }
                   10278:     $version ++;
                   10279:     return($version);
                   10280: }
                   10281: 
                   10282: sub version_selected_portfile {
                   10283:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10284:     my ($answer_name,$answer_ver,$answer_ext) =
                   10285:         &file_name_version_ext($file_name);
                   10286:     my $new_answer;
                   10287:     $env{'form.copy'} =
                   10288:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10289:     if($env{'form.copy'} eq '-1') {
                   10290:         $new_answer = 'problem getting file';
                   10291:     } else {
                   10292:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10293:         my $copy_result = 
                   10294:             &finishuserfileupload($stu_name,$domain,'copy',
                   10295:                                   '/portfolio'.$directory.$new_answer);
                   10296:     }
                   10297:     undef($env{'form.copy'});
                   10298:     return ($new_answer);
                   10299: }
                   10300: 
                   10301: sub file_name_version_ext {
                   10302:     my ($file)=@_;
                   10303:     my @file_parts = split(/\./, $file);
                   10304:     my ($name,$version,$ext);
                   10305:     if (@file_parts > 1) {
                   10306:         $ext=pop(@file_parts);
                   10307:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10308:             $version=pop(@file_parts);
                   10309:         }
                   10310:         $name=join('.',@file_parts);
                   10311:     } else {
                   10312:         $name=join('.',@file_parts);
                   10313:     }
                   10314:     return($name,$version,$ext);
                   10315: }
                   10316: 
1.745     raeburn  10317: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10318: 
1.745     raeburn  10319: sub get_portfile_permissions {
                   10320:     my ($domain,$user) = @_;
1.613     albertel 10321:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10322:     my ($tmp)=keys(%current_permissions);
                   10323:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10324:     return \%current_permissions;
                   10325: }
                   10326: 
                   10327: #---------------------------------------------Get portfolio file access controls
                   10328: 
1.749     raeburn  10329: sub get_access_controls {
1.745     raeburn  10330:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10331:     my %access;
                   10332:     my $real_file = $file;
                   10333:     $file =~ s/\.meta$//;
1.745     raeburn  10334:     if (defined($file)) {
1.749     raeburn  10335:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10336:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10337:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10338:             }
                   10339:         }
1.745     raeburn  10340:     } else {
1.749     raeburn  10341:         foreach my $key (keys(%{$current_permissions})) {
                   10342:             if ($key =~ /\0accesscontrol$/) {
                   10343:                 if (defined($group)) {
                   10344:                     if ($key !~ m-^\Q$group\E/-) {
                   10345:                         next;
                   10346:                     }
                   10347:                 }
                   10348:                 my ($fullpath) = split(/\0/,$key);
                   10349:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10350:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10351:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10352:                     }
                   10353:                 }
                   10354:             }
                   10355:         }
                   10356:     }
                   10357:     return %access;
                   10358: }
                   10359: 
                   10360: sub modify_access_controls {
                   10361:     my ($file_name,$changes,$domain,$user)=@_;
                   10362:     my ($outcome,$deloutcome);
                   10363:     my %store_permissions;
                   10364:     my %new_values;
                   10365:     my %new_control;
                   10366:     my %translation;
                   10367:     my @deletions = ();
                   10368:     my $now = time;
                   10369:     if (exists($$changes{'activate'})) {
                   10370:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10371:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10372:             my $numnew = scalar(@newitems);
                   10373:             for (my $i=0; $i<$numnew; $i++) {
                   10374:                 my $newkey = $newitems[$i];
                   10375:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10376:                 if ($newkey =~ /^\d+:/) { 
                   10377:                     $newkey =~ s/^(\d+)/$newid/;
                   10378:                     $translation{$1} = $newid;
                   10379:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10380:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10381:                     $translation{$1} = $newid;
                   10382:                 }
1.749     raeburn  10383:                 $new_values{$file_name."\0".$newkey} = 
                   10384:                                           $$changes{'activate'}{$newitems[$i]};
                   10385:                 $new_control{$newkey} = $now;
                   10386:             }
                   10387:         }
                   10388:     }
                   10389:     my %todelete;
                   10390:     my %changed_items;
                   10391:     foreach my $action ('delete','update') {
                   10392:         if (exists($$changes{$action})) {
                   10393:             if (ref($$changes{$action}) eq 'HASH') {
                   10394:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10395:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10396:                     if ($action eq 'delete') { 
                   10397:                         $todelete{$itemnum} = 1;
                   10398:                     } else {
                   10399:                         $changed_items{$itemnum} = $key;
                   10400:                     }
                   10401:                 }
1.745     raeburn  10402:             }
                   10403:         }
1.749     raeburn  10404:     }
                   10405:     # get lock on access controls for file.
                   10406:     my $lockhash = {
                   10407:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10408:                                                        ':'.$env{'user.domain'},
                   10409:                    }; 
                   10410:     my $tries = 0;
                   10411:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10412:    
1.1288    damieng  10413:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10414:         $tries ++;
1.1289    damieng  10415:         sleep(0.1);
1.749     raeburn  10416:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10417:     }
                   10418:     if ($gotlock eq 'ok') {
                   10419:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10420:         my ($tmp)=keys(%curr_permissions);
                   10421:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10422:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10423:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10424:             if (ref($curr_controls) eq 'HASH') {
                   10425:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10426:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10427:                     if (defined($todelete{$itemnum})) {
                   10428:                         push(@deletions,$file_name."\0".$control_item);
                   10429:                     } else {
                   10430:                         if (defined($changed_items{$itemnum})) {
                   10431:                             $new_control{$changed_items{$itemnum}} = $now;
                   10432:                             push(@deletions,$file_name."\0".$control_item);
                   10433:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10434:                         } else {
                   10435:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10436:                         }
                   10437:                     }
1.745     raeburn  10438:                 }
                   10439:             }
                   10440:         }
1.970     raeburn  10441:         my ($group);
                   10442:         if (&is_course($domain,$user)) {
                   10443:             ($group,my $file) = split(/\//,$file_name,2);
                   10444:         }
1.749     raeburn  10445:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10446:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10447:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10448:         #  remove lock
                   10449:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10450:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10451:         my $sqlresult =
1.970     raeburn  10452:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10453:                                     $group);
1.749     raeburn  10454:     } else {
                   10455:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10456:     }
1.749     raeburn  10457:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10458: }
                   10459: 
1.827     raeburn  10460: sub make_public_indefinitely {
1.1271    raeburn  10461:     my (@requrl) = @_;
                   10462:     return &automated_portfile_access('public',\@requrl);
                   10463: }
                   10464: 
                   10465: sub automated_portfile_access {
                   10466:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10467:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10468:         return 'invalid';
                   10469:     }
1.1271    raeburn  10470:     my %urls;
                   10471:     if (ref($addsref) eq 'ARRAY') {
                   10472:         foreach my $requrl (@{$addsref}) {
                   10473:             if (&is_portfolio_url($requrl)) {
                   10474:                 unless (exists($urls{$requrl})) {
                   10475:                     $urls{$requrl} = 'add';
                   10476:                 }
                   10477:             }
                   10478:         }
                   10479:     }
                   10480:     if (ref($delsref) eq 'ARRAY') {
                   10481:         foreach my $requrl (@{$delsref}) { 
                   10482:             if (&is_portfolio_url($requrl)) {
                   10483:                 unless (exists($urls{$requrl})) {
                   10484:                     $urls{$requrl} = 'delete'; 
                   10485:                 }
                   10486:             }
                   10487:         }
                   10488:     }
                   10489:     unless (keys(%urls)) {
                   10490:         return 'invalid';
                   10491:     }
                   10492:     my $ip;
                   10493:     if ($accesstype eq 'ip') {
                   10494:         if (ref($info) eq 'HASH') {
                   10495:             if ($info->{'ip'} ne '') {
                   10496:                 $ip = $info->{'ip'};
                   10497:             }
                   10498:         }
                   10499:         if ($ip eq '') {
                   10500:             return 'invalid';
                   10501:         }
                   10502:     }
                   10503:     my $errors;
1.827     raeburn  10504:     my $now = time;
1.1271    raeburn  10505:     my %current_perms;
                   10506:     foreach my $requrl (sort(keys(%urls))) {
                   10507:         my $action;
                   10508:         if ($urls{$requrl} eq 'add') {
                   10509:             $action = 'activate';
                   10510:         } else {
                   10511:             $action = 'none';
                   10512:         }
                   10513:         my $aclnum = 0;
1.827     raeburn  10514:         my (undef,$udom,$unum,$file_name,$group) =
                   10515:             &parse_portfolio_url($requrl);
1.1271    raeburn  10516:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10517:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10518:         }
                   10519:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10520:                                                    $group,$file_name);
                   10521:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10522:             my ($num,$scope,$end,$start) = 
                   10523:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10524:             if ($scope eq $accesstype) {
                   10525:                 if (($start <= $now) && ($end == 0)) {
                   10526:                     if ($accesstype eq 'ip') {
                   10527:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10528:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10529:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10530:                                     if ($urls{$requrl} eq 'add') {
                   10531:                                         $action = 'none';
                   10532:                                         last;
                   10533:                                     } else {
                   10534:                                         $action = 'delete';
                   10535:                                         $aclnum = $num;
                   10536:                                         last;
                   10537:                                     }
                   10538:                                 }
                   10539:                             }
                   10540:                         }
                   10541:                     } elsif ($accesstype eq 'public') {
                   10542:                         if ($urls{$requrl} eq 'add') {
                   10543:                             $action = 'none';
                   10544:                             last;
                   10545:                         } else {
                   10546:                             $action = 'delete';
                   10547:                             $aclnum = $num;
                   10548:                             last;
                   10549:                         }
                   10550:                     }
                   10551:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10552:                     $action = 'update';
                   10553:                     $aclnum = $num;
1.1271    raeburn  10554:                     last;
1.827     raeburn  10555:                 }
                   10556:             }
                   10557:         }
                   10558:         if ($action eq 'none') {
1.1271    raeburn  10559:             next;
1.827     raeburn  10560:         } else {
                   10561:             my %changes;
                   10562:             my $newend = 0;
                   10563:             my $newstart = $now;
1.1271    raeburn  10564:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10565:             $changes{$action}{$newkey} = {
1.1271    raeburn  10566:                 type => $accesstype,
1.827     raeburn  10567:                 time => {
                   10568:                     start => $newstart,
                   10569:                     end   => $newend,
                   10570:                 },
                   10571:             };
1.1271    raeburn  10572:             if ($accesstype eq 'ip') {
                   10573:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10574:             }
1.827     raeburn  10575:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10576:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10577:             unless ($outcome eq 'ok') {
                   10578:                 $errors .= $outcome.' ';
                   10579:             }
1.827     raeburn  10580:         }
1.1271    raeburn  10581:     }
                   10582:     if ($errors) {
                   10583:         $errors =~ s/\s$//;
                   10584:         return $errors;
1.827     raeburn  10585:     } else {
1.1271    raeburn  10586:         return 'ok';
1.827     raeburn  10587:     }
                   10588: }
                   10589: 
1.745     raeburn  10590: #------------------------------------------------------Get Marked as Read Only
                   10591: 
                   10592: sub get_marked_as_readonly {
                   10593:     my ($domain,$user,$what,$group) = @_;
                   10594:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10595:     my @readonly_files;
1.629     banghart 10596:     my $cmp1=$what;
                   10597:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10598:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10599:         if (defined($group)) {
                   10600:             if ($file_name !~ m-^\Q$group\E/-) {
                   10601:                 next;
                   10602:             }
                   10603:         }
1.561     banghart 10604:         if (ref($value) eq "ARRAY"){
                   10605:             foreach my $stored_what (@{$value}) {
1.629     banghart 10606:                 my $cmp2=$stored_what;
1.759     albertel 10607:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10608:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10609:                 }
1.629     banghart 10610:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10611:                     push(@readonly_files, $file_name);
1.745     raeburn  10612:                     last;
1.563     banghart 10613:                 } elsif (!defined($what)) {
                   10614:                     push(@readonly_files, $file_name);
1.745     raeburn  10615:                     last;
1.561     banghart 10616:                 }
                   10617:             }
1.745     raeburn  10618:         }
1.561     banghart 10619:     }
                   10620:     return @readonly_files;
                   10621: }
1.577     banghart 10622: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10623: 
1.577     banghart 10624: sub get_marked_as_readonly_hash {
1.745     raeburn  10625:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10626:     my %readonly_files;
1.745     raeburn  10627:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10628:         if (defined($group)) {
                   10629:             if ($file_name !~ m-^\Q$group\E/-) {
                   10630:                 next;
                   10631:             }
                   10632:         }
1.577     banghart 10633:         if (ref($value) eq "ARRAY"){
                   10634:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10635:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10636:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10637:                         if ($lock_descriptor eq 'graded') {
                   10638:                             $readonly_files{$file_name} = 'graded';
                   10639:                         } elsif ($lock_descriptor eq 'handback') {
                   10640:                             $readonly_files{$file_name} = 'handback';
                   10641:                         } else {
                   10642:                             if (!exists($readonly_files{$file_name})) {
                   10643:                                 $readonly_files{$file_name} = 'locked';
                   10644:                             }
                   10645:                         }
1.745     raeburn  10646:                     }
1.750     banghart 10647:                 } 
1.577     banghart 10648:             }
                   10649:         } 
                   10650:     }
                   10651:     return %readonly_files;
                   10652: }
1.559     banghart 10653: # ------------------------------------------------------------ Unmark as Read Only
                   10654: 
                   10655: sub unmark_as_readonly {
1.629     banghart 10656:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10657:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10658:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10659:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10660:     my $symb_crs = $what;
                   10661:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10662:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10663:     my ($tmp)=keys(%current_permissions);
                   10664:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10665:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10666:     foreach my $file (@readonly_files) {
1.759     albertel 10667: 	my $clean_file = &declutter_portfile($file);
                   10668: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10669: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10670:         my @new_locks;
                   10671:         my @del_keys;
                   10672:         if (ref($current_locks) eq "ARRAY"){
                   10673:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10674:                 my $compare=$locker;
1.749     raeburn  10675:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10676:                     $compare=join('',@{$locker});
1.746     raeburn  10677:                     if ($compare ne $symb_crs) {
                   10678:                         push(@new_locks, $locker);
                   10679:                     }
1.563     banghart 10680:                 }
                   10681:             }
1.650     albertel 10682:             if (scalar(@new_locks) > 0) {
1.563     banghart 10683:                 $current_permissions{$file} = \@new_locks;
                   10684:             } else {
                   10685:                 push(@del_keys, $file);
1.613     albertel 10686:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10687:                 delete($current_permissions{$file});
1.563     banghart 10688:             }
                   10689:         }
1.561     banghart 10690:     }
1.613     albertel 10691:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10692:     return;
                   10693: }
1.512     banghart 10694: 
1.17      www      10695: # ------------------------------------------------------------ Directory lister
                   10696: 
                   10697: sub dirlist {
1.955     raeburn  10698:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10699:     $uri=~s/^\///;
                   10700:     $uri=~s/\/$//;
1.253     stredwic 10701:     my ($udom, $uname);
1.955     raeburn  10702:     if ($getuserdir) {
1.253     stredwic 10703:         $udom = $userdomain;
                   10704:         $uname = $username;
1.955     raeburn  10705:     } else {
                   10706:         (undef,$udom,$uname)=split(/\//,$uri);
                   10707:         if(defined($userdomain)) {
                   10708:             $udom = $userdomain;
                   10709:         }
                   10710:         if(defined($username)) {
                   10711:             $uname = $username;
                   10712:         }
1.253     stredwic 10713:     }
1.955     raeburn  10714:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10715: 
1.955     raeburn  10716:     $dirRoot = $perlvar{'lonDocRoot'};
                   10717:     if (defined($getpropath)) {
                   10718:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10719:         $dirRoot =~ s/\/$//;
1.955     raeburn  10720:     } elsif (defined($getuserdir)) {
                   10721:         my $subdir=$uname.'__';
                   10722:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10723:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10724:                    ."/$udom/$subdir/$uname";
                   10725:     } elsif (defined($alternateRoot)) {
                   10726:         $dirRoot = $alternateRoot;
1.751     banghart 10727:     }
1.253     stredwic 10728: 
                   10729:     if($udom) {
                   10730:         if($uname) {
1.1135    raeburn  10731:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10732:             if ($uhome eq 'no_host') {
                   10733:                 return ([],'no_host');
                   10734:             }
1.955     raeburn  10735:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10736:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10737:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10738:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10739:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10740:             } else {
                   10741:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10742:             }
1.605     matthew  10743:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10744:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10745:                 @listing_results = split(/:/,$listing);
                   10746:             } else {
                   10747:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10748:             }
1.1135    raeburn  10749:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10750:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10751:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10752:                 return ([],$listing);
                   10753:             } else {
                   10754:                 return (\@listing_results);
1.1135    raeburn  10755:             }
1.955     raeburn  10756:         } elsif(!$alternateRoot) {
1.1136    raeburn  10757:             my (%allusers,%listerror);
1.841     albertel 10758: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10759:  	    foreach my $tryserver (keys(%servers)) {
                   10760:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10761:                                   &escape($udom),$tryserver);
                   10762:                 if ($listing eq 'unknown_cmd') {
                   10763: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10764: 				      $udom, $tryserver);
                   10765:                 } else {
                   10766:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10767:                 }
1.841     albertel 10768: 		if ($listing eq 'unknown_cmd') {
                   10769: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10770: 				      $udom, $tryserver);
                   10771: 		    @listing_results = split(/:/,$listing);
                   10772: 		} else {
                   10773: 		    @listing_results =
                   10774: 			map { &unescape($_); } split(/:/,$listing);
                   10775: 		}
1.1136    raeburn  10776:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10777:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10778:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10779:                     $listerror{$tryserver} = $listing;
                   10780:                 } else {
1.841     albertel 10781: 		    foreach my $line (@listing_results) {
                   10782: 			my ($entry) = split(/&/,$line,2);
                   10783: 			$allusers{$entry} = 1;
                   10784: 		    }
                   10785: 		}
1.253     stredwic 10786:             }
1.1136    raeburn  10787:             my @alluserslist=();
1.800     albertel 10788:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10789:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10790:             }
1.1318    droeschl 10791: 
                   10792:             if (!%listerror) {
                   10793:                 # no errors
                   10794:                 return (\@alluserslist);
                   10795:             } elsif (scalar(keys(%servers)) == 1) {
                   10796:                 # one library server, one error 
                   10797:                 my ($key) = keys(%listerror);
                   10798:                 return (\@alluserslist, $listerror{$key});
                   10799:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10800:                 # con_lost indicates that we might miss data from at least one
                   10801:                 # library server
                   10802:                 return (\@alluserslist, 'con_lost');
                   10803:             } else {
                   10804:                 # multiple library servers and no con_lost -> data should be
                   10805:                 # complete. 
                   10806:                 return (\@alluserslist);
                   10807:             }
                   10808: 
1.253     stredwic 10809:         } else {
1.1136    raeburn  10810:             return ([],'missing username');
1.253     stredwic 10811:         }
1.955     raeburn  10812:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10813:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10814:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10815:         return (\@all_domains);
1.955     raeburn  10816:     } else {
1.1136    raeburn  10817:         return ([],'missing domain');
1.275     stredwic 10818:     }
                   10819: }
                   10820: 
                   10821: # --------------------------------------------- GetFileTimestamp
                   10822: # This function utilizes dirlist and returns the date stamp for
                   10823: # when it was last modified.  It will also return an error of -1
                   10824: # if an error occurs
                   10825: 
                   10826: sub GetFileTimestamp {
1.955     raeburn  10827:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10828:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10829:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10830:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10831:                                     undef,$getuserdir);
                   10832:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10833:         return -1;
                   10834:     }
                   10835:     if (ref($fileref) eq 'ARRAY') {
                   10836:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10837:         # @stats contains first the filename, then the stat output
                   10838:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10839:     } else {
                   10840:         return -1;
1.253     stredwic 10841:     }
1.26      www      10842: }
                   10843: 
1.712     albertel 10844: sub stat_file {
                   10845:     my ($uri) = @_;
1.787     albertel 10846:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10847: 
1.955     raeburn  10848:     my ($udom,$uname,$file);
1.712     albertel 10849:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10850: 	($udom,$uname,$file) =
1.811     albertel 10851: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10852: 	$file = 'userfiles/'.$file;
                   10853:     }
                   10854:     if ($uri =~ m-^/res/-) {
                   10855: 	($udom,$uname) = 
1.807     albertel 10856: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10857: 	$file = $uri;
                   10858:     }
                   10859: 
                   10860:     if (!$udom || !$uname || !$file) {
                   10861: 	# unable to handle the uri
                   10862: 	return ();
                   10863:     }
1.956     raeburn  10864:     my $getpropath;
                   10865:     if ($file =~ /^userfiles\//) {
                   10866:         $getpropath = 1;
                   10867:     }
1.1136    raeburn  10868:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10869:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10870:         return ();
                   10871:     } else {
                   10872:         if (ref($listref) eq 'ARRAY') {
                   10873:             my @stats = split('&',$listref->[0]);
                   10874: 	    shift(@stats); #filename is first
                   10875: 	    return @stats;
                   10876:         }
1.712     albertel 10877:     }
                   10878:     return ();
                   10879: }
                   10880: 
1.1313    raeburn  10881: # --------------------------------------------------------- recursedirs
                   10882: # Recursive function to traverse either a specific user's Authoring Space
                   10883: # or corresponding Published Resource Space, and populate the hash ref:
                   10884: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10885: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10886: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10887: # files in Authoring Space.
                   10888: #
                   10889: # Inputs:
                   10890: #
                   10891: # $is_home - true if current server is home server for user's space
                   10892: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10893: # $docroot - Document root (i.e., /home/httpd/html
                   10894: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10895: # $relpath - Current path (relative to top level).
                   10896: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10897: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10898: #
                   10899: # Returns: nothing
                   10900: #
                   10901: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10902: #
                   10903: # Currently used by interface/londocs.pm to create linked select boxes for
                   10904: # directory and filename to import a Course "Author" resource into a course, and
                   10905: # also to create linked select boxes for Authoring Space and Directory to choose
                   10906: # save location for creation of a new "standard" problem from the Course Editor.
                   10907: #
                   10908: 
                   10909: sub recursedirs {
                   10910:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10911:     return unless (ref($dirhashref) eq 'HASH');
                   10912:     my $currpath = $docroot.$toppath;
                   10913:     if ($relpath) {
                   10914:         $currpath .= "/$relpath";
                   10915:     }
                   10916:     my $savefile;
                   10917:     if (ref($filehashref)) {
                   10918:         $savefile = 1;
                   10919:     }
                   10920:     if ($is_home) {
                   10921:         if (opendir(my $dirh,$currpath)) {
                   10922:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10923:                 next if ($item eq '');
                   10924:                 if (-d "$currpath/$item") {
                   10925:                     my $newpath;
                   10926:                     if ($relpath) {
                   10927:                         $newpath = "$relpath/$item";
                   10928:                     } else {
                   10929:                         $newpath = $item;
                   10930:                     }
                   10931:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10932:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10933:                 } elsif ($savefile) {
                   10934:                     if ($context eq 'priv') {
                   10935:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10936:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10937:                         }
                   10938:                     } else {
                   10939:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10940:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10941:                         }
                   10942:                     }
                   10943:                 }
                   10944:             }
                   10945:             closedir($dirh);
                   10946:         }
                   10947:     } else {
                   10948:         my ($dirlistref,$listerror) =
                   10949:             &dirlist($toppath.$relpath);
                   10950:         my @dir_lines;
                   10951:         my $dirptr=16384;
                   10952:         if (ref($dirlistref) eq 'ARRAY') {
                   10953:             foreach my $dir_line (sort
                   10954:                               {
                   10955:                                   my ($afile)=split('&',$a,2);
                   10956:                                   my ($bfile)=split('&',$b,2);
                   10957:                                   return (lc($afile) cmp lc($bfile));
                   10958:                               } (@{$dirlistref})) {
                   10959:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10960:                     split(/\&/,$dir_line,16);
                   10961:                 $item =~ s/\s+$//;
                   10962:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10963:                 if ($dirptr&$testdir) {
                   10964:                     my $newpath;
                   10965:                     if ($relpath) {
                   10966:                         $newpath = "$relpath/$item";
                   10967:                     } else {
                   10968:                         $relpath = '/';
                   10969:                         $newpath = $item;
                   10970:                     }
                   10971:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10972:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10973:                 } elsif ($savefile) {
                   10974:                     if ($context eq 'priv') {
                   10975:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10976:                             $filehashref->{$relpath}{$item} = 1;
                   10977:                         }
                   10978:                     } else {
                   10979:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10980:                             $filehashref->{$relpath}{$item} = 1;
                   10981:                         }
                   10982:                     }
                   10983:                 }
                   10984:             }
                   10985:         }
                   10986:     }
                   10987:     return;
                   10988: }
                   10989: 
1.26      www      10990: # -------------------------------------------------------- Value of a Condition
                   10991: 
1.713     albertel 10992: # gets the value of a specific preevaluated condition
                   10993: #    stored in the string  $env{user.state.<cid>}
                   10994: # or looks up a condition reference in the bighash and if if hasn't
                   10995: # already been evaluated recurses into docondval to get the value of
                   10996: # the condition, then memoizing it to 
                   10997: #   $env{user.state.<cid>.<condition>}
1.40      www      10998: sub directcondval {
                   10999:     my $number=shift;
1.620     albertel 11000:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11001: 	&Apache::lonuserstate::evalstate();
                   11002:     }
1.713     albertel 11003:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11004: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11005:     } elsif ($number =~ /^_/) {
                   11006: 	my $sub_condition;
                   11007: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11008: 		&GDBM_READER(),0640)) {
                   11009: 	    $sub_condition=$bighash{'conditions'.$number};
                   11010: 	    untie(%bighash);
                   11011: 	}
                   11012: 	my $value = &docondval($sub_condition);
1.949     raeburn  11013: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11014: 	return $value;
                   11015:     }
1.620     albertel 11016:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11017:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11018:     } else {
                   11019:        return 2;
                   11020:     }
                   11021: }
                   11022: 
1.713     albertel 11023: # get the collection of conditions for this resource
1.26      www      11024: sub condval {
                   11025:     my $condidx=shift;
1.54      www      11026:     my $allpathcond='';
1.713     albertel 11027:     foreach my $cond (split(/\|/,$condidx)) {
                   11028: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11029: 	    $allpathcond.=
                   11030: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11031: 	}
1.191     harris41 11032:     }
1.54      www      11033:     $allpathcond=~s/\|$//;
1.713     albertel 11034:     return &docondval($allpathcond);
                   11035: }
                   11036: 
                   11037: #evaluates an expression of conditions
                   11038: sub docondval {
                   11039:     my ($allpathcond) = @_;
                   11040:     my $result=0;
                   11041:     if ($env{'request.course.id'}
                   11042: 	&& defined($allpathcond)) {
                   11043: 	my $operand='|';
                   11044: 	my @stack;
                   11045: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11046: 	    if ($chunk eq '(') {
                   11047: 		push @stack,($operand,$result);
                   11048: 	    } elsif ($chunk eq ')') {
                   11049: 		my $before=pop @stack;
                   11050: 		if (pop @stack eq '&') {
                   11051: 		    $result=$result>$before?$before:$result;
                   11052: 		} else {
                   11053: 		    $result=$result>$before?$result:$before;
                   11054: 		}
                   11055: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11056: 		$operand=$chunk;
                   11057: 	    } else {
                   11058: 		my $new=directcondval($chunk);
                   11059: 		if ($operand eq '&') {
                   11060: 		    $result=$result>$new?$new:$result;
                   11061: 		} else {
                   11062: 		    $result=$result>$new?$result:$new;
                   11063: 		}
                   11064: 	    }
                   11065: 	}
1.26      www      11066:     }
                   11067:     return $result;
1.421     albertel 11068: }
                   11069: 
                   11070: # ---------------------------------------------------- Devalidate courseresdata
                   11071: 
                   11072: sub devalidatecourseresdata {
                   11073:     my ($coursenum,$coursedomain)=@_;
                   11074:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11075:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11076: }
                   11077: 
1.763     www      11078: 
1.200     www      11079: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11080: #
                   11081: #  Parameters:
                   11082: #      $coursenum    - Number of the course.
                   11083: #      $coursedomain - Domain at which the course was created.
                   11084: #  Returns:
                   11085: #     A hash of the course parameters along (I think) with timestamps
                   11086: #     and version info.
1.877     foxr     11087: 
1.624     albertel 11088: sub get_courseresdata {
                   11089:     my ($coursenum,$coursedomain)=@_;
1.200     www      11090:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11091:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11092:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11093:     my %dumpreply;
1.417     albertel 11094:     unless (defined($cached)) {
1.624     albertel 11095: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11096: 	$result=\%dumpreply;
1.251     albertel 11097: 	my ($tmp) = keys(%dumpreply);
                   11098: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11099: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11100: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11101: 	    return $tmp;
1.416     albertel 11102: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11103: 	    $result=undef;
1.599     albertel 11104: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11105: 	}
                   11106:     }
1.624     albertel 11107:     return $result;
                   11108: }
                   11109: 
1.633     albertel 11110: sub devalidateuserresdata {
                   11111:     my ($uname,$udom)=@_;
                   11112:     my $hashid="$udom:$uname";
                   11113:     &devalidate_cache_new('userres',$hashid);
                   11114: }
                   11115: 
1.624     albertel 11116: sub get_userresdata {
                   11117:     my ($uname,$udom)=@_;
                   11118:     #most student don\'t have any data set, check if there is some data
                   11119:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11120: 
                   11121:     my $hashid="$udom:$uname";
                   11122:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11123:     if (!defined($cached)) {
                   11124: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11125: 	$result=\%resourcedata;
                   11126: 	&do_cache_new('userres',$hashid,$result,600);
                   11127:     }
                   11128:     my ($tmp)=keys(%$result);
                   11129:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11130: 	return $result;
                   11131:     }
                   11132:     #error 2 occurs when the .db doesn't exist
                   11133:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11134:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11135: 	    &logthis("<font color=\"blue\">WARNING:".
                   11136: 		     " Trying to get resource data for ".
                   11137: 		     $uname." at ".$udom.": ".
                   11138: 		     $tmp."</font>");
                   11139:         }
1.624     albertel 11140:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11141: 	#&EXT_cache_set($udom,$uname);
                   11142: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11143: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11144:     }
                   11145:     return $tmp;
                   11146: }
1.879     foxr     11147: #----------------------------------------------- resdata - return resource data
                   11148: #  Purpose:
                   11149: #    Return resource data for either users or for a course.
                   11150: #  Parameters:
                   11151: #     $name      - Course/user name.
                   11152: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11153: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11154: #     $mapp      - decluttered URL of enclosing map  
                   11155: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11156: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11157: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11158: #     $courseid  - CourseID (first part of param identifier).
                   11159: #     $modifier  - Middle part of param identifier.
                   11160: #     $what      - Last part of param identifier.
1.879     foxr     11161: #     @which     - Array of names of resources desired.
                   11162: #  Returns:
                   11163: #     The value of the first reasource in @which that is found in the
                   11164: #     resource hash.
                   11165: #  Exceptional Conditions:
                   11166: #     If the $type passed in is not valid (not the string 'course' or 
                   11167: #     'user', an undefined  reference is returned.
                   11168: #     If none of the resources are found, an undef is returned
1.624     albertel 11169: sub resdata {
1.1301    raeburn  11170:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11171:         $modifier,$what,@which)=@_;
1.624     albertel 11172:     my $result;
                   11173:     if ($type eq 'course') {
                   11174: 	$result=&get_courseresdata($name,$domain);
                   11175:     } elsif ($type eq 'user') {
                   11176: 	$result=&get_userresdata($name,$domain);
                   11177:     }
                   11178:     if (!ref($result)) { return $result; }    
1.251     albertel 11179:     foreach my $item (@which) {
1.1301    raeburn  11180:         if ($item->[1] eq 'course') {
                   11181:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11182:                 unless ($$recursed) {
1.1302    raeburn  11183:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11184:                     $$recursed = 1;
                   11185:                 }
                   11186:                 foreach my $item (@${recurseup}) {
                   11187:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11188:                     last if (defined($result->{$norecursechk}));
                   11189:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11190:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11191:                 }
                   11192:             }
                   11193:         }
                   11194:         if (defined($result->{$item->[0]})) {
1.927     albertel 11195: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11196: 	}
1.250     albertel 11197:     }
1.291     albertel 11198:     return undef;
1.200     www      11199: }
                   11200: 
1.1360    raeburn  11201: sub get_domain_lti {
                   11202:     my ($cdom,$context) = @_;
                   11203:     my ($name,%lti);
                   11204:     if ($context eq 'consumer') {
                   11205:         $name = 'ltitools';
                   11206:     } elsif ($context eq 'provider') {
                   11207:         $name = 'lti';
                   11208:     } else {
                   11209:         return %lti;
                   11210:     }
                   11211:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11212:     if (defined($cached)) {
                   11213:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11214:             %lti = %{$result};
1.1298    raeburn  11215:         }
                   11216:     } else {
1.1360    raeburn  11217:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11218:         if (ref($domconfig{$name}) eq 'HASH') {
                   11219:             %lti = %{$domconfig{$name}};
                   11220:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11221:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11222:                 foreach my $id (keys(%lti)) {
                   11223:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11224:                         foreach my $item ('key','secret') {
1.1360    raeburn  11225:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11226:                         }
                   11227:                     }
                   11228:                 }
                   11229:             }
1.1298    raeburn  11230:         }
                   11231:         my $cachetime = 24*60*60;
1.1360    raeburn  11232:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11233:     }
1.1360    raeburn  11234:     return %lti;
1.1298    raeburn  11235: }
                   11236: 
1.1236    raeburn  11237: sub get_numsuppfiles {
                   11238:     my ($cnum,$cdom,$ignorecache)=@_;
                   11239:     my $hashid=$cnum.':'.$cdom;
                   11240:     my ($suppcount,$cached);
                   11241:     unless ($ignorecache) {
                   11242:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11243:     }
                   11244:     unless (defined($cached)) {
                   11245:         my $chome=&homeserver($cnum,$cdom);
                   11246:         unless ($chome eq 'no_host') {
1.1366    raeburn  11247:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11248:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11249:             ($suppcount,$supptools,$errors) =
                   11250:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11251:                                                          $supptools,$errors);
1.1236    raeburn  11252:         }
                   11253:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11254:     }
                   11255:     return $suppcount;
                   11256: }
                   11257: 
1.379     matthew  11258: #
                   11259: # EXT resource caching routines
                   11260: #
                   11261: 
1.1302    raeburn  11262: {
                   11263: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11264: #
                   11265: # The course for which we cache
                   11266: my $cachedmapkey='';
                   11267: # The cached recursive maps for this course
                   11268: my %cachedmaps=();
                   11269: # When this was last done
                   11270: my $cachedmaptime='';
                   11271: 
1.379     matthew  11272: sub clear_EXT_cache_status {
1.383     albertel 11273:     &delenv('cache.EXT.');
1.379     matthew  11274: }
                   11275: 
                   11276: sub EXT_cache_status {
                   11277:     my ($target_domain,$target_user) = @_;
1.383     albertel 11278:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11279:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11280:         # We know already the user has no data
                   11281:         return 1;
                   11282:     } else {
                   11283:         return 0;
                   11284:     }
                   11285: }
                   11286: 
                   11287: sub EXT_cache_set {
                   11288:     my ($target_domain,$target_user) = @_;
1.383     albertel 11289:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11290:     #&appenv({$cachename => time});
1.379     matthew  11291: }
                   11292: 
1.28      www      11293: # --------------------------------------------------------- Value of a Variable
1.58      www      11294: sub EXT {
1.715     albertel 11295: 
1.1228    raeburn  11296:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11297:     unless ($varname) { return ''; }
1.218     albertel 11298:     #get real user name/domain, courseid and symb
                   11299:     my $courseid;
1.359     albertel 11300:     my $publicuser;
1.427     www      11301:     if ($symbparm) {
                   11302: 	$symbparm=&get_symb_from_alias($symbparm);
                   11303:     }
1.218     albertel 11304:     if (!($uname && $udom)) {
1.790     albertel 11305:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11306:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11307:     } else {
1.620     albertel 11308: 	$courseid=$env{'request.course.id'};
1.218     albertel 11309:     }
1.48      www      11310:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11311:     my $rest;
1.320     albertel 11312:     if (defined($therest[0])) {
1.48      www      11313:        $rest=join('.',@therest);
                   11314:     } else {
                   11315:        $rest='';
                   11316:     }
1.320     albertel 11317: 
1.57      www      11318:     my $qualifierrest=$qualifier;
                   11319:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11320:     my $spacequalifierrest=$space;
                   11321:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11322:     if ($realm eq 'user') {
1.48      www      11323: # --------------------------------------------------------------- user.resource
                   11324: 	if ($space eq 'resource') {
1.651     albertel 11325: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11326: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11327: 		 &&
1.744     albertel 11328: 		 ($symbparm eq &symbread()) ) {	
                   11329: 		# if we are in the middle of processing the resource the
                   11330: 		# get the value we are planning on committing
                   11331:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11332:                     return $Apache::lonhomework::results{$qualifierrest};
                   11333:                 } else {
                   11334:                     return $Apache::lonhomework::history{$qualifierrest};
                   11335:                 }
1.335     albertel 11336: 	    } else {
1.359     albertel 11337: 		my %restored;
1.620     albertel 11338: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11339: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11340: 		} else {
                   11341: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11342: 		}
1.335     albertel 11343: 		return $restored{$qualifierrest};
                   11344: 	    }
1.48      www      11345: # ----------------------------------------------------------------- user.access
                   11346:         } elsif ($space eq 'access') {
1.218     albertel 11347: 	    # FIXME - not supporting calls for a specific user
1.48      www      11348:             return &allowed($qualifier,$rest);
                   11349: # ------------------------------------------ user.preferences, user.environment
                   11350:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11351: 	    if (($uname eq $env{'user.name'}) &&
                   11352: 		($udom eq $env{'user.domain'})) {
                   11353: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11354: 	    } else {
1.359     albertel 11355: 		my %returnhash;
                   11356: 		if (!$publicuser) {
                   11357: 		    %returnhash=&userenvironment($udom,$uname,
                   11358: 						 $qualifierrest);
                   11359: 		}
1.218     albertel 11360: 		return $returnhash{$qualifierrest};
                   11361: 	    }
1.48      www      11362: # ----------------------------------------------------------------- user.course
                   11363:         } elsif ($space eq 'course') {
1.218     albertel 11364: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11365:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11366: # ------------------------------------------------------------------- user.role
                   11367:         } elsif ($space eq 'role') {
1.218     albertel 11368: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11369:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11370:             if ($qualifier eq 'value') {
                   11371: 		return $role;
                   11372:             } elsif ($qualifier eq 'extent') {
                   11373:                 return $where;
                   11374:             }
                   11375: # ----------------------------------------------------------------- user.domain
                   11376:         } elsif ($space eq 'domain') {
1.218     albertel 11377:             return $udom;
1.48      www      11378: # ------------------------------------------------------------------- user.name
                   11379:         } elsif ($space eq 'name') {
1.218     albertel 11380:             return $uname;
1.48      www      11381: # ---------------------------------------------------- Any other user namespace
1.29      www      11382:         } else {
1.359     albertel 11383: 	    my %reply;
                   11384: 	    if (!$publicuser) {
                   11385: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11386: 	    }
                   11387: 	    return $reply{$qualifierrest};
1.48      www      11388:         }
1.236     www      11389:     } elsif ($realm eq 'query') {
                   11390: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11391:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11392: 						[$spacequalifierrest]);
1.620     albertel 11393: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11394:    } elsif ($realm eq 'request') {
1.48      www      11395: # ------------------------------------------------------------- request.browser
                   11396:         if ($space eq 'browser') {
1.1145    bisitz   11397:             return $env{'browser.'.$qualifier};
1.57      www      11398: # ------------------------------------------------------------ request.filename
                   11399:         } else {
1.620     albertel 11400:             return $env{'request.'.$spacequalifierrest};
1.29      www      11401:         }
1.28      www      11402:     } elsif ($realm eq 'course') {
1.48      www      11403: # ---------------------------------------------------------- course.description
1.620     albertel 11404:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11405:     } elsif ($realm eq 'resource') {
1.165     www      11406: 
1.620     albertel 11407: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11408: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11409: 	}
1.693     albertel 11410: 
1.1232    raeburn  11411:         if ($qualifier eq '') {
                   11412: 	    if ($space eq 'title') {
                   11413: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11414: 	        return &gettitle($symbparm);
                   11415: 	    }
1.693     albertel 11416: 	
1.1232    raeburn  11417: 	    if ($space eq 'map') {
                   11418: 	        my ($map) = &decode_symb($symbparm);
                   11419: 	        return &symbread($map);
                   11420: 	    }
                   11421:             if ($space eq 'maptitle') {
                   11422:                 my ($map) = &decode_symb($symbparm);
                   11423:                 return &gettitle($map);
                   11424:             }
                   11425: 	    if ($space eq 'filename') {
                   11426: 	        if ($symbparm) {
                   11427: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11428: 	        }
                   11429: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11430: 	    }
1.1232    raeburn  11431: 
1.1233    raeburn  11432:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11433:                 if ($space eq 'visibleparts') {
                   11434:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11435:                     my $item;
                   11436:                     if (ref($navmap)) {
                   11437:                         my $res = $navmap->getBySymb($symbparm);
                   11438:                         my $parts = $res->parts();
                   11439:                         if (ref($parts) eq 'ARRAY') {
                   11440:                             $item = join(',',@{$parts});
                   11441:                         }
                   11442:                         undef($navmap);
1.1232    raeburn  11443:                     }
1.1233    raeburn  11444:                     return $item;
1.1232    raeburn  11445:                 }
                   11446:             }
                   11447:         }
1.693     albertel 11448: 
1.1301    raeburn  11449: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11450: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11451:         if (($courseid eq '') && ($cid)) {
                   11452:             $courseid = $cid;
                   11453:         }
                   11454: 	if (($symbparm && $courseid) && 
                   11455: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11456: 
1.218     albertel 11457: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11458: 
1.60      www      11459: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11460: 	    my $symbp=$symbparm;
1.1301    raeburn  11461: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11462: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11463:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11464: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11465: 	    if (($env{'user.name'} eq $uname) &&
                   11466: 		($env{'user.domain'} eq $udom)) {
                   11467: 		$section=$env{'request.course.sec'};
1.733     raeburn  11468:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11469:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11470: 	    } else {
1.539     albertel 11471: 		if (! defined($usection)) {
1.551     albertel 11472: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11473: 		} else {
                   11474: 		    $section = $usection;
                   11475: 		}
1.733     raeburn  11476:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11477: 	    }
                   11478: 
                   11479: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11480: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11481:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11482: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11483: 
1.593     albertel 11484: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11485: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11486:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11487: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11488: 
1.60      www      11489: # ----------------------------------------------------------- first, check user
1.624     albertel 11490: 
1.1301    raeburn  11491: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11492:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11493: 				       ([$courselevelr,'resource'],
                   11494: 					[$courselevelm,'map'     ],
1.1301    raeburn  11495:                                         [$courseleveli,'map'     ],
1.927     albertel 11496: 					[$courselevel, 'course'  ]));
1.931     albertel 11497: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11498: 
1.594     albertel 11499: # ------------------------------------------------ second, check some of course
1.684     raeburn  11500:             my $coursereply;
1.691     raeburn  11501:             if (@groups > 0) {
                   11502:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11503:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11504:                                        $mapp,\$recursed,\@recurseup);
                   11505:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11506:             }
1.96      www      11507: 
1.684     raeburn  11508: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11509: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11510: 				  'course',$mapp,\$recursed,\@recurseup,
                   11511:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11512: 				  ([$seclevelr,   'resource'],
                   11513: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11514:                                    [$secleveli,   'map'     ],
1.927     albertel 11515: 				   [$seclevel,    'course'  ],
                   11516: 				   [$courselevelr,'resource']));
                   11517: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11518: 
1.60      www      11519: # ------------------------------------------------------ third, check map parms
1.218     albertel 11520: 	    my %parmhash=();
                   11521: 	    my $thisparm='';
                   11522: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11523: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11524: 		    &GDBM_READER(),0640)) {
1.218     albertel 11525: 		$thisparm=$parmhash{$symbparm};
                   11526: 		untie(%parmhash);
                   11527: 	    }
1.927     albertel 11528: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11529: 	}
1.594     albertel 11530: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11531:  
                   11532:         my $what = $spacequalifierrest;
                   11533: 	$what=~s/\./\_/;
1.282     albertel 11534: 	my $filename;
                   11535: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11536: 	if ($symbparm) {
1.409     www      11537: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11538: 	} else {
1.620     albertel 11539: 	    $filename=$env{'request.filename'};
1.282     albertel 11540: 	}
1.1362    raeburn  11541:         my $toolsymb;
                   11542:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11543:             $toolsymb = $symbparm;
                   11544:         }
                   11545: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11546: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11547: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11548: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11549: 
1.1301    raeburn  11550: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11551: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11552: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11553: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11554: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11555: 				     'course',$mapp,\$recursed,\@recurseup,
                   11556:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11557: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11558:                                       [$courseleveli,'map'   ],
1.927     albertel 11559: 				      [$courselevel, 'course']));
                   11560: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11561: 	}
1.145     www      11562: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11563: 	unless ($space eq '0') {
1.336     albertel 11564: 	    my @parts=split(/_/,$space);
                   11565: 	    my $id=pop(@parts);
                   11566: 	    my $part=join('_',@parts);
                   11567: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11568: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11569: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11570: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11571: 	}
1.395     albertel 11572: 	if ($recurse) { return undef; }
1.1362    raeburn  11573: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11574: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11575: # ---------------------------------------------------- Any other user namespace
                   11576:     } elsif ($realm eq 'environment') {
                   11577: # ----------------------------------------------------------------- environment
1.620     albertel 11578: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11579: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11580: 	} else {
1.770     albertel 11581: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11582: 		return '';
                   11583: 	    }
1.219     albertel 11584: 	    my %returnhash=&userenvironment($udom,$uname,
                   11585: 					    $spacequalifierrest);
                   11586: 	    return $returnhash{$spacequalifierrest};
                   11587: 	}
1.28      www      11588:     } elsif ($realm eq 'system') {
1.48      www      11589: # ----------------------------------------------------------------- system.time
                   11590: 	if ($space eq 'time') {
                   11591: 	    return time;
                   11592:         }
1.696     albertel 11593:     } elsif ($realm eq 'server') {
                   11594: # ----------------------------------------------------------------- system.time
                   11595: 	if ($space eq 'name') {
                   11596: 	    return $ENV{'SERVER_NAME'};
                   11597:         }
1.28      www      11598:     }
1.48      www      11599:     return '';
1.61      www      11600: }
                   11601: 
1.927     albertel 11602: sub get_reply {
                   11603:     my ($reply_value) = @_;
1.940     raeburn  11604:     if (ref($reply_value) eq 'ARRAY') {
                   11605:         if (wantarray) {
                   11606: 	    return @$reply_value;
                   11607:         }
                   11608:         return $reply_value->[0];
                   11609:     } else {
                   11610:         return $reply_value;
1.927     albertel 11611:     }
                   11612: }
                   11613: 
1.691     raeburn  11614: sub check_group_parms {
1.1301    raeburn  11615:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11616:         $recursed,$recurseupref) = @_;
                   11617:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11618:                   [$what,'course']);
                   11619:     my $coursereply;
1.691     raeburn  11620:     foreach my $group (@{$groups}) {
1.1301    raeburn  11621:         my @groupitems = ();
1.691     raeburn  11622:         foreach my $level (@levels) {
1.927     albertel 11623:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11624:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11625:         }
1.1301    raeburn  11626:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11627:                                    $env{'course.'.$courseid.'.domain'},
                   11628:                                    'course',$mapp,$recursed,$recurseupref,
                   11629:                                    $courseid,'.['.$group.'].',$what,
                   11630:                                    @groupitems);
                   11631:         last if (defined($coursereply));
1.691     raeburn  11632:     }
                   11633:     return $coursereply;
                   11634: }
                   11635: 
1.1301    raeburn  11636: sub get_map_hierarchy {
1.1302    raeburn  11637:     my ($mapname,$courseid) = @_;
                   11638:     my @recurseup = ();
1.1301    raeburn  11639:     if ($mapname) {
1.1302    raeburn  11640:         if (($cachedmapkey eq $courseid) &&
                   11641:             (abs($cachedmaptime-time)<5)) {
                   11642:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11643:                 return @{$cachedmaps{$mapname}};
                   11644:             }
                   11645:         }
1.1301    raeburn  11646:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11647:         if (ref($navmap)) {
                   11648:             @recurseup = $navmap->recurseup_maps($mapname);
                   11649:             undef($navmap);
1.1302    raeburn  11650:             $cachedmaps{$mapname} = \@recurseup;
                   11651:             $cachedmaptime=time;
                   11652:             $cachedmapkey=$courseid;
1.1301    raeburn  11653:         }
                   11654:     }
                   11655:     return @recurseup;
                   11656: }
                   11657: 
1.1302    raeburn  11658: }
                   11659: 
1.691     raeburn  11660: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11661:     my ($courseid,@groups) = @_;
                   11662:     @groups = sort(@groups);
1.691     raeburn  11663:     return @groups;
                   11664: }
                   11665: 
1.395     albertel 11666: sub packages_tab_default {
1.1362    raeburn  11667:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11668:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11669: 
                   11670:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11671:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11672: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11673: 	if ($pack_type eq 'default') {
                   11674: 	    $do_default=1;
                   11675: 	} elsif ($pack_type eq 'extension') {
                   11676: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11677: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11678: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11679: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11680: 	}
                   11681:     }
                   11682:     # first look for a package that matches the requested part id
                   11683:     foreach my $package (@specifics) {
                   11684: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11685: 	next if ($pack_part ne $part);
                   11686: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11687: 	    return $packagetab{"$pack_type&$name&default"};
                   11688: 	}
                   11689:     }
                   11690:     # look for any possible matching non extension_ package
                   11691:     foreach my $package (@specifics) {
                   11692: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11693: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11694: 	    return $packagetab{"$pack_type&$name&default"};
                   11695: 	}
1.585     albertel 11696: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11697: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11698: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11699: 	}
                   11700:     }
1.738     albertel 11701:     # look for any posible extension_ match
                   11702:     foreach my $package (@extension) {
                   11703: 	my ($package,$pack_type)=@{$package};
                   11704: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11705: 	    return $packagetab{"$pack_type&$name&default"};
                   11706: 	}
                   11707: 	if (defined($packagetab{$package."&$name&default"})) {
                   11708: 	    return $packagetab{$package."&$name&default"};
                   11709: 	}
                   11710:     }
                   11711:     # look for a global default setting
                   11712:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11713: 	return $packagetab{"default&$name&default"};
                   11714:     }
1.395     albertel 11715:     return undef;
                   11716: }
                   11717: 
1.334     albertel 11718: sub add_prefix_and_part {
                   11719:     my ($prefix,$part)=@_;
                   11720:     my $keyroot;
                   11721:     if (defined($prefix) && $prefix !~ /^__/) {
                   11722: 	# prefix that has a part already
                   11723: 	$keyroot=$prefix;
                   11724:     } elsif (defined($prefix)) {
                   11725: 	# prefix that is missing a part
                   11726: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11727:     } else {
                   11728: 	# no prefix at all
                   11729: 	if (defined($part)) { $keyroot='_'.$part; }
                   11730:     }
                   11731:     return $keyroot;
                   11732: }
                   11733: 
1.71      www      11734: # ---------------------------------------------------------------- Get metadata
                   11735: 
1.599     albertel 11736: my %metaentry;
1.1070    www      11737: my %importedpartids;
1.1369    raeburn  11738: my %importedrespids;
1.71      www      11739: sub metadata {
1.1362    raeburn  11740:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11741:     $uri=&declutter($uri);
1.288     albertel 11742:     # if it is a non metadata possible uri return quickly
1.529     albertel 11743:     if (($uri eq '') || 
                   11744: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11745: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11746:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11747: 	return undef;
                   11748:     }
1.1261    raeburn  11749:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11750: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11751: 	return undef;
1.288     albertel 11752:     }
1.73      www      11753:     my $filename=$uri;
                   11754:     $uri=~s/\.meta$//;
1.172     www      11755: #
                   11756: # Is the metadata already cached?
1.177     www      11757: # Look at timestamp of caching
1.172     www      11758: # Everything is cached by the main uri, libraries are never directly cached
                   11759: #
1.428     albertel 11760:     if (!defined($liburi)) {
1.599     albertel 11761: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11762: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11763:     }
1.1362    raeburn  11764: 
                   11765: #
                   11766: # If the uri is for an external tool the file from
                   11767: # which metadata should be retrieved depends on whether
                   11768: # the tool had been configured to be gradable (set in the Course
                   11769: # Editor or Resource Editor).
                   11770: #
                   11771: # If a valid symb has been included as the third arg in the call
                   11772: # to &metadata() that can be used to retrieve the value of
                   11773: # parameter_0_gradable set for the resource, and included in the
                   11774: # uploaded map containing the tool. The value is retrieved via
                   11775: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11776: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11777: # is retrieved via &get().
                   11778: #
                   11779: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11780: # hiddenresource and encrypturl (during course initialization)
                   11781: # the map-level parameter for resource.0.gradable included in the 
                   11782: # uploaded map containing the tool will not yet have been stored
                   11783: # in the user_course_parms.db file for the user's session, so in 
                   11784: # this case fall back to retrieving gradable status from the
                   11785: # exttool_$marker.db file.
1.1362    raeburn  11786: #
                   11787: # In order to avoid an infinite loop, &metadata() will return
                   11788: # before a call to &EXT(), if the uri is for an external tool
                   11789: # and the $what for which metadata is being requested is
                   11790: # parameter_0_gradable or 0_gradable.
                   11791: #
                   11792: 
                   11793:     if ($uri =~ /ext\.tool$/) {
                   11794:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11795:             return;
                   11796:         } else {
                   11797:             my ($checked,$use_passback);
                   11798:             if ($toolsymb ne '') {
                   11799:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11800:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11801:                     $checked = 1;
                   11802:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11803:                         $use_passback = 1;
                   11804:                     }
                   11805:                 }
                   11806:             }
                   11807:             unless ($checked) {
                   11808:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11809:                 $marker=~s/\D//g;
1.1363    raeburn  11810:                 if ($marker) {
1.1362    raeburn  11811:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11812:                     $use_passback = $toolsettings{'gradable'};
                   11813:                 }
                   11814:             }
                   11815:             if ($use_passback) {
                   11816:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11817:             } else {
                   11818:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11819:             }
                   11820:         }
                   11821:     }
                   11822: 
1.428     albertel 11823:     {
1.1069    www      11824: # Imported parts would go here
1.1369    raeburn  11825:         my @origfiletagids=();
1.1069    www      11826:         my $importedparts=0;
1.1369    raeburn  11827: 
                   11828: # Imported responseids would go here
                   11829:         my $importedresponses=0;
1.172     www      11830: #
                   11831: # Is this a recursive call for a library?
                   11832: #
1.599     albertel 11833: #	if (! exists($metacache{$uri})) {
                   11834: #	    $metacache{$uri}={};
                   11835: #	}
1.924     albertel 11836: 	my $cachetime = 60*60;
1.171     www      11837:         if ($liburi) {
                   11838: 	    $liburi=&declutter($liburi);
                   11839:             $filename=$liburi;
1.401     bowersj2 11840:         } else {
1.599     albertel 11841: 	    &devalidate_cache_new('meta',$uri);
                   11842: 	    undef(%metaentry);
1.401     bowersj2 11843: 	}
1.140     www      11844:         my %metathesekeys=();
1.73      www      11845:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11846: 	my $metastring;
1.1140    www      11847: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11848: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11849: 	    $metastring = 
1.929     albertel 11850: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11851: 					  ('grade_target' => 'meta'));
                   11852: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11853: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11854:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11855: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11856: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11857: 	    $metastring=&getfile($file);
1.489     albertel 11858: 	}
1.208     albertel 11859:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11860:         my $token;
1.140     www      11861:         undef %metathesekeys;
1.71      www      11862:         while ($token=$parser->get_token) {
1.339     albertel 11863: 	    if ($token->[0] eq 'S') {
                   11864: 		if (defined($token->[2]->{'package'})) {
1.172     www      11865: #
                   11866: # This is a package - get package info
                   11867: #
1.339     albertel 11868: 		    my $package=$token->[2]->{'package'};
                   11869: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11870: 		    if (defined($token->[2]->{'id'})) { 
                   11871: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11872: 		    }
1.599     albertel 11873: 		    if ($metaentry{':packages'}) {
                   11874: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11875: 		    } else {
1.599     albertel 11876: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11877: 		    }
1.736     albertel 11878: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11879: 			my $part=$keyroot;
                   11880: 			$part=~s/^\_//;
1.736     albertel 11881: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11882: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11883: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11884: 			    # ignore package.tab specified default values
                   11885:                             # here &package_tab_default() will fetch those
                   11886: 			    if ($subp eq 'default') { next; }
1.736     albertel 11887: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11888: 			    my $unikey;
                   11889: 			    if ($pack =~ /_0$/) {
                   11890: 				$unikey='parameter_0_'.$name;
                   11891: 				$part=0;
                   11892: 			    } else {
                   11893: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11894: 			    }
1.339     albertel 11895: 			    if ($subp eq 'display') {
                   11896: 				$value.=' [Part: '.$part.']';
                   11897: 			    }
1.599     albertel 11898: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11899: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11900: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11901: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11902: 			    }
1.599     albertel 11903: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11904: 				$metaentry{':'.$unikey}=
                   11905: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11906: 			    }
1.339     albertel 11907: 			}
                   11908: 		    }
                   11909: 		} else {
1.172     www      11910: #
                   11911: # This is not a package - some other kind of start tag
1.339     albertel 11912: #
                   11913: 		    my $entry=$token->[1];
1.1068    www      11914: 		    my $unikey='';
1.175     www      11915: 
1.339     albertel 11916: 		    if ($entry eq 'import') {
1.175     www      11917: #
                   11918: # Importing a library here
1.339     albertel 11919: #
1.1067    www      11920:                         my $location=$parser->get_text('/import');
                   11921:                         my $dir=$filename;
                   11922:                         $dir=~s|[^/]*$||;
                   11923:                         $location=&filelocation($dir,$location);
1.1369    raeburn  11924: 
                   11925:                         my $importid=$token->[2]->{'id'};
1.1068    www      11926:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  11927: #
                   11928: # Check metadata for imported file to
                   11929: # see if it contained response items
                   11930: #
1.1372  ! raeburn  11931:                         my ($origfile,@libfilekeys);
1.1370    raeburn  11932:                         my %currmetaentry = %metaentry;
1.1372  ! raeburn  11933:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
        !          11934:                                                            $depthcount+1));
        !          11935:                         if (grep(/^responseorder$/,@libfilekeys)) {
        !          11936:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
        !          11937:                                                              undef,$depthcount+1);
        !          11938:                             if ($libresponseorder ne '') {
        !          11939:                                 if ($#origfiletagids<0) {
        !          11940:                                     undef(%importedrespids);
        !          11941:                                     undef(%importedpartids);
        !          11942:                                 }
        !          11943:                                 @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
        !          11944:                                 if (@{$importedrespids{$importid}} > 0) {
        !          11945:                                     $importedresponses = 1;
1.1369    raeburn  11946: # We need to get the original file and the imported file to get the response order correct
                   11947: # Load and inspect original file
1.1372  ! raeburn  11948:                                     if ($#origfiletagids<0) {
        !          11949:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
        !          11950:                                         $origfile=&getfile($origfilelocation);
        !          11951:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
        !          11952:                                     }
1.1369    raeburn  11953:                                 }
                   11954:                             }
                   11955:                         }
1.1370    raeburn  11956: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11957: # hash populated for imported library file
                   11958:                         %metaentry = %currmetaentry;
                   11959:                         undef(%currmetaentry);
1.1068    www      11960:                         if ($importmode eq 'problem') {
1.1069    www      11961: # Import as problem/response
1.1068    www      11962:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11963:                         } elsif ($importmode eq 'part') {
                   11964: # Import as part(s)
1.1069    www      11965:                            $importedparts=1;
                   11966: # We need to get the original file and the imported file to get the part order correct
                   11967: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  11968: # Load and inspect original file if we didn't do that already
                   11969:                            if ($#origfiletagids<0) {
                   11970:                                undef(%importedrespids);
                   11971:                                undef(%importedpartids);
                   11972:                                if ($origfile eq '') {
                   11973:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11974:                                    $origfile=&getfile($origfilelocation);
                   11975:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11976:                                }
1.1070    www      11977:                            }
1.1372  ! raeburn  11978:                            my @impfilepartids;
        !          11979: # If <partorder> tag is included in metadata for the imported file
        !          11980: # get the parts in the imported file from that.
        !          11981:                            if (grep(/^partorder$/,@libfilekeys)) {
        !          11982:                                %currmetaentry = %metaentry;
        !          11983:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
        !          11984:                                                             $depthcount+1);
        !          11985:                                %metaentry = %currmetaentry;
        !          11986:                                undef(%currmetaentry);
        !          11987:                                if ($libpartorder ne '') {
        !          11988:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
        !          11989:                                }
        !          11990:                            } else {
        !          11991: # If no <partorder> tag available, load and inspect imported file
        !          11992:                                my $impfile=&getfile($location);
        !          11993:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
        !          11994:                            }
1.1069    www      11995:                            if ($#impfilepartids>=0) {
                   11996: # This problem had parts
1.1070    www      11997:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11998:                            } else {
                   11999: # Importing by turning a single problem into a problem part
                   12000: # It gets the import-tags ID as part-ID
                   12001:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12002:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12003:                            }
1.1068    www      12004:                         } else {
                   12005: # Normal import
                   12006:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12007:                            if (defined($token->[2]->{'id'})) {
                   12008:                               $unikey.='_'.$token->[2]->{'id'};
                   12009:                            }
1.1067    www      12010:                         }
                   12011: 
1.339     albertel 12012: 			if ($depthcount<20) {
1.736     albertel 12013: 			    my $metadata = 
1.1362    raeburn  12014: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12015: 					  $depthcount+1);
                   12016: 			    foreach my $meta (split(',',$metadata)) {
                   12017: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12018: 				$metathesekeys{$meta}=1;
1.339     albertel 12019: 			    }
1.1068    www      12020:                         }
1.1067    www      12021: 		    } else {
                   12022: #
                   12023: # Not importing, some other kind of non-package, non-library start tag
                   12024: # 
                   12025:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12026:                         if (defined($token->[2]->{'id'})) {
                   12027:                             $unikey.='_'.$token->[2]->{'id'};
                   12028:                         }
1.339     albertel 12029: 			if (defined($token->[2]->{'name'})) { 
                   12030: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12031: 			}
                   12032: 			$metathesekeys{$unikey}=1;
1.736     albertel 12033: 			foreach my $param (@{$token->[3]}) {
                   12034: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12035: 				$token->[2]->{$param};
1.339     albertel 12036: 			}
                   12037: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12038: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12039: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12040: 		 # only ws inside the tag, and not in default, so use default
                   12041: 		 # as value
1.599     albertel 12042: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12043: 			} elsif ( $internaltext =~ /\S/ ) {
                   12044: 		  # something interesting inside the tag
                   12045: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12046: 			} else {
1.908     albertel 12047: 		  # no interesting values, don't set a default
1.339     albertel 12048: 			}
1.172     www      12049: # end of not-a-package not-a-library import
1.339     albertel 12050: 		    }
1.172     www      12051: # end of not-a-package start tag
1.339     albertel 12052: 		}
1.172     www      12053: # the next is the end of "start tag"
1.339     albertel 12054: 	    }
                   12055: 	}
1.483     albertel 12056: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12057: 	$extension = lc($extension);
                   12058: 	if ($extension eq 'htm') { $extension='html'; }
                   12059: 
1.737     albertel 12060: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12061: 	    #no specific packages #how's our extension
                   12062: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12063: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12064: 					 \%metathesekeys);
                   12065: 	}
1.883     albertel 12066: 
                   12067: 	if (!exists($metaentry{':packages'})
                   12068: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12069: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12070: 		#no specific packages well let's get default then
                   12071: 		if ($key!~/^default&/) { next; }
1.488     albertel 12072: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12073: 					     \%metathesekeys);
                   12074: 	    }
                   12075: 	}
1.338     www      12076: # are there custom rights to evaluate
1.599     albertel 12077: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12078: 
1.338     www      12079:     #
                   12080:     # Importing a rights file here
1.339     albertel 12081:     #
                   12082: 	    unless ($depthcount) {
1.599     albertel 12083: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12084: 		my $dir=$filename;
                   12085: 		$dir=~s|[^/]*$||;
                   12086: 		$location=&filelocation($dir,$location);
1.736     albertel 12087: 		my $rights_metadata =
1.1362    raeburn  12088: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12089: 			      $depthcount+1);
                   12090: 		foreach my $rights (split(',',$rights_metadata)) {
                   12091: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12092: 		    $metathesekeys{$rights}=1;
1.339     albertel 12093: 		}
                   12094: 	    }
                   12095: 	}
1.737     albertel 12096: 	# uniqifiy package listing
                   12097: 	my %seen;
                   12098: 	my @uniq_packages =
                   12099: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12100: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12101: 
1.1369    raeburn  12102:         if (($importedresponses) || ($importedparts)) {
                   12103:             if ($importedparts) {
1.1070    www      12104: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12105:                 $metaentry{':partorder'}='';
                   12106:                 $metathesekeys{'partorder'}=1;
                   12107:             }
                   12108:             if ($importedresponses) {
                   12109: # We had imported responses and need to rebuil responseorder
                   12110:                 $metaentry{':responseorder'}='';
                   12111:                 $metathesekeys{'responseorder'}=1;
                   12112:             }
                   12113:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12114:                 my $origid = $origfiletagids[$index+1];
                   12115:                 if ($origfiletagids[$index] eq 'part') {
                   12116: # Original part, part of the problem
                   12117:                     if ($importedparts) {
                   12118:                         $metaentry{':partorder'}.=','.$origid;
                   12119:                     }
                   12120:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12121:                     if ($importedparts) {
                   12122: # We have imported parts at this position
                   12123:                         $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12124:                     }
                   12125:                     if ($importedresponses) {
                   12126: # We have imported responses at this position
                   12127:                         if (ref($importedrespids{$origid}) eq 'ARRAY') {
                   12128:                             $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
                   12129:                         }
                   12130:                     }
                   12131:                 } else {
                   12132: # Original response item, part of the problem
                   12133:                     if ($importedresponses) {
                   12134:                         $metaentry{':responseorder'}.=','.$origid;
                   12135:                     }
                   12136:                 }
                   12137:             }
                   12138:             if ($importedparts) {
                   12139:                 $metaentry{':partorder'}=~s/^\,//;
                   12140:             }
                   12141:             if ($importedresponses) {
                   12142:                 $metaentry{':responseorder'}=~s/^\,//;
                   12143:             }
1.1070    www      12144:         }
1.737     albertel 12145: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12146: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12147: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12148:         unless ($liburi) {
                   12149: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12150:         }
1.177     www      12151: # this is the end of "was not already recently cached
1.71      www      12152:     }
1.599     albertel 12153:     return $metaentry{':'.$what};
1.261     albertel 12154: }
                   12155: 
1.488     albertel 12156: sub metadata_create_package_def {
1.483     albertel 12157:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12158:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12159:     if ($subp eq 'default') { next; }
                   12160:     
1.599     albertel 12161:     if (defined($metaentry{':packages'})) {
                   12162: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12163:     } else {
1.599     albertel 12164: 	$metaentry{':packages'}=$package;
1.483     albertel 12165:     }
                   12166:     my $value=$packagetab{$key};
                   12167:     my $unikey;
                   12168:     $unikey='parameter_0_'.$name;
1.599     albertel 12169:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12170:     $$metathesekeys{$unikey}=1;
1.599     albertel 12171:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12172: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12173:     }
1.599     albertel 12174:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12175: 	$metaentry{':'.$unikey}=
                   12176: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12177:     }
                   12178: }
                   12179: 
1.261     albertel 12180: sub metadata_generate_part0 {
                   12181:     my ($metadata,$metacache,$uri) = @_;
                   12182:     my %allnames;
1.737     albertel 12183:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12184: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12185: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12186: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12187: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12188: 	    $allnames{$name}=$part;
                   12189: 	  }
                   12190: 	}
                   12191:     }
                   12192:     foreach my $name (keys(%allnames)) {
                   12193:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12194:       my $key=":parameter_0_$name";
1.261     albertel 12195:       $$metacache{"$key.part"}='0';
                   12196:       $$metacache{"$key.name"}=$name;
1.428     albertel 12197:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12198: 					   $allnames{$name}.'_'.$name.
                   12199: 					   '.type'};
1.428     albertel 12200:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12201: 			     '.display'};
1.644     www      12202:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12203:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12204:       $$metacache{"$key.display"}=$olddis;
                   12205:     }
1.71      www      12206: }
                   12207: 
1.764     albertel 12208: # ------------------------------------------------------ Devalidate title cache
                   12209: 
                   12210: sub devalidate_title_cache {
                   12211:     my ($url)=@_;
                   12212:     if (!$env{'request.course.id'}) { return; }
                   12213:     my $symb=&symbread($url);
                   12214:     if (!$symb) { return; }
                   12215:     my $key=$env{'request.course.id'}."\0".$symb;
                   12216:     &devalidate_cache_new('title',$key);
                   12217: }
                   12218: 
1.1014    droeschl 12219: # ------------------------------------------------- Get the title of a course
                   12220: 
                   12221: sub current_course_title {
                   12222:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12223: }
1.301     www      12224: # ------------------------------------------------- Get the title of a resource
                   12225: 
                   12226: sub gettitle {
                   12227:     my $urlsymb=shift;
                   12228:     my $symb=&symbread($urlsymb);
1.534     albertel 12229:     if ($symb) {
1.620     albertel 12230: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12231: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12232: 	if (defined($cached)) { 
                   12233: 	    return $result;
                   12234: 	}
1.534     albertel 12235: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12236: 	my $title='';
1.907     albertel 12237: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12238: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12239: 	} else {
                   12240: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12241: 		    &GDBM_READER(),0640)) {
                   12242: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12243: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12244: 		untie(%bighash);
                   12245: 	    }
1.534     albertel 12246: 	}
                   12247: 	$title=~s/\&colon\;/\:/gs;
                   12248: 	if ($title) {
1.1159    www      12249: # Remember both $symb and $title for dynamic metadata
                   12250:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12251:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12252: # Cache this title and then return it
1.599     albertel 12253: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12254: 	}
                   12255: 	$urlsymb=$url;
                   12256:     }
                   12257:     my $title=&metadata($urlsymb,'title');
                   12258:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12259:     return $title;
1.301     www      12260: }
1.613     albertel 12261: 
1.614     albertel 12262: sub get_slot {
                   12263:     my ($which,$cnum,$cdom)=@_;
                   12264:     if (!$cnum || !$cdom) {
1.790     albertel 12265: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12266: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12267: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12268:     }
1.703     albertel 12269:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12270:     my %slotinfo;
                   12271:     if (exists($remembered{$key})) {
                   12272: 	$slotinfo{$which} = $remembered{$key};
                   12273:     } else {
                   12274: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12275: 	&Apache::lonhomework::showhash(%slotinfo);
                   12276: 	my ($tmp)=keys(%slotinfo);
                   12277: 	if ($tmp=~/^error:/) { return (); }
                   12278: 	$remembered{$key} = $slotinfo{$which};
                   12279:     }
1.616     albertel 12280:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12281: 	return %{$slotinfo{$which}};
                   12282:     }
                   12283:     return $slotinfo{$which};
1.614     albertel 12284: }
1.1150    raeburn  12285: 
                   12286: sub get_reservable_slots {
                   12287:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12288:     my $now = time;
                   12289:     my $reservable_info;
                   12290:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12291:     if (exists($remembered{$key})) {
                   12292:         $reservable_info = $remembered{$key};
                   12293:     } else {
                   12294:         my %resv;
                   12295:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12296:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12297:         $reservable_info = \%resv;
                   12298:         $remembered{$key} = $reservable_info;
                   12299:     }
                   12300:     return $reservable_info;
                   12301: }
                   12302: 
                   12303: sub get_course_slots {
                   12304:     my ($cnum,$cdom) = @_;
                   12305:     my $hashid=$cnum.':'.$cdom;
                   12306:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12307:     if (defined($cached)) {
                   12308:         if (ref($result) eq 'HASH') {
                   12309:             return %{$result};
                   12310:         }
                   12311:     } else {
                   12312:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12313:         my ($tmp) = keys(%slots);
                   12314:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12315:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12316:             return %slots;
                   12317:         }
                   12318:     }
                   12319:     return;
                   12320: }
                   12321: 
                   12322: sub devalidate_slots_cache {
                   12323:     my ($cnum,$cdom)=@_;
                   12324:     my $hashid=$cnum.':'.$cdom;
                   12325:     &devalidate_cache_new('allslots',$hashid);
                   12326: }
                   12327: 
1.1181    raeburn  12328: sub get_coursechange {
                   12329:     my ($cdom,$cnum) = @_;
                   12330:     if ($cdom eq '' || $cnum eq '') {
                   12331:         return unless ($env{'request.course.id'});
                   12332:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12333:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12334:     }
                   12335:     my $hashid=$cdom.'_'.$cnum;
                   12336:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12337:     if ((defined($cached)) && ($change ne '')) {
                   12338:         return $change;
                   12339:     } else {
                   12340:         my %crshash;
                   12341:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12342:         if ($crshash{'internal.contentchange'} eq '') {
                   12343:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12344:             if ($change eq '') {
                   12345:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12346:                 $change = $crshash{'internal.created'};
                   12347:             }
                   12348:         } else {
                   12349:             $change = $crshash{'internal.contentchange'};
                   12350:         }
                   12351:         my $cachetime = 600;
                   12352:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12353:     }
                   12354:     return $change;
                   12355: }
                   12356: 
                   12357: sub devalidate_coursechange_cache {
                   12358:     my ($cnum,$cdom)=@_;
                   12359:     my $hashid=$cnum.':'.$cdom;
                   12360:     &devalidate_cache_new('crschange',$hashid);
                   12361: }
                   12362: 
1.31      www      12363: # ------------------------------------------------- Update symbolic store links
                   12364: 
                   12365: sub symblist {
                   12366:     my ($mapname,%newhash)=@_;
1.438     www      12367:     $mapname=&deversion(&declutter($mapname));
1.31      www      12368:     my %hash;
1.620     albertel 12369:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12370:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12371:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12372: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12373: 		next if ($url eq 'last_known'
                   12374: 			 && $env{'form.no_update_last_known'});
                   12375: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12376: 						    $newhash{$url}->[1],
                   12377: 						    $newhash{$url}->[0]);
1.191     harris41 12378:             }
1.31      www      12379:             if (untie(%hash)) {
                   12380: 		return 'ok';
                   12381:             }
                   12382:         }
                   12383:     }
                   12384:     return 'error';
1.212     www      12385: }
                   12386: 
                   12387: # --------------------------------------------------------------- Verify a symb
                   12388: 
                   12389: sub symbverify {
1.1190    raeburn  12390:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12391:     my $thisfn=$thisurl;
1.439     www      12392:     $thisfn=&declutter($thisfn);
1.215     www      12393: # direct jump to resource in page or to a sequence - will construct own symbs
                   12394:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12395: # check URL part
1.409     www      12396:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12397: 
1.431     www      12398:     unless ($url eq $thisfn) { return 0; }
1.213     www      12399: 
1.216     www      12400:     $symb=&symbclean($symb);
1.510     www      12401:     $thisurl=&deversion($thisurl);
1.439     www      12402:     $thisfn=&deversion($thisfn);
1.213     www      12403: 
                   12404:     my %bighash;
                   12405:     my $okay=0;
1.431     www      12406: 
1.620     albertel 12407:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12408:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12409:         my $noclutter;
1.1032    raeburn  12410:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12411:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12412:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12413:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12414:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12415:                 $noclutter = 1;
                   12416:             }
                   12417:         }
                   12418:         my $ids;
                   12419:         if ($noclutter) {
                   12420:             $ids=$bighash{'ids_'.$thisurl};
                   12421:         } else {
                   12422:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12423:         }
1.1102    raeburn  12424:         unless ($ids) {
                   12425:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12426:             $ids=$bighash{$idkey};
1.216     www      12427:         }
                   12428:         if ($ids) {
                   12429: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12430:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12431:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12432:             }
1.800     albertel 12433: 	    foreach my $id (split(/\,/,$ids)) {
                   12434: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12435:                if (
                   12436:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12437:    eq $symb) {
                   12438:                    if (ref($encstate)) {
                   12439:                        $$encstate = $bighash{'encrypted_'.$id};
                   12440:                    }
1.620     albertel 12441: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12442: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12443:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12444: 		       $okay=1;
1.1202    raeburn  12445:                        last;
1.582     albertel 12446: 		   }
                   12447: 	       }
1.216     www      12448: 	   }
                   12449:         }
1.213     www      12450: 	untie(%bighash);
                   12451:     }
                   12452:     return $okay;
1.31      www      12453: }
                   12454: 
1.210     www      12455: # --------------------------------------------------------------- Clean-up symb
                   12456: 
                   12457: sub symbclean {
                   12458:     my $symb=shift;
1.568     albertel 12459:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12460: # remove version from map
                   12461:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12462: 
1.210     www      12463: # remove version from URL
                   12464:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12465: 
1.507     www      12466: # remove wrapper
                   12467: 
1.510     www      12468:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12469:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12470:     return $symb;
1.409     www      12471: }
                   12472: 
                   12473: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12474: 
                   12475: sub encode_symb {
                   12476:     my ($map,$resid,$url)=@_;
                   12477:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12478: }
1.409     www      12479: 
                   12480: sub decode_symb {
1.568     albertel 12481:     my $symb=shift;
                   12482:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12483:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12484:     return (&fixversion($map),$resid,&fixversion($url));
                   12485: }
                   12486: 
                   12487: sub fixversion {
                   12488:     my $fn=shift;
1.609     banghart 12489:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12490:     my %bighash;
                   12491:     my $uri=&clutter($fn);
1.620     albertel 12492:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12493: # is this cached?
1.599     albertel 12494:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12495:     if (defined($cached)) { return $result; }
                   12496: # unfortunately not cached, or expired
1.620     albertel 12497:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12498: 	    &GDBM_READER(),0640)) {
                   12499:  	if ($bighash{'version_'.$uri}) {
                   12500:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12501:  	    unless (($version eq 'mostrecent') || 
                   12502: 		    ($version==&getversion($uri))) {
1.440     www      12503:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12504:  	    }
                   12505:  	}
                   12506:  	untie %bighash;
1.413     www      12507:     }
1.599     albertel 12508:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12509: }
                   12510: 
                   12511: sub deversion {
                   12512:     my $url=shift;
                   12513:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12514:     return $url;
1.210     www      12515: }
                   12516: 
1.31      www      12517: # ------------------------------------------------------ Return symb list entry
                   12518: 
                   12519: sub symbread {
1.1282    raeburn  12520:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12521:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12522:     if (defined($env{$cache_str})) {
                   12523:         if ($ignorecachednull) {
                   12524:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12525:         } else {
                   12526:             return $env{$cache_str};
                   12527:         }
                   12528:     }
1.242     www      12529: # no filename provided? try from environment
1.1265    raeburn  12530:     unless ($thisfn) {
1.620     albertel 12531:         if ($env{'request.symb'}) {
                   12532: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12533: 	}
1.620     albertel 12534: 	$thisfn=$env{'request.filename'};
1.44      www      12535:     }
1.569     albertel 12536:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12537: # is that filename actually a symb? Verify, clean, and return
                   12538:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12539: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12540: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12541: 	}
1.242     www      12542:     }
1.44      www      12543:     $thisfn=declutter($thisfn);
1.31      www      12544:     my %hash;
1.37      www      12545:     my %bighash;
                   12546:     my $syval='';
1.620     albertel 12547:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12548:         my $targetfn = $thisfn;
1.609     banghart 12549:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12550:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12551:         }
1.687     albertel 12552: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12553: 	    $targetfn=$1;
                   12554: 	}
1.620     albertel 12555:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12556:                       &GDBM_READER(),0640)) {
1.481     raeburn  12557: 	    $syval=$hash{$targetfn};
1.37      www      12558:             untie(%hash);
                   12559:         }
                   12560: # ---------------------------------------------------------- There was an entry
                   12561:         if ($syval) {
1.601     albertel 12562: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12563: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12564: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12565: 		    #return $env{$cache_str}='';
1.601     albertel 12566: 		#}    
                   12567: 		#$syval.=$1;
                   12568: 	    #}
1.37      www      12569:         } else {
                   12570: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12571:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12572:                             &GDBM_READER(),0640)) {
1.37      www      12573: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12574:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12575:               unless ($ids) { 
                   12576:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12577:               }
                   12578:               unless ($ids) {
                   12579: # alias?
                   12580: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12581:               }
1.37      www      12582:               if ($ids) {
                   12583: # ------------------------------------------------------------------- Has ID(s)
                   12584:                  my @possibilities=split(/\,/,$ids);
1.39      www      12585:                  if ($#possibilities==0) {
                   12586: # ----------------------------------------------- There is only one possibility
1.37      www      12587: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12588: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12589: 						    $resid,$thisfn);
1.1282    raeburn  12590:                      if (ref($possibles) eq 'HASH') {
                   12591:                          $possibles->{$syval} = 1;    
                   12592:                      }
                   12593:                      if ($checkforblock) {
                   12594:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12595:                          if (@blockers) {
                   12596:                              $syval = '';
                   12597:                              return;
                   12598:                          }
                   12599:                      }
                   12600:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12601: # ------------------------------------------ There is more than one possibility
                   12602:                      my $realpossible=0;
1.800     albertel 12603:                      foreach my $id (@possibilities) {
                   12604: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12605:                          my $canaccess;
                   12606:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12607:                              $canaccess = 1;
                   12608:                          } else { 
                   12609:                              $canaccess = &allowed('bre',$file);
                   12610:                          }
                   12611:                          if ($canaccess) {
                   12612:          		     my ($mapid,$resid)=split(/\./,$id);
                   12613:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12614:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12615: 						             $resid,$thisfn);
                   12616:                                  if (ref($possibles) eq 'HASH') {
                   12617:                                      $possibles->{$syval} = 1;
                   12618:                                  }
                   12619:                                  if ($checkforblock) {
                   12620:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12621:                                      unless (@blockers > 0) {
                   12622:                                          $syval = $poss_syval;
                   12623:                                          $realpossible++;
                   12624:                                      }
                   12625:                                  } else {
                   12626:                                      $syval = $poss_syval;
                   12627:                                      $realpossible++;
                   12628:                                  }
                   12629:                              }
1.39      www      12630: 			 }
1.191     harris41 12631:                      }
1.39      www      12632: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12633:                  } else {
                   12634:                      $syval='';
1.37      www      12635:                  }
                   12636: 	      }
1.1282    raeburn  12637:               untie(%bighash);
1.481     raeburn  12638:            }
1.31      www      12639:         }
1.62      www      12640:         if ($syval) {
1.620     albertel 12641: 	    return $env{$cache_str}=$syval;
1.62      www      12642:         }
1.31      www      12643:     }
1.949     raeburn  12644:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12645:     return $env{$cache_str}='';
1.31      www      12646: }
                   12647: 
                   12648: # ---------------------------------------------------------- Return random seed
                   12649: 
1.32      www      12650: sub numval {
                   12651:     my $txt=shift;
                   12652:     $txt=~tr/A-J/0-9/;
                   12653:     $txt=~tr/a-j/0-9/;
                   12654:     $txt=~tr/K-T/0-9/;
                   12655:     $txt=~tr/k-t/0-9/;
                   12656:     $txt=~tr/U-Z/0-5/;
                   12657:     $txt=~tr/u-z/0-5/;
                   12658:     $txt=~s/\D//g;
1.564     albertel 12659:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12660:     return int($txt);
1.368     albertel 12661: }
                   12662: 
1.484     albertel 12663: sub numval2 {
                   12664:     my $txt=shift;
                   12665:     $txt=~tr/A-J/0-9/;
                   12666:     $txt=~tr/a-j/0-9/;
                   12667:     $txt=~tr/K-T/0-9/;
                   12668:     $txt=~tr/k-t/0-9/;
                   12669:     $txt=~tr/U-Z/0-5/;
                   12670:     $txt=~tr/u-z/0-5/;
                   12671:     $txt=~s/\D//g;
                   12672:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12673:     my $total;
                   12674:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12675:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12676:     return int($total);
                   12677: }
                   12678: 
1.575     albertel 12679: sub numval3 {
                   12680:     use integer;
                   12681:     my $txt=shift;
                   12682:     $txt=~tr/A-J/0-9/;
                   12683:     $txt=~tr/a-j/0-9/;
                   12684:     $txt=~tr/K-T/0-9/;
                   12685:     $txt=~tr/k-t/0-9/;
                   12686:     $txt=~tr/U-Z/0-5/;
                   12687:     $txt=~tr/u-z/0-5/;
                   12688:     $txt=~s/\D//g;
                   12689:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12690:     my $total;
                   12691:     foreach my $val (@txts) { $total+=$val; }
                   12692:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12693:     return $total;
                   12694: }
                   12695: 
1.675     albertel 12696: sub digest {
                   12697:     my ($data)=@_;
                   12698:     my $digest=&Digest::MD5::md5($data);
                   12699:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12700:     my ($e,$f);
                   12701:     {
                   12702:         use integer;
                   12703:         $e=($a+$b);
                   12704:         $f=($c+$d);
                   12705:         if ($_64bit) {
                   12706:             $e=(($e<<32)>>32);
                   12707:             $f=(($f<<32)>>32);
                   12708:         }
                   12709:     }
                   12710:     if (wantarray) {
                   12711: 	return ($e,$f);
                   12712:     } else {
                   12713: 	my $g;
                   12714: 	{
                   12715: 	    use integer;
                   12716: 	    $g=($e+$f);
                   12717: 	    if ($_64bit) {
                   12718: 		$g=(($g<<32)>>32);
                   12719: 	    }
                   12720: 	}
                   12721: 	return $g;
                   12722:     }
                   12723: }
                   12724: 
1.368     albertel 12725: sub latest_rnd_algorithm_id {
1.675     albertel 12726:     return '64bit5';
1.366     albertel 12727: }
1.32      www      12728: 
1.503     albertel 12729: sub get_rand_alg {
                   12730:     my ($courseid)=@_;
1.790     albertel 12731:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12732:     if ($courseid) {
1.620     albertel 12733: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12734:     }
                   12735:     return &latest_rnd_algorithm_id();
                   12736: }
                   12737: 
1.562     albertel 12738: sub validCODE {
                   12739:     my ($CODE)=@_;
                   12740:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12741:     return 0;
                   12742: }
                   12743: 
1.491     albertel 12744: sub getCODE {
1.620     albertel 12745:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12746:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12747: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12748: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12749: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12750:     }
                   12751:     return undef;
                   12752: }
1.1133    foxr     12753: #
                   12754: #  Determines the random seed for a specific context:
                   12755: #
                   12756: # parameters:
                   12757: #   symb      - in course context the symb for the seed.
                   12758: #   course_id - The course id of the form domain_coursenum.
                   12759: #   domain    - Domain for the user.
                   12760: #   course    - Course for the user.
                   12761: #   cenv      - environment of the course.
                   12762: #
                   12763: # NOTE:
                   12764: #   All parameters are picked out of the environment if missing
                   12765: #   or not defined.
                   12766: #   If a symb cannot be determined the current time is used instead.
                   12767: #
                   12768: #  For a given well defined symb, courside, domain, username,
                   12769: #  and course environment, the seed is reproducible.
                   12770: #
1.31      www      12771: sub rndseed {
1.1133    foxr     12772:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12773:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12774:     if (!defined($symb)) {
1.366     albertel 12775: 	unless ($symb=$wsymb) { return time; }
                   12776:     }
1.1146    foxr     12777:     if (!defined $courseid) { 
                   12778: 	$courseid=$wcourseid; 
                   12779:     }
                   12780:     if (!defined $domain) { $domain=$wdomain; }
                   12781:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12782: 
                   12783:     my $which;
                   12784:     if (defined($cenv->{'rndseed'})) {
                   12785: 	$which = $cenv->{'rndseed'};
                   12786:     } else {
                   12787: 	$which =&get_rand_alg($courseid);
                   12788:     }
1.491     albertel 12789:     if (defined(&getCODE())) {
1.1133    foxr     12790: 
1.675     albertel 12791: 	if ($which eq '64bit5') {
                   12792: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12793: 	} elsif ($which eq '64bit4') {
1.575     albertel 12794: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12795: 	} else {
                   12796: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12797: 	}
1.675     albertel 12798:     } elsif ($which eq '64bit5') {
                   12799: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12800:     } elsif ($which eq '64bit4') {
                   12801: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12802:     } elsif ($which eq '64bit3') {
                   12803: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12804:     } elsif ($which eq '64bit2') {
                   12805: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12806:     } elsif ($which eq '64bit') {
                   12807: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12808:     }
                   12809:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12810: }
                   12811: 
                   12812: sub rndseed_32bit {
                   12813:     my ($symb,$courseid,$domain,$username)=@_;
                   12814:     {
                   12815: 	use integer;
                   12816: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12817: 	my $symbseed=numval($symb) << 22;
                   12818: 	my $namechck=unpack("%32C*",$username) << 17;
                   12819: 	my $nameseed=numval($username) << 12;
                   12820: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12821: 	my $courseseed=unpack("%32C*",$courseid);
                   12822: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12823: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12824: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12825: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12826: 	return $num;
                   12827:     }
                   12828: }
                   12829: 
                   12830: sub rndseed_64bit {
                   12831:     my ($symb,$courseid,$domain,$username)=@_;
                   12832:     {
                   12833: 	use integer;
                   12834: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12835: 	my $symbseed=numval($symb) << 10;
                   12836: 	my $namechck=unpack("%32S*",$username);
                   12837: 	
                   12838: 	my $nameseed=numval($username) << 21;
                   12839: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12840: 	my $courseseed=unpack("%32S*",$courseid);
                   12841: 	
                   12842: 	my $num1=$symbchck+$symbseed+$namechck;
                   12843: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12844: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12845: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12846: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12847: 	return "$num1,$num2";
1.155     albertel 12848:     }
1.366     albertel 12849: }
                   12850: 
1.443     albertel 12851: sub rndseed_64bit2 {
                   12852:     my ($symb,$courseid,$domain,$username)=@_;
                   12853:     {
                   12854: 	use integer;
                   12855: 	# strings need to be an even # of cahracters long, it it is odd the
                   12856:         # last characters gets thrown away
                   12857: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12858: 	my $symbseed=numval($symb) << 10;
                   12859: 	my $namechck=unpack("%32S*",$username.' ');
                   12860: 	
                   12861: 	my $nameseed=numval($username) << 21;
1.501     albertel 12862: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12863: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12864: 	
                   12865: 	my $num1=$symbchck+$symbseed+$namechck;
                   12866: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12867: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12868: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12869: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12870: 	return "$num1,$num2";
                   12871:     }
                   12872: }
                   12873: 
                   12874: sub rndseed_64bit3 {
                   12875:     my ($symb,$courseid,$domain,$username)=@_;
                   12876:     {
                   12877: 	use integer;
                   12878: 	# strings need to be an even # of cahracters long, it it is odd the
                   12879:         # last characters gets thrown away
                   12880: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12881: 	my $symbseed=numval2($symb) << 10;
                   12882: 	my $namechck=unpack("%32S*",$username.' ');
                   12883: 	
                   12884: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12885: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12886: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12887: 	
                   12888: 	my $num1=$symbchck+$symbseed+$namechck;
                   12889: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12890: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12891: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12892: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12893: 	
1.503     albertel 12894: 	return "$num1:$num2";
1.443     albertel 12895:     }
                   12896: }
                   12897: 
1.575     albertel 12898: sub rndseed_64bit4 {
                   12899:     my ($symb,$courseid,$domain,$username)=@_;
                   12900:     {
                   12901: 	use integer;
                   12902: 	# strings need to be an even # of cahracters long, it it is odd the
                   12903:         # last characters gets thrown away
                   12904: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12905: 	my $symbseed=numval3($symb) << 10;
                   12906: 	my $namechck=unpack("%32S*",$username.' ');
                   12907: 	
                   12908: 	my $nameseed=numval3($username) << 21;
                   12909: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12910: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12911: 	
                   12912: 	my $num1=$symbchck+$symbseed+$namechck;
                   12913: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12914: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12915: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12916: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12917: 	
1.575     albertel 12918: 	return "$num1:$num2";
                   12919:     }
                   12920: }
                   12921: 
1.675     albertel 12922: sub rndseed_64bit5 {
                   12923:     my ($symb,$courseid,$domain,$username)=@_;
                   12924:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12925:     return "$num1:$num2";
                   12926: }
                   12927: 
1.366     albertel 12928: sub rndseed_CODE_64bit {
                   12929:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12930:     {
1.366     albertel 12931: 	use integer;
1.443     albertel 12932: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12933: 	my $symbseed=numval2($symb);
1.491     albertel 12934: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12935: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12936: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12937: 	my $num1=$symbseed+$CODEchck;
                   12938: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12939: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12940: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12941: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12942: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12943: 	return "$num1:$num2";
1.366     albertel 12944:     }
                   12945: }
                   12946: 
1.575     albertel 12947: sub rndseed_CODE_64bit4 {
                   12948:     my ($symb,$courseid,$domain,$username)=@_;
                   12949:     {
                   12950: 	use integer;
                   12951: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12952: 	my $symbseed=numval3($symb);
                   12953: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12954: 	my $CODEseed=numval3(&getCODE());
                   12955: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12956: 	my $num1=$symbseed+$CODEchck;
                   12957: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12958: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12959: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12960: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12961: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12962: 	return "$num1:$num2";
                   12963:     }
                   12964: }
                   12965: 
1.675     albertel 12966: sub rndseed_CODE_64bit5 {
                   12967:     my ($symb,$courseid,$domain,$username)=@_;
                   12968:     my $code = &getCODE();
                   12969:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12970:     return "$num1:$num2";
                   12971: }
                   12972: 
1.366     albertel 12973: sub setup_random_from_rndseed {
                   12974:     my ($rndseed)=@_;
1.503     albertel 12975:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12976:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12977:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12978:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12979:         } else {
                   12980:             &Math::Random::random_set_seed($num1,$num2);
                   12981:         }
1.366     albertel 12982:     } else {
                   12983: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12984:     }
1.36      albertel 12985: }
                   12986: 
1.474     albertel 12987: sub latest_receipt_algorithm_id {
1.835     albertel 12988:     return 'receipt3';
1.474     albertel 12989: }
                   12990: 
1.480     www      12991: sub recunique {
                   12992:     my $fucourseid=shift;
                   12993:     my $unique;
1.835     albertel 12994:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12995: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12996: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12997:     } else {
                   12998: 	$unique=$perlvar{'lonReceipt'};
                   12999:     }
                   13000:     return unpack("%32C*",$unique);
                   13001: }
                   13002: 
                   13003: sub recprefix {
                   13004:     my $fucourseid=shift;
                   13005:     my $prefix;
1.835     albertel 13006:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13007: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13008: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13009:     } else {
                   13010: 	$prefix=$perlvar{'lonHostID'};
                   13011:     }
                   13012:     return unpack("%32C*",$prefix);
                   13013: }
                   13014: 
1.76      www      13015: sub ireceipt {
1.474     albertel 13016:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13017: 
                   13018:     my $return =&recprefix($fucourseid).'-';
                   13019: 
                   13020:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13021: 	$env{'request.state'} eq 'construct') {
                   13022: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13023: 	return $return;
                   13024:     }
                   13025: 
1.76      www      13026:     my $cuname=unpack("%32C*",$funame);
                   13027:     my $cudom=unpack("%32C*",$fudom);
                   13028:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13029:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13030:     my $cunique=&recunique($fucourseid);
1.474     albertel 13031:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13032:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13033: 
1.790     albertel 13034: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13035: 			       
                   13036: 	$return.= ($cunique%$cuname+
                   13037: 		   $cunique%$cudom+
                   13038: 		   $cusymb%$cuname+
                   13039: 		   $cusymb%$cudom+
                   13040: 		   $cucourseid%$cuname+
                   13041: 		   $cucourseid%$cudom+
                   13042: 		   $cpart%$cuname+
                   13043: 		   $cpart%$cudom);
                   13044:     } else {
                   13045: 	$return.= ($cunique%$cuname+
                   13046: 		   $cunique%$cudom+
                   13047: 		   $cusymb%$cuname+
                   13048: 		   $cusymb%$cudom+
                   13049: 		   $cucourseid%$cuname+
                   13050: 		   $cucourseid%$cudom);
                   13051:     }
                   13052:     return $return;
1.76      www      13053: }
                   13054: 
                   13055: sub receipt {
1.474     albertel 13056:     my ($part)=@_;
1.790     albertel 13057:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13058:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13059: }
1.260     ng       13060: 
1.790     albertel 13061: sub whichuser {
                   13062:     my ($passedsymb)=@_;
                   13063:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13064:     if (defined($env{'form.grade_symb'})) {
                   13065: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13066: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13067: 	if (!$allowed &&
                   13068: 	    exists($env{'request.course.sec'}) &&
                   13069: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13070: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13071: 			      '/'.$env{'request.course.sec'});
                   13072: 	}
                   13073: 	if ($allowed) {
                   13074: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13075: 	    $courseid=$tmp_courseid;
                   13076: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13077: 	    ($name)=&get_env_multiple('form.grade_username');
                   13078: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13079: 	}
                   13080:     }
                   13081:     if (!$passedsymb) {
                   13082: 	$symb=&symbread();
                   13083:     } else {
                   13084: 	$symb=$passedsymb;
                   13085:     }
                   13086:     $courseid=$env{'request.course.id'};
                   13087:     $domain=$env{'user.domain'};
                   13088:     $name=$env{'user.name'};
                   13089:     if ($name eq 'public' && $domain eq 'public') {
                   13090: 	if (!defined($env{'form.username'})) {
                   13091: 	    $env{'form.username'}.=time.rand(10000000);
                   13092: 	}
                   13093: 	$name.=$env{'form.username'};
                   13094:     }
                   13095:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13096: 
                   13097: }
                   13098: 
1.36      albertel 13099: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13100: # returns either the contents of the file or 
                   13101: # -1 if the file doesn't exist
1.481     raeburn  13102: #
                   13103: # if the target is a file that was uploaded via DOCS, 
                   13104: # a check will be made to see if a current copy exists on the local server,
                   13105: # if it does this will be served, otherwise a copy will be retrieved from
                   13106: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13107: # the local server.   
1.472     albertel 13108: 
1.36      albertel 13109: sub getfile {
1.538     albertel 13110:     my ($file) = @_;
1.609     banghart 13111:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13112:     &repcopy($file);
                   13113:     return &readfile($file);
                   13114: }
                   13115: 
                   13116: sub repcopy_userfile {
                   13117:     my ($file)=@_;
1.1142    raeburn  13118:     my $londocroot = $perlvar{'lonDocRoot'};
                   13119:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13120:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13121:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13122: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13123:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13124:     if (-e "$file") {
1.828     www      13125: # we already have a local copy, check it out
1.538     albertel 13126: 	my @fileinfo = stat($file);
1.828     www      13127: 	my $rtncode;
                   13128: 	my $info;
1.538     albertel 13129: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13130: 	if ($lwpresp ne 'ok') {
1.828     www      13131: # there is no such file anymore, even though we had a local copy
1.482     albertel 13132: 	    if ($rtncode eq '404') {
1.538     albertel 13133: 		unlink($file);
1.482     albertel 13134: 	    }
                   13135: 	    return -1;
                   13136: 	}
                   13137: 	if ($info < $fileinfo[9]) {
1.828     www      13138: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13139: 	    return 'ok';
1.828     www      13140: 	} else {
                   13141: # the file is outdated, get rid of it
                   13142: 	    unlink($file);
1.482     albertel 13143: 	}
1.828     www      13144:     }
                   13145: # one way or the other, at this point, we don't have the file
                   13146: # construct the correct path for the file
                   13147:     my @parts = ($cdom,$cnum); 
                   13148:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13149: 	push @parts, split(/\//,$1);
                   13150:     }
                   13151:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13152:     foreach my $part (@parts) {
                   13153: 	$path .= '/'.$part;
                   13154: 	if (!-e $path) {
                   13155: 	    mkdir($path,0770);
1.482     albertel 13156: 	}
                   13157:     }
1.828     www      13158: # now the path exists for sure
                   13159: # get a user agent
                   13160:     my $transferfile=$file.'.in.transfer';
                   13161: # FIXME: this should flock
                   13162:     if (-e $transferfile) { return 'ok'; }
                   13163:     my $request;
                   13164:     $uri=~s/^\///;
1.980     raeburn  13165:     my $homeserver = &homeserver($cnum,$cdom);
                   13166:     my $protocol = $protocol{$homeserver};
                   13167:     $protocol = 'http' if ($protocol ne 'https');
                   13168:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13169:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13170: # did it work?
                   13171:     if ($response->is_error()) {
                   13172: 	unlink($transferfile);
                   13173: 	&logthis("Userfile repcopy failed for $uri");
                   13174: 	return -1;
                   13175:     }
                   13176: # worked, rename the transfer file
                   13177:     rename($transferfile,$file);
1.607     raeburn  13178:     return 'ok';
1.481     raeburn  13179: }
                   13180: 
1.517     albertel 13181: sub tokenwrapper {
                   13182:     my $uri=shift;
1.980     raeburn  13183:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13184:     $uri=~s|^/||;
1.620     albertel 13185:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13186:     my $token=$1;
1.552     albertel 13187:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13188:     if ($udom && $uname && $file) {
                   13189: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13190:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13191:         my $homeserver = &homeserver($uname,$udom);
                   13192:         my $protocol = $protocol{$homeserver};
                   13193:         $protocol = 'http' if ($protocol ne 'https');
                   13194:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13195:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13196:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13197:     } else {
                   13198:         return '/adm/notfound.html';
                   13199:     }
                   13200: }
                   13201: 
1.828     www      13202: # call with reqtype HEAD: get last modification time
                   13203: # call with reqtype GET: get the file contents
                   13204: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13205: #
1.481     raeburn  13206: sub getuploaded {
                   13207:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13208:     $uri=~s/^\///;
1.980     raeburn  13209:     my $homeserver = &homeserver($cnum,$cdom);
                   13210:     my $protocol = $protocol{$homeserver};
                   13211:     $protocol = 'http' if ($protocol ne 'https');
                   13212:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13213:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13214:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13215:     $$rtncode = $response->code;
1.482     albertel 13216:     if (! $response->is_success()) {
                   13217: 	return 'failed';
                   13218:     }      
                   13219:     if ($reqtype eq 'HEAD') {
1.486     www      13220: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13221:     } elsif ($reqtype eq 'GET') {
                   13222: 	$$info = $response->content;
1.472     albertel 13223:     }
1.482     albertel 13224:     return 'ok';
1.36      albertel 13225: }
                   13226: 
1.481     raeburn  13227: sub readfile {
                   13228:     my $file = shift;
                   13229:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13230:     my $fh;
1.1359    raeburn  13231:     open($fh,"<",$file);
1.481     raeburn  13232:     my $a='';
1.800     albertel 13233:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13234:     return $a;
                   13235: }
                   13236: 
1.36      albertel 13237: sub filelocation {
1.590     banghart 13238:     my ($dir,$file) = @_;
                   13239:     my $location;
                   13240:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13241: 
                   13242:     if ($file =~ m-^/adm/-) {
                   13243: 	$file=~s-^/adm/wrapper/-/-;
                   13244: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13245:     }
1.882     albertel 13246: 
1.1139    www      13247:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13248:         $location = $file;
1.609     banghart 13249:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13250:         my ($udom,$uname,$filename)=
1.811     albertel 13251:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13252:         my $home=&homeserver($uname,$udom);
                   13253:         my $is_me=0;
                   13254:         my @ids=&current_machine_ids();
                   13255:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13256:         if ($is_me) {
1.1117    foxr     13257:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13258:         } else {
                   13259:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13260:   	      $udom.'/'.$uname.'/'.$filename;
                   13261:         }
1.882     albertel 13262:     } elsif ($file =~ m-^/adm/-) {
                   13263: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13264:     } else {
                   13265:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13266:         $file=~s:^/(res|priv)/:/:;
                   13267:         my $space=$1;
1.590     banghart 13268:         if ( !( $file =~ m:^/:) ) {
                   13269:             $location = $dir. '/'.$file;
                   13270:         } else {
1.1142    raeburn  13271:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13272:         }
1.59      albertel 13273:     }
1.590     banghart 13274:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13275:     while ($location=~m{/\.\./}) {
                   13276: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13277: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13278: 	} else {
                   13279: 	    $location=~ s{/\.\./}{/}g;
                   13280: 	}
                   13281:     } #remove dir/..
1.590     banghart 13282:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13283:     return $location;
1.46      www      13284: }
1.36      albertel 13285: 
1.46      www      13286: sub hreflocation {
                   13287:     my ($dir,$file)=@_;
1.980     raeburn  13288:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13289: 	$file=filelocation($dir,$file);
1.700     albertel 13290:     } elsif ($file=~m-^/adm/-) {
                   13291: 	$file=~s-^/adm/wrapper/-/-;
                   13292: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13293:     }
                   13294:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13295: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13296:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13297: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13298: 	        {/uploaded/$1/$2/}x;
1.46      www      13299:     }
1.913     albertel 13300:     if ($file=~ m{^/userfiles/}) {
                   13301: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13302:     }
1.462     albertel 13303:     return $file;
1.465     albertel 13304: }
                   13305: 
1.1139    www      13306: 
                   13307: 
                   13308: 
                   13309: 
1.465     albertel 13310: sub current_machine_domains {
1.853     albertel 13311:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13312: }
                   13313: 
                   13314: sub machine_domains {
                   13315:     my ($hostname) = @_;
1.465     albertel 13316:     my @domains;
1.838     albertel 13317:     my %hostname = &all_hostnames();
1.465     albertel 13318:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13319: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13320: 	if ($hostname eq $name) {
1.844     albertel 13321: 	    push(@domains,&host_domain($id));
1.465     albertel 13322: 	}
                   13323:     }
                   13324:     return @domains;
                   13325: }
                   13326: 
                   13327: sub current_machine_ids {
1.853     albertel 13328:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13329: }
                   13330: 
                   13331: sub machine_ids {
                   13332:     my ($hostname) = @_;
                   13333:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13334:     my @ids;
1.888     albertel 13335:     my %name_to_host = &all_names();
1.889     albertel 13336:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13337: 	return @{ $name_to_host{$hostname} };
                   13338:     }
                   13339:     return;
1.31      www      13340: }
                   13341: 
1.824     raeburn  13342: sub additional_machine_domains {
                   13343:     my @domains;
1.1359    raeburn  13344:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13345:     while( my $line = <$fh>) {
                   13346:         $line =~ s/\s//g;
                   13347:         push(@domains,$line);
                   13348:     }
                   13349:     return @domains;
                   13350: }
                   13351: 
                   13352: sub default_login_domain {
                   13353:     my $domain = $perlvar{'lonDefDomain'};
                   13354:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13355:     foreach my $posdom (&current_machine_domains(),
                   13356:                         &additional_machine_domains()) {
                   13357:         if (lc($posdom) eq lc($testdomain)) {
                   13358:             $domain=$posdom;
                   13359:             last;
                   13360:         }
                   13361:     }
                   13362:     return $domain;
                   13363: }
                   13364: 
1.31      www      13365: # ------------------------------------------------------------- Declutters URLs
                   13366: 
                   13367: sub declutter {
                   13368:     my $thisfn=shift;
1.569     albertel 13369:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13370:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13371:         $thisfn=~s{^/home/httpd/html}{};
                   13372:     }
1.31      www      13373:     $thisfn=~s/^\///;
1.697     albertel 13374:     $thisfn=~s|^adm/wrapper/||;
                   13375:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13376:     $thisfn=~s/^res\///;
1.1172    bisitz   13377:     $thisfn=~s/^priv\///;
1.1032    raeburn  13378:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13379:         $thisfn=~s/\?.+$//;
                   13380:     }
1.268     www      13381:     return $thisfn;
                   13382: }
                   13383: 
                   13384: # ------------------------------------------------------------- Clutter up URLs
                   13385: 
                   13386: sub clutter {
                   13387:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13388:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13389: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13390:        $thisfn='/res'.$thisfn; 
                   13391:     }
1.1031    raeburn  13392:     if ($thisfn !~m|^/adm|) {
                   13393: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13394: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13395: 	} else {
                   13396: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13397: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13398: 	    if ($embstyle eq 'ssi'
                   13399: 		|| ($embstyle eq 'hdn')
                   13400: 		|| ($embstyle eq 'rat')
                   13401: 		|| ($embstyle eq 'prv')
                   13402: 		|| ($embstyle eq 'ign')) {
                   13403: 		#do nothing with these
                   13404: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13405: 		|| ($embstyle eq 'emb')
                   13406: 		|| ($embstyle eq 'wrp')) {
                   13407: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13408: 	    } elsif ($embstyle eq 'unk'
                   13409: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13410: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13411: 	    } else {
1.718     www      13412: #		&logthis("Got a blank emb style");
1.695     albertel 13413: 	    }
1.694     albertel 13414: 	}
1.1343    raeburn  13415:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13416:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13417:     }
1.31      www      13418:     return $thisfn;
1.12      www      13419: }
                   13420: 
1.787     albertel 13421: sub clutter_with_no_wrapper {
                   13422:     my $uri = &clutter(shift);
                   13423:     if ($uri =~ m-^/adm/-) {
                   13424: 	$uri =~ s-^/adm/wrapper/-/-;
                   13425: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13426:     }
                   13427:     return $uri;
                   13428: }
                   13429: 
1.557     albertel 13430: sub freeze_escape {
                   13431:     my ($value)=@_;
                   13432:     if (ref($value)) {
                   13433: 	$value=&nfreeze($value);
                   13434: 	return '__FROZEN__'.&escape($value);
                   13435:     }
                   13436:     return &escape($value);
                   13437: }
                   13438: 
1.11      www      13439: 
1.557     albertel 13440: sub thaw_unescape {
                   13441:     my ($value)=@_;
                   13442:     if ($value =~ /^__FROZEN__/) {
                   13443: 	substr($value,0,10,undef);
                   13444: 	$value=&unescape($value);
                   13445: 	return &thaw($value);
                   13446:     }
                   13447:     return &unescape($value);
                   13448: }
                   13449: 
1.436     albertel 13450: sub correct_line_ends {
                   13451:     my ($result)=@_;
                   13452:     $$result =~s/\r\n/\n/mg;
                   13453:     $$result =~s/\r/\n/mg;
1.415     albertel 13454: }
1.1       albertel 13455: # ================================================================ Main Program
                   13456: 
1.184     www      13457: sub goodbye {
1.204     albertel 13458:    &logthis("Starting Shut down");
1.443     albertel 13459: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13460:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13461: #converted
1.599     albertel 13462: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13463:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13464: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13465: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13466: #1.1 only
1.870     albertel 13467: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13468: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13469: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13470: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13471:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13472:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13473:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13474:    &flushcourselogs();
                   13475:    &logthis("Shutting down");
                   13476: }
                   13477: 
1.852     albertel 13478: sub get_dns {
1.1210    raeburn  13479:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13480:     if (!$ignore_cache) {
                   13481: 	my ($content,$cached)=
                   13482: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13483: 	if ($cached) {
1.1210    raeburn  13484: 	    &$func($content,$hashref);
1.869     albertel 13485: 	    return;
                   13486: 	}
                   13487:     }
                   13488: 
                   13489:     my %alldns;
1.1359    raeburn  13490:     open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13491:     foreach my $dns (<$config>) {
                   13492: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13493:         my $line = $1;
                   13494:         my ($host,$protocol) = split(/:/,$line);
                   13495:         if ($protocol ne 'https') {
                   13496:             $protocol = 'http';
                   13497:         }
                   13498: 	$alldns{$host} = $protocol;
1.869     albertel 13499:     }
                   13500:     while (%alldns) {
1.1263    raeburn  13501: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13502: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13503:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13504:         delete($alldns{$dns});
1.852     albertel 13505: 	next if ($response->is_error());
                   13506: 	my @content = split("\n",$response->content);
1.1210    raeburn  13507: 	unless ($nocache) {
1.1219    raeburn  13508: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13509: 	}
                   13510: 	&$func(\@content,$hashref);
1.869     albertel 13511: 	return;
1.852     albertel 13512:     }
                   13513:     close($config);
1.871     albertel 13514:     my $which = (split('/',$url))[3];
                   13515:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1359    raeburn  13516:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13517:     my @content = <$config>;
1.1210    raeburn  13518:     &$func(\@content,$hashref);
                   13519:     return;
                   13520: }
                   13521: 
                   13522: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13523: sub parse_dns_checksums_tab {
1.1210    raeburn  13524:     my ($lines,$hashref) = @_;
1.1264    raeburn  13525:     my $lonhost = $perlvar{'lonHostID'};
                   13526:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13527:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13528:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13529:     my $webconfdir = '/etc/httpd/conf';
                   13530:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13531:         $webconfdir = '/etc/apache2';
                   13532:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13533:         if ($1 >= 10) {
                   13534:             $webconfdir = '/etc/apache2';
                   13535:         }
                   13536:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13537:         if ($1 >= 10.0) {
                   13538:             $webconfdir = '/etc/apache2';
                   13539:         }
                   13540:     }
1.1210    raeburn  13541:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13542:     my (%chksum,%revnum);
                   13543:     if (ref($lines) eq 'ARRAY') {
                   13544:         chomp(@{$lines});
1.1238    raeburn  13545:         my $version = shift(@{$lines});
                   13546:         if ($version eq $release) {  
1.1210    raeburn  13547:             foreach my $line (@{$lines}) {
1.1238    raeburn  13548:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13549:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13550:                     if ($webconfdir eq '/etc/apache2') {
                   13551:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13552:                     }
                   13553:                 }
1.1238    raeburn  13554:                 $chksum{$file} = $shasum;
                   13555:                 $revnum{$file} = $version;
1.1210    raeburn  13556:             }
                   13557:             if (ref($hashref) eq 'HASH') {
                   13558:                 %{$hashref} = (
                   13559:                                 sums     => \%chksum,
                   13560:                                 versions => \%revnum,
                   13561:                               );
                   13562:             }
                   13563:         }
                   13564:     }
1.869     albertel 13565:     return;
1.852     albertel 13566: }
1.1210    raeburn  13567: 
                   13568: sub fetch_dns_checksums {
1.1238    raeburn  13569:     my %checksums;
                   13570:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13571:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13572:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13573:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13574:              \%checksums);
1.1210    raeburn  13575:     return \%checksums;
                   13576: }
                   13577: 
1.327     albertel 13578: # ------------------------------------------------------------ Read domain file
                   13579: {
1.852     albertel 13580:     my $loaded;
1.846     albertel 13581:     my %domain;
                   13582: 
1.852     albertel 13583:     sub parse_domain_tab {
                   13584: 	my ($lines) = @_;
                   13585: 	foreach my $line (@$lines) {
                   13586: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13587: 
1.846     albertel 13588: 	    chomp($line);
1.852     albertel 13589: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13590: 	    my %this_domain;
                   13591: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13592: 			       'lang_def', 'city', 'longi', 'lati',
                   13593: 			       'primary') {
                   13594: 		$this_domain{$field} = shift(@elements);
                   13595: 	    }
                   13596: 	    $domain{$name} = \%this_domain;
1.852     albertel 13597: 	}
                   13598:     }
1.864     albertel 13599: 
                   13600:     sub reset_domain_info {
                   13601: 	undef($loaded);
                   13602: 	undef(%domain);
                   13603:     }
                   13604: 
1.852     albertel 13605:     sub load_domain_tab {
1.1293    raeburn  13606: 	my ($ignore_cache,$nocache) = @_;
                   13607: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13608: 	my $fh;
1.1359    raeburn  13609: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13610: 	    my @lines = <$fh>;
                   13611: 	    &parse_domain_tab(\@lines);
1.448     albertel 13612: 	}
1.852     albertel 13613: 	close($fh);
                   13614: 	$loaded = 1;
1.327     albertel 13615:     }
1.846     albertel 13616: 
                   13617:     sub domain {
1.852     albertel 13618: 	&load_domain_tab() if (!$loaded);
                   13619: 
1.846     albertel 13620: 	my ($name,$what) = @_;
                   13621: 	return if ( !exists($domain{$name}) );
                   13622: 
                   13623: 	if (!$what) {
                   13624: 	    return $domain{$name}{'description'};
                   13625: 	}
                   13626: 	return $domain{$name}{$what};
                   13627:     }
1.974     raeburn  13628: 
                   13629:     sub domain_info {
                   13630:         &load_domain_tab() if (!$loaded);
                   13631:         return %domain;
                   13632:     }
                   13633: 
1.327     albertel 13634: }
                   13635: 
                   13636: 
1.1       albertel 13637: # ------------------------------------------------------------- Read hosts file
                   13638: {
1.838     albertel 13639:     my %hostname;
1.844     albertel 13640:     my %hostdom;
1.845     albertel 13641:     my %libserv;
1.852     albertel 13642:     my $loaded;
1.888     albertel 13643:     my %name_to_host;
1.1074    raeburn  13644:     my %internetdom;
1.1107    raeburn  13645:     my %LC_dns_serv;
1.852     albertel 13646: 
                   13647:     sub parse_hosts_tab {
                   13648: 	my ($file) = @_;
                   13649: 	foreach my $configline (@$file) {
                   13650: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13651:             chomp($configline);
                   13652: 	    if ($configline =~ /^\^/) {
                   13653:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13654:                     $LC_dns_serv{$1} = 1;
                   13655:                 }
                   13656:                 next;
                   13657:             }
1.1074    raeburn  13658: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13659: 	    $name=~s/\s//g;
                   13660: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13661:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13662:                     my $curr = $hostname{$id};
                   13663:                     my $skip;
                   13664:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13665:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13666:                             $skip = 1;
                   13667:                         } else {
                   13668:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13669:                         }
                   13670:                     }
                   13671:                     unless ($skip) {
                   13672:                         push(@{$name_to_host{$name}},$id);
                   13673:                     }
                   13674:                 } else {
                   13675:                     push(@{$name_to_host{$name}},$id);
                   13676:                 }
1.852     albertel 13677: 		$hostname{$id}=$name;
                   13678: 		$hostdom{$id}=$domain;
                   13679: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13680:                 if (defined($protocol)) {
                   13681:                     if ($protocol eq 'https') {
                   13682:                         $protocol{$id} = $protocol;
                   13683:                     } else {
                   13684:                         $protocol{$id} = 'http'; 
                   13685:                     }
1.968     raeburn  13686:                 } else {
1.969     raeburn  13687:                     $protocol{$id} = 'http';
1.968     raeburn  13688:                 }
1.1074    raeburn  13689:                 if (defined($intdom)) {
                   13690:                     $internetdom{$id} = $intdom;
                   13691:                 }
1.852     albertel 13692: 	    }
                   13693: 	}
                   13694:     }
1.864     albertel 13695:     
                   13696:     sub reset_hosts_info {
1.897     albertel 13697: 	&purge_remembered();
1.864     albertel 13698: 	&reset_domain_info();
                   13699: 	&reset_hosts_ip_info();
1.1339    raeburn  13700:         undef(%internetdom);
1.892     albertel 13701: 	undef(%name_to_host);
1.864     albertel 13702: 	undef(%hostname);
                   13703: 	undef(%hostdom);
                   13704: 	undef(%libserv);
                   13705: 	undef($loaded);
                   13706:     }
1.1       albertel 13707: 
1.852     albertel 13708:     sub load_hosts_tab {
1.1293    raeburn  13709: 	my ($ignore_cache,$nocache) = @_;
                   13710: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13711: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13712: 	my @config = <$config>;
                   13713: 	&parse_hosts_tab(\@config);
                   13714: 	close($config);
                   13715: 	$loaded=1;
1.1       albertel 13716:     }
1.852     albertel 13717: 
1.838     albertel 13718:     sub hostname {
1.852     albertel 13719: 	&load_hosts_tab() if (!$loaded);
                   13720: 
1.838     albertel 13721: 	my ($lonid) = @_;
                   13722: 	return $hostname{$lonid};
                   13723:     }
1.845     albertel 13724: 
1.838     albertel 13725:     sub all_hostnames {
1.852     albertel 13726: 	&load_hosts_tab() if (!$loaded);
                   13727: 
1.838     albertel 13728: 	return %hostname;
                   13729:     }
1.845     albertel 13730: 
1.888     albertel 13731:     sub all_names {
1.1293    raeburn  13732:         my ($ignore_cache,$nocache) = @_;
                   13733: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13734: 
                   13735: 	return %name_to_host;
                   13736:     }
                   13737: 
1.974     raeburn  13738:     sub all_host_domain {
                   13739:         &load_hosts_tab() if (!$loaded);
                   13740:         return %hostdom;
                   13741:     }
                   13742: 
1.1339    raeburn  13743:     sub all_host_intdom {
                   13744:         &load_hosts_tab() if (!$loaded);
                   13745:         return %internetdom;
                   13746:     }
                   13747: 
1.845     albertel 13748:     sub is_library {
1.852     albertel 13749: 	&load_hosts_tab() if (!$loaded);
                   13750: 
1.845     albertel 13751: 	return exists($libserv{$_[0]});
                   13752:     }
                   13753: 
                   13754:     sub all_library {
1.852     albertel 13755: 	&load_hosts_tab() if (!$loaded);
                   13756: 
1.845     albertel 13757: 	return %libserv;
                   13758:     }
                   13759: 
1.1062    droeschl 13760:     sub unique_library {
                   13761: 	#2x reverse removes all hostnames that appear more than once
                   13762:         my %unique = reverse &all_library();
                   13763:         return reverse %unique;
                   13764:     }
                   13765: 
1.841     albertel 13766:     sub get_servers {
1.852     albertel 13767: 	&load_hosts_tab() if (!$loaded);
                   13768: 
1.841     albertel 13769: 	my ($domain,$type) = @_;
                   13770: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13771: 	                                          : %hostname;
                   13772: 	my %result;
1.842     albertel 13773: 	if (ref($domain) eq 'ARRAY') {
                   13774: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13775: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13776: 		    $result{$host} = $hostname;
                   13777: 		}
                   13778: 	    }
                   13779: 	} else {
                   13780: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13781: 		if ($hostdom{$host} eq $domain) {
                   13782: 		    $result{$host} = $hostname;
                   13783: 		}
1.841     albertel 13784: 	    }
                   13785: 	}
                   13786: 	return %result;
                   13787:     }
1.845     albertel 13788: 
1.1062    droeschl 13789:     sub get_unique_servers {
                   13790:         my %unique = reverse &get_servers(@_);
                   13791: 	return reverse %unique;
                   13792:     }
                   13793: 
1.844     albertel 13794:     sub host_domain {
1.852     albertel 13795: 	&load_hosts_tab() if (!$loaded);
                   13796: 
1.844     albertel 13797: 	my ($lonid) = @_;
                   13798: 	return $hostdom{$lonid};
                   13799:     }
                   13800: 
1.841     albertel 13801:     sub all_domains {
1.852     albertel 13802: 	&load_hosts_tab() if (!$loaded);
                   13803: 
1.841     albertel 13804: 	my %seen;
                   13805: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13806: 	return @uniq;
                   13807:     }
1.1074    raeburn  13808: 
                   13809:     sub internet_dom {
                   13810:         &load_hosts_tab() if (!$loaded);
                   13811: 
                   13812:         my ($lonid) = @_;
                   13813:         return $internetdom{$lonid};
                   13814:     }
1.1107    raeburn  13815: 
                   13816:     sub is_LC_dns {
                   13817:         &load_hosts_tab() if (!$loaded);
                   13818: 
                   13819:         my ($hostname) = @_;
                   13820:         return exists($LC_dns_serv{$hostname});
                   13821:     }
                   13822: 
1.1       albertel 13823: }
                   13824: 
1.847     albertel 13825: { 
                   13826:     my %iphost;
1.856     albertel 13827:     my %name_to_ip;
                   13828:     my %lonid_to_ip;
1.869     albertel 13829: 
1.847     albertel 13830:     sub get_hosts_from_ip {
                   13831: 	my ($ip) = @_;
                   13832: 	my %iphosts = &get_iphost();
                   13833: 	if (ref($iphosts{$ip})) {
                   13834: 	    return @{$iphosts{$ip}};
                   13835: 	}
                   13836: 	return;
1.839     albertel 13837:     }
1.864     albertel 13838:     
                   13839:     sub reset_hosts_ip_info {
                   13840: 	undef(%iphost);
                   13841: 	undef(%name_to_ip);
                   13842: 	undef(%lonid_to_ip);
                   13843:     }
1.856     albertel 13844: 
                   13845:     sub get_host_ip {
                   13846: 	my ($lonid) = @_;
                   13847: 	if (exists($lonid_to_ip{$lonid})) {
                   13848: 	    return $lonid_to_ip{$lonid};
                   13849: 	}
                   13850: 	my $name=&hostname($lonid);
                   13851:    	my $ip = gethostbyname($name);
                   13852: 	return if (!$ip || length($ip) ne 4);
                   13853: 	$ip=inet_ntoa($ip);
                   13854: 	$name_to_ip{$name}   = $ip;
                   13855: 	$lonid_to_ip{$lonid} = $ip;
                   13856: 	return $ip;
                   13857:     }
1.847     albertel 13858:     
                   13859:     sub get_iphost {
1.1293    raeburn  13860: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13861: 
1.869     albertel 13862: 	if (!$ignore_cache) {
                   13863: 	    if (%iphost) {
                   13864: 		return %iphost;
                   13865: 	    }
                   13866: 	    my ($ip_info,$cached)=
                   13867: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13868: 	    if ($cached) {
                   13869: 		%iphost      = %{$ip_info->[0]};
                   13870: 		%name_to_ip  = %{$ip_info->[1]};
                   13871: 		%lonid_to_ip = %{$ip_info->[2]};
                   13872: 		return %iphost;
                   13873: 	    }
                   13874: 	}
1.894     albertel 13875: 
                   13876: 	# get yesterday's info for fallback
                   13877: 	my %old_name_to_ip;
                   13878: 	my ($ip_info,$cached)=
                   13879: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13880: 	if ($cached) {
                   13881: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13882: 	}
                   13883: 
1.1293    raeburn  13884: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13885: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13886: 	    my $ip;
                   13887: 	    if (!exists($name_to_ip{$name})) {
                   13888: 		$ip = gethostbyname($name);
                   13889: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13890: 		    if (defined($old_name_to_ip{$name})) {
                   13891: 			$ip = $old_name_to_ip{$name};
                   13892: 			&logthis("Can't find $name defaulting to old $ip");
                   13893: 		    } else {
                   13894: 			&logthis("Name $name no IP found");
                   13895: 			next;
                   13896: 		    }
                   13897: 		} else {
                   13898: 		    $ip=inet_ntoa($ip);
1.847     albertel 13899: 		}
                   13900: 		$name_to_ip{$name} = $ip;
                   13901: 	    } else {
                   13902: 		$ip = $name_to_ip{$name};
1.653     albertel 13903: 	    }
1.888     albertel 13904: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13905: 		$lonid_to_ip{$id} = $ip;
                   13906: 	    }
                   13907: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13908: 	}
1.1293    raeburn  13909:         unless ($nocache) {
                   13910: 	    &do_cache_new('iphost','iphost',
                   13911: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13912: 		          48*60*60);
                   13913:         }
1.869     albertel 13914: 
1.847     albertel 13915: 	return %iphost;
1.598     albertel 13916:     }
                   13917: 
1.992     raeburn  13918:     #
                   13919:     #  Given a DNS returns the loncapa host name for that DNS 
                   13920:     # 
                   13921:     sub host_from_dns {
                   13922:         my ($dns) = @_;
                   13923:         my @hosts;
                   13924:         my $ip;
                   13925: 
1.993     raeburn  13926:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13927:             $ip = $name_to_ip{$dns};
                   13928:         }
                   13929:         if (!$ip) {
                   13930:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13931:             if (length($ip) == 4) { 
                   13932: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13933:             }
                   13934:         }
                   13935:         if ($ip) {
                   13936: 	    @hosts = get_hosts_from_ip($ip);
                   13937: 	    return $hosts[0];
                   13938:         }
                   13939:         return undef;
1.986     foxr     13940:     }
1.992     raeburn  13941: 
1.1074    raeburn  13942:     sub get_internet_names {
                   13943:         my ($lonid) = @_;
                   13944:         return if ($lonid eq '');
                   13945:         my ($idnref,$cached)=
                   13946:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13947:         if ($cached) {
                   13948:             return $idnref;
                   13949:         }
                   13950:         my $ip = &get_host_ip($lonid);
                   13951:         my @hosts = &get_hosts_from_ip($ip);
                   13952:         my %iphost = &get_iphost();
                   13953:         my (@idns,%seen);
                   13954:         foreach my $id (@hosts) {
                   13955:             my $dom = &host_domain($id);
                   13956:             my $prim_id = &domain($dom,'primary');
                   13957:             my $prim_ip = &get_host_ip($prim_id);
                   13958:             next if ($seen{$prim_ip});
                   13959:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13960:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13961:                     my $intdom = &internet_dom($id);
                   13962:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13963:                         push(@idns,$intdom);
                   13964:                     }
                   13965:                 }
                   13966:             }
                   13967:             $seen{$prim_ip} = 1;
                   13968:         }
1.1219    raeburn  13969:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13970:     }
                   13971: 
1.986     foxr     13972: }
                   13973: 
1.1079    raeburn  13974: sub all_loncaparevs {
1.1249    raeburn  13975:     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  13976: }
                   13977: 
1.1227    raeburn  13978: # ---------------------------------------------------------- Read loncaparev table
                   13979: {
                   13980:     sub load_loncaparevs { 
                   13981:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  13982:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  13983:                 while (my $configline=<$config>) {
                   13984:                     chomp($configline);
                   13985:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13986:                     $loncaparevs{$hostid}=$loncaparev;
                   13987:                 }
                   13988:                 close($config);
                   13989:             }
                   13990:         }
                   13991:     }
                   13992: }
                   13993: 
                   13994: # ---------------------------------------------------------- Read serverhostID table
                   13995: {
                   13996:     sub load_serverhomeIDs {
                   13997:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  13998:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  13999:                 while (my $configline=<$config>) {
                   14000:                     chomp($configline);
                   14001:                     my ($name,$id)=split(/:/,$configline);
                   14002:                     $serverhomeIDs{$name}=$id;
                   14003:                 }
                   14004:                 close($config);
                   14005:             }
                   14006:         }
                   14007:     }
                   14008: }
                   14009: 
                   14010: 
1.862     albertel 14011: BEGIN {
                   14012: 
                   14013: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14014:     unless ($readit) {
                   14015: {
                   14016:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14017:     %perlvar = (%perlvar,%{$configvars});
                   14018: }
                   14019: 
                   14020: 
1.1       albertel 14021: # ------------------------------------------------------ Read spare server file
                   14022: {
1.1359    raeburn  14023:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14024: 
                   14025:     while (my $configline=<$config>) {
                   14026:        chomp($configline);
1.284     matthew  14027:        if ($configline) {
1.784     albertel 14028: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14029: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14030: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14031:        }
                   14032:     }
1.448     albertel 14033:     close($config);
1.1       albertel 14034: }
1.11      www      14035: # ------------------------------------------------------------ Read permissions
                   14036: {
1.1359    raeburn  14037:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14038: 
                   14039:     while (my $configline=<$config>) {
1.448     albertel 14040: 	chomp($configline);
                   14041: 	if ($configline) {
                   14042: 	    my ($role,$perm)=split(/ /,$configline);
                   14043: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14044: 	}
1.11      www      14045:     }
1.448     albertel 14046:     close($config);
1.11      www      14047: }
                   14048: 
                   14049: # -------------------------------------------- Read plain texts for permissions
                   14050: {
1.1359    raeburn  14051:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14052: 
                   14053:     while (my $configline=<$config>) {
1.448     albertel 14054: 	chomp($configline);
                   14055: 	if ($configline) {
1.742     raeburn  14056: 	    my ($short,@plain)=split(/:/,$configline);
                   14057:             %{$prp{$short}} = ();
                   14058: 	    if (@plain > 0) {
                   14059:                 $prp{$short}{'std'} = $plain[0];
                   14060:                 for (my $i=1; $i<@plain; $i++) {
                   14061:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14062:                 }
                   14063:             }
1.448     albertel 14064: 	}
1.135     www      14065:     }
1.448     albertel 14066:     close($config);
1.135     www      14067: }
                   14068: 
                   14069: # ---------------------------------------------------------- Read package table
                   14070: {
1.1359    raeburn  14071:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14072: 
                   14073:     while (my $configline=<$config>) {
1.483     albertel 14074: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14075: 	chomp($configline);
                   14076: 	my ($short,$plain)=split(/:/,$configline);
                   14077: 	my ($pack,$name)=split(/\&/,$short);
                   14078: 	if ($plain ne '') {
                   14079: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14080: 	    $packagetab{$short}=$plain; 
                   14081: 	}
1.11      www      14082:     }
1.448     albertel 14083:     close($config);
1.329     matthew  14084: }
                   14085: 
1.1073    raeburn  14086: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14087: 
                   14088: &load_loncaparevs();
1.1073    raeburn  14089: 
1.1074    raeburn  14090: # ---------------------------------------------------------- Read serverhostID table
                   14091: 
1.1227    raeburn  14092: &load_serverhomeIDs();
                   14093: 
                   14094: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14095: {
                   14096:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14097:     if (-e $file) {
                   14098:         my $parser = HTML::LCParser->new($file);
                   14099:         while (my $token = $parser->get_token()) {
                   14100:             if ($token->[0] eq 'S') {
                   14101:                 my $item = $token->[1];
                   14102:                 my $name = $token->[2]{'name'};
                   14103:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14104:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14105:                 my $namematch = $token->[2]{'namematch'};
                   14106:                 if ($item eq 'parameter') {
                   14107:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14108:                         my $release = $parser->get_text();
                   14109:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14110:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14111:                     }
                   14112:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14113:                     my $release = $parser->get_text();
                   14114:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14115:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14116:                 }
                   14117:             }
                   14118:         }
                   14119:     }
1.1073    raeburn  14120: }
                   14121: 
1.1138    raeburn  14122: # ---------------------------------------------------------- Read managers table
                   14123: {
                   14124:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14125:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14126:             while (my $configline=<$config>) {
                   14127:                 chomp($configline);
                   14128:                 next if ($configline =~ /^\#/);
                   14129:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14130:                     $managerstab{$configline} = 1;
                   14131:                 }
                   14132:             }
                   14133:             close($config);
                   14134:         }
                   14135:     }
                   14136: }
                   14137: 
1.329     matthew  14138: # ------------- set up temporary directory
                   14139: {
1.1117    foxr     14140:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14141: 
1.11      www      14142: }
                   14143: 
1.794     albertel 14144: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14145: 				'compress_threshold'=> 20_000,
                   14146:  			        });
1.185     www      14147: 
1.281     www      14148: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14149: $dumpcount=0;
1.958     www      14150: $locknum=0;
1.22      www      14151: 
1.163     harris41 14152: &logtouch();
1.672     albertel 14153: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14154: $readit=1;
1.564     albertel 14155:     {
                   14156: 	use integer;
                   14157: 	my $test=(2**32)+1;
1.568     albertel 14158: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14159: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14160:     }
1.195     www      14161: }
1.1       albertel 14162: }
1.179     www      14163: 
1.1       albertel 14164: 1;
1.191     harris41 14165: __END__
                   14166: 
1.243     albertel 14167: =pod
                   14168: 
1.191     harris41 14169: =head1 NAME
                   14170: 
1.243     albertel 14171: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14172: 
                   14173: =head1 SYNOPSIS
                   14174: 
1.243     albertel 14175: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14176: 
                   14177:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14178: 
1.243     albertel 14179: Common parameters:
                   14180: 
                   14181: =over 4
                   14182: 
                   14183: =item *
                   14184: 
                   14185: $uname : an internal username (if $cname expecting a course Id specifically)
                   14186: 
                   14187: =item *
                   14188: 
                   14189: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14190: 
                   14191: =item *
                   14192: 
                   14193: $symb : a resource instance identifier
                   14194: 
                   14195: =item *
                   14196: 
                   14197: $namespace : the name of a .db file that contains the data needed or
                   14198: being set.
                   14199: 
                   14200: =back
                   14201: 
1.394     bowersj2 14202: =head1 OVERVIEW
1.191     harris41 14203: 
1.394     bowersj2 14204: lonnet provides subroutines which interact with the
                   14205: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14206: about classes, users, and resources.
1.243     albertel 14207: 
                   14208: For many of these objects you can also use this to store data about
                   14209: them or modify them in various ways.
1.191     harris41 14210: 
1.394     bowersj2 14211: =head2 Symbs
1.191     harris41 14212: 
1.394     bowersj2 14213: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14214: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14215: map, the resource number of the resource in the map, and the URL of
                   14216: the resource itself. The latter is somewhat redundant, but might help
                   14217: if maps change.
                   14218: 
                   14219: An example is
                   14220: 
                   14221:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14222: 
                   14223: The respective map entry is
                   14224: 
                   14225:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14226:   title="Problem 2">
                   14227:  </resource>
                   14228: 
                   14229: Symbs are used by the random number generator, as well as to store and
                   14230: restore data specific to a certain instance of for example a problem.
                   14231: 
                   14232: =head2 Storing And Retrieving Data
                   14233: 
                   14234: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14235: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14236: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14237: is is the non-critical message twin of cstore. These functions are for
                   14238: handlers to store a perl hash to a user's permanent data space in an
                   14239: easy manner, and to retrieve it again on another call. It is expected
                   14240: that a handler would use this once at the beginning to retrieve data,
                   14241: and then again once at the end to send only the new data back.
                   14242: 
                   14243: The data is stored in the user's data directory on the user's
                   14244: homeserver under the ID of the course.
                   14245: 
                   14246: The hash that is returned by restore will have all of the previous
                   14247: value for all of the elements of the hash.
                   14248: 
                   14249: Example:
                   14250: 
                   14251:  #creating a hash
                   14252:  my %hash;
                   14253:  $hash{'foo'}='bar';
                   14254: 
                   14255:  #storing it
                   14256:  &Apache::lonnet::cstore(\%hash);
                   14257: 
                   14258:  #changing a value
                   14259:  $hash{'foo'}='notbar';
                   14260: 
                   14261:  #adding a new value
                   14262:  $hash{'bar'}='foo';
                   14263:  &Apache::lonnet::cstore(\%hash);
                   14264: 
                   14265:  #retrieving the hash
                   14266:  my %history=&Apache::lonnet::restore();
                   14267: 
                   14268:  #print the hash
                   14269:  foreach my $key (sort(keys(%history))) {
                   14270:    print("\%history{$key} = $history{$key}");
                   14271:  }
                   14272: 
                   14273: Will print out:
1.191     harris41 14274: 
1.394     bowersj2 14275:  %history{1:foo} = bar
                   14276:  %history{1:keys} = foo:timestamp
                   14277:  %history{1:timestamp} = 990455579
                   14278:  %history{2:bar} = foo
                   14279:  %history{2:foo} = notbar
                   14280:  %history{2:keys} = foo:bar:timestamp
                   14281:  %history{2:timestamp} = 990455580
                   14282:  %history{bar} = foo
                   14283:  %history{foo} = notbar
                   14284:  %history{timestamp} = 990455580
                   14285:  %history{version} = 2
                   14286: 
                   14287: Note that the special hash entries C<keys>, C<version> and
                   14288: C<timestamp> were added to the hash. C<version> will be equal to the
                   14289: total number of versions of the data that have been stored. The
                   14290: C<timestamp> attribute will be the UNIX time the hash was
                   14291: stored. C<keys> is available in every historical section to list which
                   14292: keys were added or changed at a specific historical revision of a
                   14293: hash.
                   14294: 
                   14295: B<Warning>: do not store the hash that restore returns directly. This
                   14296: will cause a mess since it will restore the historical keys as if the
                   14297: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14298: 
1.394     bowersj2 14299: Calling convention:
1.191     harris41 14300: 
1.1225    raeburn  14301:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14302:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14303: 
1.394     bowersj2 14304: For more detailed information, see lonnet specific documentation.
1.191     harris41 14305: 
1.394     bowersj2 14306: =head1 RETURN MESSAGES
1.191     harris41 14307: 
1.394     bowersj2 14308: =over 4
1.191     harris41 14309: 
1.394     bowersj2 14310: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14311: 
1.394     bowersj2 14312: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14313: when the connection is brought back up
1.191     harris41 14314: 
1.394     bowersj2 14315: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14316: for later delivery
1.191     harris41 14317: 
1.967     bisitz   14318: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14319: 
1.394     bowersj2 14320: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14321: that was requested
1.191     harris41 14322: 
1.243     albertel 14323: =back
1.191     harris41 14324: 
1.243     albertel 14325: =head1 PUBLIC SUBROUTINES
1.191     harris41 14326: 
1.243     albertel 14327: =head2 Session Environment Functions
1.191     harris41 14328: 
1.243     albertel 14329: =over 4
1.191     harris41 14330: 
1.394     bowersj2 14331: =item * 
                   14332: X<appenv()>
1.949     raeburn  14333: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14334: the user envirnoment file, and will be restored for each access this
1.620     albertel 14335: user makes during this session, also modifies the %env for the current
1.949     raeburn  14336: process. Optional rolesarrayref - if defined contains a reference to an array
                   14337: of roles which are exempt from the restriction on modifying user.role entries 
                   14338: in the user's environment.db and in %env.    
1.191     harris41 14339: 
                   14340: =item *
1.394     bowersj2 14341: X<delenv()>
1.987     raeburn  14342: B<delenv($delthis,$regexp)>: removes all items from the session
                   14343: environment file that begin with $delthis. If the 
                   14344: optional second arg - $regexp - is true, $delthis is treated as a 
                   14345: regular expression, otherwise \Q$delthis\E is used. 
                   14346: The values are also deleted from the current processes %env.
1.191     harris41 14347: 
1.795     albertel 14348: =item * get_env_multiple($name) 
                   14349: 
                   14350: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14351: values may be defined and end up as an array ref.
                   14352: 
                   14353: returns an array of values
                   14354: 
1.243     albertel 14355: =back
                   14356: 
                   14357: =head2 User Information
1.191     harris41 14358: 
1.243     albertel 14359: =over 4
1.191     harris41 14360: 
                   14361: =item *
1.394     bowersj2 14362: X<queryauthenticate()>
                   14363: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14364: authentication scheme
                   14365: 
                   14366: =item *
1.394     bowersj2 14367: X<authenticate()>
1.1073    raeburn  14368: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14369: authenticate user from domain's lib servers (first use the current
                   14370: one). C<$upass> should be the users password.
1.1073    raeburn  14371: $checkdefauth is optional (value is 1 if a check should be made to
                   14372:    authenticate user using default authentication method, and allow
                   14373:    account creation if username does not have account in the domain).
                   14374: $clientcancheckhost is optional (value is 1 if checking whether the
                   14375:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14376: 
                   14377: =item *
1.394     bowersj2 14378: X<homeserver()>
                   14379: B<homeserver($uname,$udom)>: find the server which has
                   14380: the user's directory and files (there must be only one), this caches
                   14381: the answer, and also caches if there is a borken connection.
1.191     harris41 14382: 
                   14383: =item *
1.394     bowersj2 14384: X<idget()>
1.1300    raeburn  14385: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14386: a list of student/employee IDs or clicker IDs
                   14387: (student/employee IDs are a unique resource in a domain, there must be 
                   14388: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14389: clickerIDs are not necessarily unique, as students might share clickers.
                   14390: (returns hash: id=>name,id=>name)
1.191     harris41 14391: 
                   14392: =item *
1.394     bowersj2 14393: X<idrget()>
                   14394: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14395: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14396: 
                   14397: =item *
1.394     bowersj2 14398: X<idput()>
1.1300    raeburn  14399: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14400: names and associated student/employee IDs or clicker IDs.
                   14401: 
                   14402: =item *
                   14403: X<iddel()>
                   14404: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14405: student/employee ID or clicker ID username look-ups from domain.
                   14406: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14407: If no $uhome is provided, it will be determined usig &homeserver()
                   14408: for each user.  If no $namespace is provided, the default is ids.
                   14409: 
                   14410: =item *
                   14411: X<updateclickers()>
                   14412: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14413: clicker ID-to-username look-ups in clickers.db on library server.
                   14414: Permitted actions are add or del (i.e., add or delete). The 
                   14415: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14416: value is an escaped comma-separated list of usernames (for whom the
                   14417: library server is the homeserver), who registered that particular ID.
                   14418: If $critical is true, the update will be sent via &critical, otherwise
                   14419: &reply() will be used.
1.191     harris41 14420: 
                   14421: =item *
1.394     bowersj2 14422: X<rolesinit()>
1.1169    droeschl 14423: B<rolesinit($udom,$username)>: get user privileges.
                   14424: returns user role, first access and timer interval hashes
1.243     albertel 14425: 
                   14426: =item *
1.1171    droeschl 14427: X<privileged()>
                   14428: B<privileged($username,$domain)>: returns a true if user has a
                   14429: privileged and active role (i.e. su or dc), false otherwise.
                   14430: 
                   14431: =item *
1.551     albertel 14432: X<getsection()>
                   14433: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14434: course $cname, return section name/number or '' for "not in course"
                   14435: and '-1' for "no section"
                   14436: 
                   14437: =item *
1.394     bowersj2 14438: X<userenvironment()>
                   14439: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14440: passed in @what from the requested user's environment, returns a hash
                   14441: 
1.858     raeburn  14442: =item * 
                   14443: X<userlog_query()>
1.859     albertel 14444: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14445: activity.log file. %filters defines filters applied when parsing the
                   14446: log file. These can be start or end timestamps, or the type of action
                   14447: - log to look for Login or Logout events, check for Checkin or
                   14448: Checkout, role for role selection. The response is in the form
                   14449: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14450: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14451: 
1.243     albertel 14452: =back
                   14453: 
                   14454: =head2 User Roles
                   14455: 
                   14456: =over 4
                   14457: 
                   14458: =item *
                   14459: 
1.1284    raeburn  14460: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14461: returns codes for allowed actions.
                   14462: 
                   14463: The first argument is required, all others are optional.
                   14464: 
                   14465: $priv is the privilege being checked.
                   14466: $uri contains additional information about what is being checked for access (e.g.,
                   14467: URL, course ID etc.). 
                   14468: $symb is the unique resource instance identifier in a course; if needed,
                   14469: but not provided, it will be retrieved via a call to &symbread(). 
                   14470: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14471: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14472: files).
                   14473: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14474: prevents recursive calls to &allowed.
                   14475: 
1.243     albertel 14476:  F: full access
                   14477:  U,I,K: authentication modes (cxx only)
                   14478:  '': forbidden
                   14479:  1: user needs to choose course
                   14480:  2: browse allowed
1.766     albertel 14481:  A: passphrase authentication needed
1.1284    raeburn  14482:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14483: 
                   14484: =item *
                   14485: 
1.1192    raeburn  14486: constructaccess($url,$setpriv) : check for access to construction space URL
                   14487: 
                   14488: See if the owner domain and name in the URL match those in the
                   14489: expected environment.  If so, return three element list
                   14490: ($ownername,$ownerdomain,$ownerhome).
                   14491: 
                   14492: Otherwise return the null string.
                   14493: 
                   14494: If second argument 'setpriv' is true, it assigns the privileges,
                   14495: and returns the same three element list, unless the owner has
                   14496: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14497: in which case the null string is returned.
                   14498: 
                   14499: =item *
                   14500: 
1.1326    raeburn  14501: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14502: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14503: for system, domain, and course level. $uname and $udom are optional (current
                   14504: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14505: 
                   14506: =item *
                   14507: 
1.988     raeburn  14508: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14509: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14510: $type is Course (default) or Community.
1.988     raeburn  14511: If $forcedefault evaluates to true, text returned will be default 
                   14512: text for $type. Otherwise, if this is a course, the text returned 
                   14513: will be a custom name for the role (if defined in the course's 
                   14514: environment).  If no custom name is defined the default is returned.
                   14515:    
1.832     raeburn  14516: =item *
                   14517: 
1.1219    raeburn  14518: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14519: All arguments are optional. Returns a hash of a roles, either for
                   14520: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14521: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14522: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14523: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14524: For each key, value is set to colon-separated start and end times for
                   14525: the role.  If no username and domain are specified, will default to
1.934     raeburn  14526: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14527: of role statuses (active, future or previous), roles 
                   14528: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14529: to restrict the list of roles reported. If no array ref is 
                   14530: provided for types, will default to return only active roles.
1.834     albertel 14531: 
1.1195    raeburn  14532: =item *
                   14533: 
                   14534: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14535: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14536: 
                   14537: Additional optional arguments are: $type (if role checking is to be restricted 
                   14538: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14539: available roles) or future (roles available in the future), and
                   14540: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14541: have active Domain Coordinator role in course's domain or in additional
                   14542: domains (specified in 'Domains to check for privileged users' in course
                   14543: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14544: 
                   14545: =item *
                   14546: 
                   14547: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14548: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14549: $possdomains and $possroles are optional array refs -- to domains to check and
                   14550: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14551: users' roles.db to check for a dc or su role in any domain. This can be
                   14552: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14553: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14554: this then allows &privileged_by_domain() to be used, which caches the identity
                   14555: of privileged users, eliminating the need for repeated calls to &dump().
                   14556: 
                   14557: =item *
                   14558: 
                   14559: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14560: where the outer hash keys are domains specified in the $possdomains array ref,
                   14561: next inner hash keys are privileged roles specified in the $roles array ref,
                   14562: and the innermost hash contains key = value pairs for username:domain = end:start
                   14563: for active or future "privileged" users with that role in that domain. To avoid
                   14564: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14565: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14566: 
1.243     albertel 14567: =back
                   14568: 
                   14569: =head2 User Modification
                   14570: 
                   14571: =over 4
                   14572: 
                   14573: =item *
                   14574: 
1.957     raeburn  14575: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14576: user for the level given by URL.  Optional start and end dates (leave empty
                   14577: string or zero for "no date")
1.191     harris41 14578: 
                   14579: =item *
                   14580: 
1.243     albertel 14581: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14582: change a users, password, possible return values are: ok,
                   14583: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14584: refused
1.191     harris41 14585: 
                   14586: =item *
                   14587: 
1.243     albertel 14588: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14589: 
                   14590: =item *
                   14591: 
1.1058    raeburn  14592: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14593:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14594: 
                   14595: will update user information (firstname,middlename,lastname,generation,
                   14596: permanentemail), and if forceid is true, student/employee ID also.
                   14597: A user's institutional affiliation(s) can also be updated.
                   14598: User information fields will not be overwritten with empty entries 
                   14599: unless the field is included in the $candelete array reference.
                   14600: This array is included when a single user is modified via "Manage Users",
                   14601: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14602: 
                   14603: =item *
                   14604: 
1.286     matthew  14605: modifystudent
                   14606: 
1.957     raeburn  14607: modify a student's enrollment and identification information.
1.1235    raeburn  14608: The course id is resolved based on the current user's environment.  
                   14609: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14610: associated with a course.
                   14611: 
1.297     matthew  14612: This call is essentially a wrapper for lonnet::modifyuser and
                   14613: lonnet::modify_student_enrollment
1.286     matthew  14614: 
                   14615: Inputs: 
                   14616: 
                   14617: =over 4
                   14618: 
1.957     raeburn  14619: =item B<$udom> Student's loncapa domain
1.286     matthew  14620: 
1.957     raeburn  14621: =item B<$uname> Student's loncapa login name
1.286     matthew  14622: 
1.964     bisitz   14623: =item B<$uid> Student/Employee ID
1.286     matthew  14624: 
1.957     raeburn  14625: =item B<$umode> Student's authentication mode
1.286     matthew  14626: 
1.957     raeburn  14627: =item B<$upass> Student's password
1.286     matthew  14628: 
1.957     raeburn  14629: =item B<$first> Student's first name
1.286     matthew  14630: 
1.957     raeburn  14631: =item B<$middle> Student's middle name
1.286     matthew  14632: 
1.957     raeburn  14633: =item B<$last> Student's last name
1.286     matthew  14634: 
1.957     raeburn  14635: =item B<$gene> Student's generation
1.286     matthew  14636: 
1.957     raeburn  14637: =item B<$usec> Student's section in course
1.286     matthew  14638: 
                   14639: =item B<$end> Unix time of the roles expiration
                   14640: 
                   14641: =item B<$start> Unix time of the roles start date
                   14642: 
                   14643: =item B<$forceid> If defined, allow $uid to be changed
                   14644: 
                   14645: =item B<$desiredhome> server to use as home server for student
                   14646: 
1.957     raeburn  14647: =item B<$email> Student's permanent e-mail address
                   14648: 
                   14649: =item B<$type> Type of enrollment (auto or manual)
                   14650: 
1.963     raeburn  14651: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14652: 
                   14653: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14654: 
1.963     raeburn  14655: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14656: 
1.963     raeburn  14657: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14658: 
1.1216    raeburn  14659: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14660: 
                   14661: =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  14662: 
1.286     matthew  14663: =back
1.297     matthew  14664: 
                   14665: =item *
                   14666: 
                   14667: modify_student_enrollment
                   14668: 
1.1235    raeburn  14669: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14670: 'role.request.course' must be defined for this function to proceed.
                   14671: 
                   14672: Inputs:
                   14673: 
                   14674: =over 4
                   14675: 
1.1235    raeburn  14676: =item $udom, student's domain
1.297     matthew  14677: 
1.1235    raeburn  14678: =item $uname, student's name
1.297     matthew  14679: 
1.1235    raeburn  14680: =item $uid, student's user id
1.297     matthew  14681: 
1.1235    raeburn  14682: =item $first, student's first name
1.297     matthew  14683: 
                   14684: =item $middle
                   14685: 
                   14686: =item $last
                   14687: 
                   14688: =item $gene
                   14689: 
                   14690: =item $usec
                   14691: 
                   14692: =item $end
                   14693: 
                   14694: =item $start
                   14695: 
1.957     raeburn  14696: =item $type
                   14697: 
                   14698: =item $locktype
                   14699: 
                   14700: =item $cid
                   14701: 
                   14702: =item $selfenroll
                   14703: 
                   14704: =item $context
                   14705: 
1.1216    raeburn  14706: =item $credits, number of credits student will earn from this class
                   14707: 
1.1314    raeburn  14708: =item $instsec, institutional course section code for student
                   14709: 
1.297     matthew  14710: =back
                   14711: 
1.191     harris41 14712: 
                   14713: =item *
                   14714: 
1.243     albertel 14715: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14716: custom role; give a custom role to a user for the level given by URL.  Specify
                   14717: name and domain of role author, and role name
1.191     harris41 14718: 
                   14719: =item *
                   14720: 
1.243     albertel 14721: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14722: 
                   14723: =item *
                   14724: 
1.243     albertel 14725: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14726: 
                   14727: =back
                   14728: 
                   14729: =head2 Course Infomation
                   14730: 
                   14731: =over 4
1.191     harris41 14732: 
                   14733: =item *
                   14734: 
1.1118    foxr     14735: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14736: specified course id, including all environment settings for the
                   14737: course, the description of the course will be in the hash under the
                   14738: key 'description'
1.191     harris41 14739: 
1.1118    foxr     14740: $options is an optional parameter that if supplied is a hash reference that controls
                   14741: what how this function works.  It has the following key/values:
                   14742: 
                   14743: =over 4
                   14744: 
                   14745: =item freshen_cache
                   14746: 
                   14747: If defined, and the environment cache for the course is valid, it is 
                   14748: returned in the returned hash.
                   14749: 
                   14750: =item one_time
                   14751: 
                   14752: If defined, the last cache time is set to _now_
                   14753: 
                   14754: =item user
                   14755: 
                   14756: If defined, the supplied username is used instead of the current user.
                   14757: 
                   14758: 
                   14759: =back
                   14760: 
1.191     harris41 14761: =item *
                   14762: 
1.624     albertel 14763: resdata($name,$domain,$type,@which) : request for current parameter
                   14764: setting for a specific $type, where $type is either 'course' or 'user',
                   14765: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14766: answers for 10 minutes.
1.243     albertel 14767: 
1.877     foxr     14768: =item *
                   14769: 
                   14770: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14771: data base, returning a hash that is keyed by the resource name and has
                   14772: values that are the resource value.  I believe that the timestamps and
                   14773: versions are also returned.
                   14774: 
1.1236    raeburn  14775: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14776: supplemental content area. This routine caches the number of files for 
                   14777: 10 minutes.
                   14778: 
1.243     albertel 14779: =back
                   14780: 
                   14781: =head2 Course Modification
                   14782: 
                   14783: =over 4
1.191     harris41 14784: 
                   14785: =item *
                   14786: 
1.243     albertel 14787: writecoursepref($courseid,%prefs) : write preferences (environment
                   14788: database) for a course
1.191     harris41 14789: 
                   14790: =item *
                   14791: 
1.1011    raeburn  14792: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14793: 
                   14794: =item *
                   14795: 
1.1038    raeburn  14796: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14797: 
1.1167    droeschl 14798: =item *
                   14799: 
                   14800: is_course($courseid), is_course($cdom, $cnum)
                   14801: 
                   14802: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14803: two component version $cdom, $cnum. It checks if the specified course exists.
                   14804: 
                   14805: Returns:
                   14806:     undef if the course doesn't exist, otherwise
                   14807:     in scalar context the combined courseid.
                   14808:     in list context the two components of the course identifier, domain and 
                   14809:     courseid.    
                   14810: 
1.243     albertel 14811: =back
                   14812: 
                   14813: =head2 Resource Subroutines
                   14814: 
                   14815: =over 4
1.191     harris41 14816: 
                   14817: =item *
                   14818: 
1.243     albertel 14819: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14820: 
                   14821: =item *
                   14822: 
1.243     albertel 14823: repcopy($filename) : subscribes to the requested file, and attempts to
                   14824: replicate from the owning library server, Might return
1.607     raeburn  14825: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14826: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14827: resource. Expects the local filesystem pathname
                   14828: (/home/httpd/html/res/....)
                   14829: 
                   14830: =back
                   14831: 
                   14832: =head2 Resource Information
                   14833: 
                   14834: =over 4
1.191     harris41 14835: 
                   14836: =item *
                   14837: 
1.1228    raeburn  14838: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14839: and returns the value of a variety of different possible values,
                   14840: $varname should be a request string, and the other parameters can be
                   14841: used to specify who and what one is asking about. Ordinarily, $cid 
                   14842: does not need to be specified, as it is retrived from 
                   14843: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14844: within lonuserstate::loadmap() when initializing a course, before
                   14845: $env{'request.course.id'} has been set, so it needs to be provided
                   14846: in that one case.
1.243     albertel 14847: 
                   14848: Possible values for $varname are environment.lastname (or other item
                   14849: from the envirnment hash), user.name (or someother aspect about the
                   14850: user), resource.0.maxtries (or some other part and parameter of a
                   14851: resource)
1.204     albertel 14852: 
                   14853: =item *
                   14854: 
1.243     albertel 14855: directcondval($number) : get current value of a condition; reads from a state
                   14856: string
1.204     albertel 14857: 
                   14858: =item *
                   14859: 
1.243     albertel 14860: condval($condidx) : value of condition index based on state
1.204     albertel 14861: 
                   14862: =item *
                   14863: 
1.1362    raeburn  14864: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 14865: resource's metadata, $what should be either a specific key, or either
                   14866: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  14867: packages that this resource currently uses, the last 3 arguments are 
                   14868: only used internally for recursive metadata.
                   14869: 
                   14870: the toolsymb is only used where the uri is for an external tool (for which
                   14871: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 14872: 
1.1371    raeburn  14873: this function automatically caches all requests except any made recursively
                   14874: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   14875: defined).
1.191     harris41 14876: 
                   14877: =item *
                   14878: 
1.243     albertel 14879: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14880: network of library servers; returns file handle of where SQL and regex results
                   14881: will be stored for query
1.191     harris41 14882: 
                   14883: =item *
                   14884: 
1.1282    raeburn  14885: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14886: return symbolic list entry (all arguments optional). 
                   14887: 
                   14888: Args: filename is the filename (including path) for the file for which a symb 
                   14889: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14890: to check access status if more than one resource was found in the bighash 
                   14891: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14892: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14893: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14894: cause possible symbs to be checked to determine if they are subject to content
                   14895: blocking, if so they will not be included as possible symbs; possibles is a
                   14896: ref to a hash, which, as a side effect, will be populated with all possible 
                   14897: symbs (content blocking not tested).
                   14898:  
1.243     albertel 14899: returns the data handle
1.191     harris41 14900: 
                   14901: =item *
                   14902: 
1.1190    raeburn  14903: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14904: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14905: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14906: on failure, user must be in a course, as it assumes the existence of
                   14907: the course initial hash, and uses $env('request.course.id'}.  The third
                   14908: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14909: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14910: encrypted; otherwise it will be null.  
1.191     harris41 14911: 
                   14912: =item *
                   14913: 
1.243     albertel 14914: symbclean($symb) : removes versions numbers from a symb, returns the
                   14915: cleaned symb
1.191     harris41 14916: 
                   14917: =item *
                   14918: 
1.243     albertel 14919: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14920: course map, user must be in a course for it to work.
1.191     harris41 14921: 
                   14922: =item *
                   14923: 
1.243     albertel 14924: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14925: 
                   14926: =item *
                   14927: 
1.243     albertel 14928: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14929: a random seed, all arguments are optional, if they aren't sent it uses the
                   14930: environment to derive them. Note: if symb isn't sent and it can't get one
                   14931: from &symbread it will use the current time as its return value
1.191     harris41 14932: 
                   14933: =item *
                   14934: 
1.243     albertel 14935: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14936: unfakeable, receipt
1.191     harris41 14937: 
                   14938: =item *
                   14939: 
1.620     albertel 14940: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14941: 
                   14942: =item *
                   14943: 
1.243     albertel 14944: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14945: 
                   14946: =item *
                   14947: 
1.243     albertel 14948: 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 14949: 
                   14950: =item *
                   14951: 
1.243     albertel 14952: 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 14953: 
                   14954: =item *
                   14955: 
1.243     albertel 14956: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14957: 
                   14958: =item *
                   14959: 
1.243     albertel 14960: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14961: forcing spreadsheet to reevaluate the resource scores next time.
                   14962: 
1.1195    raeburn  14963: =item * 
                   14964: 
1.1196    raeburn  14965: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14966: when viewing in course context.
1.1195    raeburn  14967: 
1.1196    raeburn  14968:  input: six args -- filename (decluttered), course number, course domain,
                   14969:                     url, symb (if registered) and group (if this is a 
                   14970:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14971: 
1.1196    raeburn  14972:  output: array of five scalars --
1.1195    raeburn  14973:          $cfile -- url for file editing if editable on current server
                   14974:          $home -- homeserver of resource (i.e., for author if published,
                   14975:                                           or course if uploaded.).
                   14976:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14977:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14978:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14979: 
                   14980: =item *
                   14981: 
                   14982: is_course_upload($file,$cnum,$cdom)
                   14983: 
                   14984: Used in course context to determine if current file was uploaded to 
                   14985: the course (i.e., would be found in /userfiles/docs on the course's 
                   14986: homeserver.
                   14987: 
                   14988:   input: 3 args -- filename (decluttered), course number and course domain.
                   14989:   output: boolean -- 1 if file was uploaded.
                   14990: 
1.243     albertel 14991: =back
                   14992: 
                   14993: =head2 Storing/Retreiving Data
                   14994: 
                   14995: =over 4
1.191     harris41 14996: 
                   14997: =item *
                   14998: 
1.1269    raeburn  14999: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15000: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15001: the remaining args aren't required and if they aren't passed or are '' they will
                   15002: be derived from the env (with the exception of $laststore, which is an 
                   15003: optional arg used when a user's submission is stored in grading).
                   15004: $laststore is $version=$timestamp, where $version is the most recent version
                   15005: number retrieved for the corresponding $symb in the $namespace db file, and
                   15006: $timestamp is the timestamp for that transaction (UNIX time).
                   15007: $laststore is currently only passed when cstore() is called by 
                   15008: structuretags::finalize_storage().
1.191     harris41 15009: 
                   15010: =item *
                   15011: 
1.1269    raeburn  15012: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15013: but uses critical subroutine
1.191     harris41 15014: 
                   15015: =item *
                   15016: 
1.243     albertel 15017: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15018: all args are optional
1.191     harris41 15019: 
                   15020: =item *
                   15021: 
1.717     albertel 15022: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15023: dumps the complete (or key matching regexp) namespace into a hash
                   15024: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15025: normally &store()ed into
                   15026: 
                   15027: $range should be either an integer '100' (give me the first 100
                   15028:                                            matching records)
                   15029:               or be  two integers sperated by a - with no spaces
                   15030:                  '30-50' (give me the 30th through the 50th matching
                   15031:                           records)
                   15032: 
                   15033: 
                   15034: =item *
                   15035: 
1.1269    raeburn  15036: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15037: replaces a &store() version of data with a replacement set of data
                   15038: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15039: reference. If $tolog is true, the transaction is logged in the courselog
                   15040: with an action=PUTSTORE.
1.717     albertel 15041: 
                   15042: =item *
                   15043: 
1.243     albertel 15044: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15045: works very similar to store/cstore, but all data is stored in a
                   15046: temporary location and can be reset using tmpreset, $storehash should
                   15047: be a hash reference, returns nothing on success
1.191     harris41 15048: 
                   15049: =item *
                   15050: 
1.243     albertel 15051: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15052: similar to restore, but all data is stored in a temporary location and
                   15053: can be reset using tmpreset. Returns a hash of values on success,
                   15054: error string otherwise.
1.191     harris41 15055: 
                   15056: =item *
                   15057: 
1.243     albertel 15058: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15059: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15060: 
                   15061: =item *
                   15062: 
1.243     albertel 15063: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15064: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15065: 
                   15066: =item *
                   15067: 
1.243     albertel 15068: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15069: namesp ($udom and $uname are optional)
1.191     harris41 15070: 
                   15071: =item *
                   15072: 
1.702     albertel 15073: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15074: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15075: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15076: 
1.702     albertel 15077: $range should be either an integer '100' (give me the first 100
                   15078:                                            matching records)
                   15079:               or be  two integers sperated by a - with no spaces
                   15080:                  '30-50' (give me the 30th through the 50th matching
                   15081:                           records)
1.449     matthew  15082: =item *
                   15083: 
                   15084: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15085: $store can be a scalar, an array reference, or if the amount to be 
                   15086: incremented is > 1, a hash reference.
                   15087: 
                   15088: ($udom and $uname are optional)
1.191     harris41 15089: 
                   15090: =item *
                   15091: 
1.243     albertel 15092: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15093: ($udom and $uname are optional)
1.191     harris41 15094: 
                   15095: =item *
                   15096: 
1.243     albertel 15097: cput($namespace,$storehash,$udom,$uname) : critical put
                   15098: ($udom and $uname are optional)
1.191     harris41 15099: 
                   15100: =item *
                   15101: 
1.748     albertel 15102: newput($namespace,$storehash,$udom,$uname) :
                   15103: 
                   15104: Attempts to store the items in the $storehash, but only if they don't
                   15105: currently exist, if this succeeds you can be certain that you have 
                   15106: successfully created a new key value pair in the $namespace db.
                   15107: 
                   15108: 
                   15109: Args:
                   15110:  $namespace: name of database to store values to
                   15111:  $storehash: hashref to store to the db
                   15112:  $udom: (optional) domain of user containing the db
                   15113:  $uname: (optional) name of user caontaining the db
                   15114: 
                   15115: Returns:
                   15116:  'ok' -> succeeded in storing all keys of $storehash
                   15117:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15118:                         least <key> already existed in the db (other
                   15119:                         requested keys may also already exist)
1.967     bisitz   15120:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15121:  'con_lost' -> unable to contact request server
                   15122:  'refused' -> action was not allowed by remote machine
                   15123: 
                   15124: 
                   15125: =item *
                   15126: 
1.243     albertel 15127: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15128: reference filled in from namesp (encrypts the return communication)
                   15129: ($udom and $uname are optional)
1.191     harris41 15130: 
                   15131: =item *
                   15132: 
1.243     albertel 15133: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15134: critical subroutine
                   15135: 
1.806     raeburn  15136: =item *
                   15137: 
1.860     raeburn  15138: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15139: array reference filled in from namespace found in domain level on either
                   15140: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15141: 
                   15142: =item *
                   15143: 
1.860     raeburn  15144: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15145: domain level either on specified domain server ($uhome) or primary domain 
                   15146: server ($udom and $uhome are optional)
1.806     raeburn  15147: 
1.943     raeburn  15148: =item * 
                   15149: 
1.1240    raeburn  15150: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15151: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15152: the target domain.
                   15153: 
                   15154: May also include additional key => value pairs for the following groups:
                   15155: 
                   15156: =over
                   15157: 
                   15158: =item
                   15159: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15160: 
                   15161: =over
                   15162: 
                   15163: =item defaultquota, authorquota
                   15164: 
                   15165: =back
                   15166: 
                   15167: =item
                   15168: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15169: portfolio for users).
                   15170: 
                   15171: =over
                   15172: 
                   15173: =item
                   15174: aboutme, blog, webdav, portfolio
                   15175: 
                   15176: =back
                   15177: 
                   15178: =item
                   15179: requestcourses: ability to request courses, and how requests are processed.
                   15180: 
                   15181: =over
                   15182: 
                   15183: =item
1.1305    raeburn  15184: official, unofficial, community, textbook, placement
1.1240    raeburn  15185: 
                   15186: =back
                   15187: 
                   15188: =item
                   15189: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15190: 
                   15191: =over
                   15192: 
                   15193: =item
1.1256    raeburn  15194: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15195: 
                   15196: =back
                   15197: 
                   15198: =item
                   15199: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15200: for course's uploaded content.
                   15201: 
                   15202: =over
                   15203: 
                   15204: =item
1.1246    raeburn  15205: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15206: communityquota, textbookquota, placementquota
1.1240    raeburn  15207: 
                   15208: =back
                   15209: 
                   15210: =item
                   15211: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15212: on your servers.
                   15213: 
                   15214: =over
                   15215: 
                   15216: =item 
                   15217: remotesessions, hostedsessions
                   15218: 
                   15219: =back
                   15220: 
                   15221: =back
                   15222: 
                   15223: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15224: utility to create a configuration.db file on a domain's primary library server 
                   15225: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15226: -- corresponding values are authentication type (internal, krb4, krb5,
                   15227: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15228: will be available. Values are retrieved from cache (if current), unless the
                   15229: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15230: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15231: 
                   15232: Typical usage:
1.943     raeburn  15233: 
1.1240    raeburn  15234: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15235: 
1.243     albertel 15236: =back
                   15237: 
                   15238: =head2 Network Status Functions
                   15239: 
                   15240: =over 4
1.191     harris41 15241: 
                   15242: =item *
                   15243: 
1.1137    raeburn  15244: dirlist() : return directory list based on URI (first arg).
                   15245: 
                   15246: Inputs: 1 required, 5 optional.
                   15247: 
                   15248: =over
                   15249: 
                   15250: =item 
                   15251: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15252: 
                   15253: =item
                   15254: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15255: 
                   15256: =item
                   15257: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15258: 
                   15259: =item
                   15260: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15261: 
                   15262: =item
                   15263: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15264: 
                   15265: =item 
                   15266: $alternateRoot - path to prepend in place of path from $uri.
                   15267: 
                   15268: =back
                   15269: 
                   15270: Returns: Array of up to two items.
                   15271: 
                   15272: =over
                   15273: 
                   15274: a reference to an array of files/subdirectories
                   15275: 
                   15276: =over
                   15277: 
                   15278: Each element in the array of files/subdirectories is a & separated list of
                   15279: item name and the result of running stat on the item.  If dirlist was requested
                   15280: for a file instead of a directory, the item name will be ''. For a directory 
                   15281: listing, if the item is a metadata file, the element will end &N&M 
                   15282: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15283: default copyright set (1).  
                   15284: 
                   15285: =back
                   15286: 
                   15287: a scalar containing error condition (if encountered).
                   15288: 
                   15289: =over
                   15290: 
                   15291: =item 
                   15292: no_host (no homeserver identified for $username:$domain).
                   15293: 
                   15294: =item 
                   15295: no_such_host (server contacted for listing not identified as valid host).
                   15296: 
                   15297: =item 
                   15298: con_lost (connection to remote server failed).
                   15299: 
                   15300: =item 
                   15301: refused (invalid $username:$domain received on lond side).
                   15302: 
                   15303: =item 
                   15304: no_such_dir (directory at specified path on lond side does not exist). 
                   15305: 
                   15306: =item 
                   15307: empty (directory at specified path on lond side is empty).
                   15308: 
                   15309: =over
                   15310: 
                   15311: This is currently not encountered because the &ls3, &ls2, 
                   15312: &ls (_handler) routines on the lond side do not filter out
                   15313: . and .. from a directory listing. 
                   15314: 
                   15315: =back
                   15316: 
                   15317: =back
                   15318: 
                   15319: =back
1.191     harris41 15320: 
                   15321: =item *
                   15322: 
1.243     albertel 15323: spareserver() : find server with least workload from spare.tab
                   15324: 
1.986     foxr     15325: 
                   15326: =item *
                   15327: 
                   15328: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15329: if there is no corresponding loncapa host.
                   15330: 
1.243     albertel 15331: =back
                   15332: 
1.986     foxr     15333: 
1.243     albertel 15334: =head2 Apache Request
                   15335: 
                   15336: =over 4
1.191     harris41 15337: 
                   15338: =item *
                   15339: 
1.243     albertel 15340: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15341: localhost, posts hash
                   15342: 
                   15343: =back
                   15344: 
                   15345: =head2 Data to String to Data
                   15346: 
                   15347: =over 4
1.191     harris41 15348: 
                   15349: =item *
                   15350: 
1.243     albertel 15351: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15352: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15353: 
                   15354: =item *
                   15355: 
1.243     albertel 15356: hashref2str($hashref) : convert a hashref into a string complete with
                   15357: escaping and '=' and '&' separators, supports elements that are
                   15358: arrayrefs and hashrefs
1.191     harris41 15359: 
                   15360: =item *
                   15361: 
1.243     albertel 15362: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15363: with escaping and '&' separators, supports elements that are arrayrefs
                   15364: and hashrefs
1.191     harris41 15365: 
                   15366: =item *
                   15367: 
1.243     albertel 15368: str2hash($string) : convert string to hash using unescaping and
                   15369: splitting on '=' and '&', supports elements that are arrayrefs and
                   15370: hashrefs
1.191     harris41 15371: 
                   15372: =item *
                   15373: 
1.243     albertel 15374: str2array($string) : convert string to hash using unescaping and
                   15375: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15376: 
                   15377: =back
                   15378: 
                   15379: =head2 Logging Routines
                   15380: 
                   15381: 
                   15382: These routines allow one to make log messages in the lonnet.log and
                   15383: lonnet.perm logfiles.
1.191     harris41 15384: 
1.1119    foxr     15385: =over 4
                   15386: 
1.191     harris41 15387: =item *
                   15388: 
1.243     albertel 15389: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15390: 
                   15391: =item *
                   15392: 
1.243     albertel 15393: logthis() : append message to the normal lonnet.log file, it gets
                   15394: preiodically rolled over and deleted.
1.191     harris41 15395: 
                   15396: =item *
                   15397: 
1.243     albertel 15398: logperm() : append a permanent message to lonnet.perm.log, this log
                   15399: file never gets deleted by any automated portion of the system, only
                   15400: messages of critical importance should go in here.
                   15401: 
1.1119    foxr     15402: 
1.243     albertel 15403: =back
                   15404: 
                   15405: =head2 General File Helper Routines
                   15406: 
                   15407: =over 4
1.191     harris41 15408: 
                   15409: =item *
                   15410: 
1.481     raeburn  15411: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15412: (a) files in /uploaded
                   15413:   (i) If a local copy of the file exists - 
                   15414:       compares modification date of local copy with last-modified date for 
                   15415:       definitive version stored on home server for course. If local copy is 
                   15416:       stale, requests a new version from the home server and stores it. 
                   15417:       If the original has been removed from the home server, then local copy 
                   15418:       is unlinked.
                   15419:   (ii) If local copy does not exist -
                   15420:       requests the file from the home server and stores it. 
                   15421:   
                   15422:   If $caller is 'uploadrep':  
                   15423:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15424:     for request for files originally uploaded via DOCS. 
                   15425:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15426:   
                   15427:   Otherwise:
                   15428:      This indicates a call from the content generation phase of the request.
                   15429:      -  returns the entire contents of the file or -1.
                   15430:      
                   15431: (b) files in /res
                   15432:    - returns the entire contents of a file or -1; 
                   15433:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15434: 
1.712     albertel 15435: 
                   15436: =item *
                   15437: 
                   15438: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15439:                   reference
                   15440: 
                   15441: returns either a stat() list of data about the file or an empty list
                   15442: if the file doesn't exist or couldn't find out about it (connection
                   15443: problems or user unknown)
                   15444: 
1.191     harris41 15445: =item *
                   15446: 
1.243     albertel 15447: filelocation($dir,$file) : returns file system location of a file
                   15448: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15449: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15450: and a file of ../bob will become /a/bob)
1.191     harris41 15451: 
                   15452: =item *
                   15453: 
                   15454: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15455: filelocation except for hrefs
                   15456: 
                   15457: =item *
                   15458: 
1.1261    raeburn  15459: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15460: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15461: 
1.243     albertel 15462: =back
                   15463: 
1.608     albertel 15464: =head2 Usererfile file routines (/uploaded*)
                   15465: 
                   15466: =over 4
                   15467: 
                   15468: =item *
                   15469: 
                   15470: userfileupload(): main rotine for putting a file in a user or course's
                   15471:                   filespace, arguments are,
                   15472: 
1.620     albertel 15473:  formname - required - this is the name of the element in $env where the
1.608     albertel 15474:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15475:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15476:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15477:  context - if coursedoc, store the file in the course of the active role
                   15478:              of the current user; 
                   15479:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15480:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15481:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15482:          if undefined, it will be placed in "unknown"
                   15483: 
                   15484:  (This routine calls clean_filename() to remove any dangerous
                   15485:  characters from the filename, and then calls finuserfileupload() to
                   15486:  complete the transaction)
                   15487: 
                   15488:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15489:  and /adm/notfound.html if unsuccessful
                   15490: 
                   15491: =item *
                   15492: 
                   15493: clean_filename(): routine for cleaing a filename up for storage in
                   15494:                  userfile space, argument is:
                   15495: 
                   15496:  filename - proposed filename
                   15497: 
                   15498: returns: the new clean filename
                   15499: 
                   15500: =item *
                   15501: 
1.1090    raeburn  15502: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15503: userspace, probably shouldn't be called directly
                   15504: 
                   15505:   docuname: username or courseid of destination for the file
                   15506:   docudom: domain of user/course of destination for the file
                   15507:   formname: same as for userfileupload()
1.1090    raeburn  15508:   fname: filename (including subdirectories) for the file
                   15509:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15510:   allfiles: reference to hash used to store objects found by parser
                   15511:   codebase: reference to hash used for codebases of java objects found by parser
                   15512:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15513:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15514:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15515:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15516:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15517:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15518:   mimetype: reference to scalar to accommodate mime type determined
                   15519:             from File::MMagic if $parser = parse.
1.608     albertel 15520: 
                   15521:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15522:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15523:  was 'overwrite').
                   15524:  
1.608     albertel 15525: 
                   15526: =item *
                   15527: 
                   15528: renameuserfile(): renames an existing userfile to a new name
                   15529: 
                   15530:   Args:
                   15531:    docuname: username or courseid of destination for the file
                   15532:    docudom: domain of user/course of destination for the file
                   15533:    old: current file name (including any subdirs under userfiles)
                   15534:    new: desired file name (including any subdirs under userfiles)
                   15535: 
                   15536: =item *
                   15537: 
                   15538: mkdiruserfile(): creates a directory is a userfiles dir
                   15539: 
                   15540:   Args:
                   15541:    docuname: username or courseid of destination for the file
                   15542:    docudom: domain of user/course of destination for the file
                   15543:    dir: dir to create (including any subdirs under userfiles)
                   15544: 
                   15545: =item *
                   15546: 
                   15547: removeuserfile(): removes a file that exists in userfiles
                   15548: 
                   15549:   Args:
                   15550:    docuname: username or courseid of destination for the file
                   15551:    docudom: domain of user/course of destination for the file
                   15552:    fname: filname to delete (including any subdirs under userfiles)
                   15553: 
                   15554: =item *
                   15555: 
                   15556: removeuploadedurl(): convience function for removeuserfile()
                   15557: 
                   15558:   Args:
                   15559:    url:  a full /uploaded/... url to delete
                   15560: 
1.747     albertel 15561: =item * 
                   15562: 
                   15563: get_portfile_permissions():
                   15564:   Args:
                   15565:     domain: domain of user or course contain the portfolio files
                   15566:     user: name of user or num of course contain the portfolio files
                   15567:   Returns:
                   15568:     hashref of a dump of the proper file_permissions.db
                   15569:    
                   15570: 
                   15571: =item * 
                   15572: 
                   15573: get_access_controls():
                   15574: 
                   15575: Args:
                   15576:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15577:   group: (optional) the group you want the files associated with
                   15578:   file: (optional) the file you want access info on
                   15579: 
                   15580: Returns:
1.749     raeburn  15581:     a hash (keys are file names) of hashes containing
                   15582:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15583:         values are XML containing access control settings (see below) 
1.747     albertel 15584: 
                   15585: Internal notes:
                   15586: 
1.749     raeburn  15587:  access controls are stored in file_permissions.db as key=value pairs.
                   15588:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15589:         where scope -> public,guest,course,group,domains or users.
                   15590:               end -> UNIX time for end of access (0 -> no end date)
                   15591:               start -> UNIX time for start of access
                   15592: 
                   15593:     value -> XML description of access control
                   15594:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15595:             <start></start>
                   15596:             <end></end>
                   15597: 
                   15598:             <password></password>  for scope type = guest
                   15599: 
                   15600:             <domain></domain>     for scope type = course or group
                   15601:             <number></number>
                   15602:             <roles id="">
                   15603:              <role></role>
                   15604:              <access></access>
                   15605:              <section></section>
                   15606:              <group></group>
                   15607:             </roles>
                   15608: 
                   15609:             <dom></dom>         for scope type = domains
                   15610: 
                   15611:             <users>             for scope type = users
                   15612:              <user>
                   15613:               <uname></uname>
                   15614:               <udom></udom>
                   15615:              </user>
                   15616:             </users>
                   15617:            </scope> 
                   15618:               
                   15619:  Access data is also aggregated for each file in an additional key=value pair:
                   15620:  key -> path to file/file_name\0accesscontrol 
                   15621:  value -> reference to hash
                   15622:           hash contains key = value pairs
                   15623:           where key = uniqueID:scope_end_start
                   15624:                 value = UNIX time record was last updated
                   15625: 
                   15626:           Used to improve speed of look-ups of access controls for each file.  
                   15627:  
                   15628:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15629: 
1.1198    raeburn  15630: =item *
                   15631: 
1.749     raeburn  15632: modify_access_controls():
                   15633: 
                   15634: Modifies access controls for a portfolio file
                   15635: Args
                   15636: 1. file name
                   15637: 2. reference to hash of required changes,
                   15638: 3. domain
                   15639: 4. username
                   15640:   where domain,username are the domain of the portfolio owner 
                   15641:   (either a user or a course) 
                   15642: 
                   15643: Returns:
                   15644: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15645: 2. result of deletions ('ok' or 'error', with error message).
                   15646: 3. reference to hash of any new or updated access controls.
                   15647: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15648:    key = integer (inbound ID)
1.1198    raeburn  15649:    value = uniqueID
                   15650: 
                   15651: =item *
                   15652: 
                   15653: get_timebased_id():
                   15654: 
                   15655: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15656: course via the Course Editor (e.g., folders, composite pages, 
                   15657: group bulletin boards).
                   15658: 
                   15659: Args: (first three required; six others optional)
                   15660: 
                   15661: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15662:    docssequence, or name of group
                   15663: 
                   15664: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15665:    e.g., num, boardids
                   15666: 
                   15667: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15668:    file will be named nohist_namespace.db
                   15669: 
                   15670: 4. cdom: domain of course; default is current course domain from %env
                   15671: 
                   15672: 5. cnum: course number; default is current course number from %env
                   15673: 
                   15674: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15675:    unix timestamp to form the suffix, if the plain timestamp is already
                   15676:    in use.  Default is to not do this, but simply increment the unix 
                   15677:    timestamp by 1 until a unique key is obtained.
                   15678: 
                   15679: 7. who: holder of locking key; defaults to user:domain for user.
                   15680: 
                   15681: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15682:    retrying); default is 3.
                   15683: 
                   15684: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15685: 
                   15686: Returns:
                   15687: 
                   15688: 1. suffix obtained (numeric)
                   15689: 
                   15690: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15691: 
                   15692: 3. error: contains (localized) error message if an error occurred.
                   15693: 
1.747     albertel 15694: 
1.608     albertel 15695: =back
                   15696: 
1.243     albertel 15697: =head2 HTTP Helper Routines
                   15698: 
                   15699: =over 4
                   15700: 
1.191     harris41 15701: =item *
                   15702: 
                   15703: escape() : unpack non-word characters into CGI-compatible hex codes
                   15704: 
                   15705: =item *
                   15706: 
                   15707: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15708: 
1.243     albertel 15709: =back
                   15710: 
                   15711: =head1 PRIVATE SUBROUTINES
                   15712: 
                   15713: =head2 Underlying communication routines (Shouldn't call)
                   15714: 
                   15715: =over 4
                   15716: 
                   15717: =item *
                   15718: 
                   15719: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15720: 
                   15721: =item *
                   15722: 
                   15723: reply() : uses subreply to send a message to remote machine, logs all failures
                   15724: 
                   15725: =item *
                   15726: 
                   15727: critical() : passes a critical message to another server; if cannot
                   15728: get through then place message in connection buffer directory and
                   15729: returns con_delayed, if incapable of saving message, returns
                   15730: con_failed
                   15731: 
                   15732: =item *
                   15733: 
                   15734: reconlonc() : tries to reconnect lonc client processes.
                   15735: 
                   15736: =back
                   15737: 
                   15738: =head2 Resource Access Logging
                   15739: 
                   15740: =over 4
                   15741: 
                   15742: =item *
                   15743: 
                   15744: flushcourselogs() : flush (save) buffer logs and access logs
                   15745: 
                   15746: =item *
                   15747: 
                   15748: courselog($what) : save message for course in hash
                   15749: 
                   15750: =item *
                   15751: 
                   15752: courseacclog($what) : save message for course using &courselog().  Perform
                   15753: special processing for specific resource types (problems, exams, quizzes, etc).
                   15754: 
1.191     harris41 15755: =item *
                   15756: 
                   15757: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15758: as a PerlChildExitHandler
1.243     albertel 15759: 
                   15760: =back
                   15761: 
                   15762: =head2 Other
                   15763: 
                   15764: =over 4
                   15765: 
                   15766: =item *
                   15767: 
                   15768: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15769: 
                   15770: =back
                   15771: 
                   15772: =cut
1.877     foxr     15773: 

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