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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1340  ! raeburn     4: # $Id: lonnet.pm,v 1.1339 2017/02/28 05:42:12 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1182    foxr       78: 
1.1173    foxr       79: use Encode;
                     80: 
1.1245    raeburn    81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    82:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     83:             %managerstab);
1.871     albertel   84: 
                     85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     86:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     87:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        88:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        89: 
1.1       albertel   90: use IO::Socket;
1.31      www        91: use GDBM_File;
1.208     albertel   92: use HTML::LCParser;
1.88      www        93: use Fcntl qw(:flock);
1.870     albertel   94: use Storable qw(thaw nfreeze);
1.1289    damieng    95: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   96: use Cache::Memcached;
1.676     albertel   97: use Digest::MD5;
1.790     albertel   98: use Math::Random;
1.1024    raeburn    99: use File::MMagic;
1.807     albertel  100: use LONCAPA qw(:DEFAULT :match);
1.740     www       101: use LONCAPA::Configuration;
1.1160    www       102: use LONCAPA::lonmetadata;
1.1167    droeschl  103: use LONCAPA::Lond;
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") {	
                    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.448     albertel  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.448     albertel  174:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    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:             }
                    246:         }
                    247:     }
                    248:     if ($uselocal) {
                    249:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
                    250:     } else {
                    251:         $rep=&reply('servercerts',$lonhost);
                    252:     }
                    253:     my ($result,%returnhash);
                    254:     if (defined($lonhost)) {
                    255:         if (!defined(&hostname($lonhost))) {
                    256:             return;
                    257:         }
                    258:     }
                    259:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    260:         ($rep eq 'unknown_cmd')) {
                    261:         $result = $rep;
                    262:     } else {
                    263:         $result = 'ok';
                    264:         my @pairs=split(/\&/,$rep);
                    265:         foreach my $item (@pairs) {
                    266:             my ($key,$value)=split(/=/,$item,2);
                    267:             my $what = &unescape($key);
                    268:             $returnhash{$what}=&thaw_unescape($value);
                    269:         }
                    270:     }
                    271:     return ($result,\%returnhash);
                    272: }
                    273: 
1.993     raeburn   274: sub get_server_loncaparev {
1.1073    raeburn   275:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   276:     if (defined($lonhost)) {
                    277:         if (!defined(&hostname($lonhost))) {
                    278:             undef($lonhost);
                    279:         }
                    280:     }
                    281:     if (!defined($lonhost)) {
                    282:         if (defined(&domain($dom,'primary'))) {
                    283:             $lonhost=&domain($dom,'primary');
                    284:             if ($lonhost eq 'no_host') {
                    285:                 undef($lonhost);
                    286:             }
                    287:         }
                    288:     }
                    289:     if (defined($lonhost)) {
1.1073    raeburn   290:         my $cachetime = 12*3600;
                    291:         if (!$ignore_cache) {
                    292:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    293:             if (defined($cached)) {
                    294:                 return $loncaparev;
                    295:             }
                    296:         }
                    297:         my ($answer,$loncaparev);
                    298:         my @ids=&current_machine_ids();
                    299:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    300:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   301:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   302:                 $loncaparev = $1;
                    303:             }
                    304:         } else {
                    305:             $answer = &reply('serverloncaparev',$lonhost);
                    306:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    307:                 if ($caller eq 'loncron') {
                    308:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   309:                     $ua->timeout(4);
1.1073    raeburn   310:                     my $protocol = $protocol{$lonhost};
                    311:                     $protocol = 'http' if ($protocol ne 'https');
                    312:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    313:                     my $request=new HTTP::Request('GET',$url);
                    314:                     my $response=$ua->request($request);
                    315:                     unless ($response->is_error()) {
                    316:                         my $content = $response->content;
1.1081    raeburn   317:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   318:                             $loncaparev = $1;
                    319:                         }
                    320:                     }
                    321:                 } else {
                    322:                     $loncaparev = $loncaparevs{$lonhost};
                    323:                 }
1.1081    raeburn   324:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   325:                 $loncaparev = $1;
                    326:             }
1.993     raeburn   327:         }
1.1073    raeburn   328:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   329:     }
                    330: }
                    331: 
1.1074    raeburn   332: sub get_server_homeID {
                    333:     my ($hostname,$ignore_cache,$caller) = @_;
                    334:     unless ($ignore_cache) {
                    335:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    336:         if (defined($cached)) {
                    337:             return $serverhomeID;
                    338:         }
                    339:     }
                    340:     my $cachetime = 12*3600;
                    341:     my $serverhomeID;
                    342:     if ($caller eq 'loncron') { 
                    343:         my @machine_ids = &machine_ids($hostname);
                    344:         foreach my $id (@machine_ids) {
                    345:             my $response = &reply('serverhomeID',$id);
                    346:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    347:                 $serverhomeID = $response;
                    348:                 last;
                    349:             }
                    350:         }
                    351:         if ($serverhomeID eq '') {
                    352:             $serverhomeID = $machine_ids[-1];
                    353:         }
                    354:     } else {
                    355:         $serverhomeID = $serverhomeIDs{$hostname};
                    356:     }
                    357:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    358: }
                    359: 
1.1121    raeburn   360: sub get_remote_globals {
                    361:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   362:     my ($result,%returnhash,%whatneeded);
                    363:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   364:         foreach my $what (sort(keys(%{$whathash}))) {
                    365:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   366:             my ($response,$cached);
1.1121    raeburn   367:             unless ($ignore_cache) {
1.1125    raeburn   368:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   369:             }
                    370:             if (defined($cached)) {
1.1125    raeburn   371:                 $returnhash{$what} = $response;
1.1121    raeburn   372:             } else {
1.1125    raeburn   373:                 $whatneeded{$what} = 1;
1.1121    raeburn   374:             }
                    375:         }
1.1125    raeburn   376:         if (keys(%whatneeded) == 0) {
                    377:             $result = 'ok';
                    378:         } else {
1.1121    raeburn   379:             my $requested = &freeze_escape(\%whatneeded);
                    380:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   381:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    382:                 ($rep eq 'unknown_cmd')) {
                    383:                 $result = $rep;
                    384:             } else {
                    385:                 $result = 'ok';
1.1121    raeburn   386:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   387:                 foreach my $item (@pairs) {
                    388:                     my ($key,$value)=split(/=/,$item,2);
                    389:                     my $what = &unescape($key);
                    390:                     my $hashid = $lonhost.'-'.$what;
                    391:                     $returnhash{$what}=&thaw_unescape($value);
                    392:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   393:                 }
                    394:             }
                    395:         }
                    396:     }
1.1125    raeburn   397:     return ($result,\%returnhash);
1.1121    raeburn   398: }
                    399: 
1.1124    raeburn   400: sub remote_devalidate_cache {
1.1241    raeburn   401:     my ($lonhost,$cachekeys) = @_;
                    402:     my $items;
                    403:     return unless (ref($cachekeys) eq 'ARRAY');
                    404:     my $cachestr = join('&',@{$cachekeys});
                    405:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   406:     return $response;
                    407: }
                    408: 
1.1       albertel  409: # -------------------------------------------------- Non-critical communication
                    410: sub subreply {
                    411:     my ($cmd,$server)=@_;
1.838     albertel  412:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      413:     #
                    414:     #  With loncnew process trimming, there's a timing hole between lonc server
                    415:     #  process exit and the master server picking up the listen on the AF_UNIX
                    416:     #  socket.  In that time interval, a lock file will exist:
                    417: 
                    418:     my $lockfile=$peerfile.".lock";
                    419:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   420: 	sleep(0.1);
1.549     foxr      421:     }
                    422:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      423:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      424:     #
1.550     foxr      425:     #   We'll give the connection a few tries before abandoning it.  If
                    426:     #   connection is not possible, we'll con_lost back to the client.
                    427:     #   
                    428:     my $client;
                    429:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    430: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    431: 				      Type    => SOCK_STREAM,
                    432: 				      Timeout => 10);
1.869     albertel  433: 	if ($client) {
1.550     foxr      434: 	    last;		# Connected!
1.850     albertel  435: 	} else {
1.853     albertel  436: 	    &create_connection(&hostname($server),$server);
1.550     foxr      437: 	}
1.1289    damieng   438:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      439:     }
                    440:     my $answer;
                    441:     if ($client) {
1.704     albertel  442: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      443: 	$answer=<$client>;
                    444: 	if (!$answer) { $answer="con_lost"; }
                    445: 	chomp($answer);
                    446:     } else {
                    447: 	$answer = 'con_lost';	# Failed connection.
                    448:     }
1.1       albertel  449:     return $answer;
                    450: }
                    451: 
                    452: sub reply {
                    453:     my ($cmd,$server)=@_;
1.838     albertel  454:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  455:     my $answer=subreply($cmd,$server);
1.65      www       456:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  457:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       458:                 " $cmd to $server returned $answer</font>");
                    459:     }
1.1       albertel  460:     return $answer;
                    461: }
                    462: 
                    463: # ----------------------------------------------------------- Send USR1 to lonc
                    464: 
                    465: sub reconlonc {
1.891     albertel  466:     my ($lonid) = @_;
                    467:     if ($lonid) {
1.1295    raeburn   468:         my $hostname = &hostname($lonid);
1.891     albertel  469: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    470: 	if ($hostname && -e $peerfile) {
                    471: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    472: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    473: 					     Type    => SOCK_STREAM,
                    474: 					     Timeout => 10);
                    475: 	    if ($client) {
                    476: 		print $client ("reset_retries\n");
                    477: 		my $answer=<$client>;
                    478: 		#reset just this one.
                    479: 	    }
                    480: 	}
                    481: 	return;
                    482:     }
                    483: 
1.836     www       484:     &logthis("Trying to reconnect lonc");
1.1       albertel  485:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  486:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  487: 	my $loncpid=<$fh>;
                    488:         chomp($loncpid);
                    489:         if (kill 0 => $loncpid) {
                    490: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    491:             kill USR1 => $loncpid;
                    492:             sleep 1;
1.1295    raeburn   493:         } else {
1.12      www       494: 	    &logthis(
1.672     albertel  495:                "<font color=\"blue\">WARNING:".
1.12      www       496:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  497:         }
                    498:     } else {
1.836     www       499: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  500:     }
                    501: }
                    502: 
                    503: # ------------------------------------------------------ Critical communication
1.12      www       504: 
1.1       albertel  505: sub critical {
                    506:     my ($cmd,$server)=@_;
1.838     albertel  507:     unless (&hostname($server)) {
1.672     albertel  508:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       509:                " Critical message to unknown server ($server)</font>");
                    510:         return 'no_such_host';
                    511:     }
1.1       albertel  512:     my $answer=reply($cmd,$server);
                    513:     if ($answer eq 'con_lost') {
1.1295    raeburn   514: 	&reconlonc($server);
1.589     albertel  515: 	my $answer=reply($cmd,$server);
1.1       albertel  516:         if ($answer eq 'con_lost') {
                    517:             my $now=time;
                    518:             my $middlename=$cmd;
1.5       www       519:             $middlename=substr($middlename,0,16);
1.1       albertel  520:             $middlename=~s/\W//g;
                    521:             my $dfilename=
1.305     www       522:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    523:             $dumpcount++;
1.1       albertel  524:             {
1.448     albertel  525: 		my $dfh;
                    526: 		if (open($dfh,">$dfilename")) {
                    527: 		    print $dfh "$cmd\n"; 
                    528: 		    close($dfh);
                    529: 		}
1.1       albertel  530:             }
1.1288    damieng   531:             sleep 1;
1.1       albertel  532:             my $wcmd='';
                    533:             {
1.448     albertel  534: 		my $dfh;
                    535: 		if (open($dfh,"<$dfilename")) {
                    536: 		    $wcmd=<$dfh>; 
                    537: 		    close($dfh);
                    538: 		}
1.1       albertel  539:             }
                    540:             chomp($wcmd);
1.7       www       541:             if ($wcmd eq $cmd) {
1.672     albertel  542: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       543:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  544:                 &logperm("D:$server:$cmd");
                    545: 	        return 'con_delayed';
                    546:             } else {
1.672     albertel  547:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       548:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  549:                 &logperm("F:$server:$cmd");
                    550:                 return 'con_failed';
                    551:             }
                    552:         }
                    553:     }
                    554:     return $answer;
1.405     albertel  555: }
                    556: 
1.755     albertel  557: # ------------------------------------------- check if return value is an error
                    558: 
                    559: sub error {
                    560:     my ($result) = @_;
1.756     albertel  561:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  562: 	if ($2 == 2) { return undef; }
                    563: 	return $1;
                    564:     }
                    565:     return undef;
                    566: }
                    567: 
1.783     albertel  568: sub convert_and_load_session_env {
                    569:     my ($lonidsdir,$handle)=@_;
                    570:     my @profile;
                    571:     {
1.917     albertel  572: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    573: 	if (!$opened) {
1.915     albertel  574: 	    return 0;
                    575: 	}
1.783     albertel  576: 	flock($idf,LOCK_SH);
                    577: 	@profile=<$idf>;
                    578: 	close($idf);
                    579:     }
                    580:     my %temp_env;
                    581:     foreach my $line (@profile) {
1.786     albertel  582: 	if ($line !~ m/=/) {
                    583: 	    return 0;
                    584: 	}
1.783     albertel  585: 	chomp($line);
                    586: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    587: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    588:     }
                    589:     unlink("$lonidsdir/$handle.id");
                    590:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    591: 	    0640)) {
                    592: 	%disk_env = %temp_env;
                    593: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    594: 	untie(%disk_env);
                    595:     }
1.786     albertel  596:     return 1;
1.783     albertel  597: }
                    598: 
1.374     www       599: # ------------------------------------------- Transfer profile into environment
1.780     albertel  600: my $env_loaded;
                    601: sub transfer_profile_to_env {
1.788     albertel  602:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    603:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       604: 
1.720     albertel  605:     if (!defined($lonidsdir)) {
                    606: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    607:     }
                    608:     if (!defined($handle)) {
                    609:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    610:     }
                    611: 
1.786     albertel  612:     my $convert;
                    613:     {
1.917     albertel  614:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    615: 	if (!$opened) {
1.915     albertel  616: 	    return;
                    617: 	}
1.786     albertel  618: 	flock($idf,LOCK_SH);
                    619: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    620: 		&GDBM_READER(),0640)) {
                    621: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    622: 	    untie(%disk_env);
                    623: 	} else {
                    624: 	    $convert = 1;
                    625: 	}
                    626:     }
                    627:     if ($convert) {
                    628: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    629: 	    &logthis("Failed to load session, or convert session.");
                    630: 	}
1.374     www       631:     }
1.783     albertel  632: 
1.786     albertel  633:     my %remove;
1.783     albertel  634:     while ( my $envname = each(%env) ) {
1.433     matthew   635:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    636:             if ($time < time-300) {
1.783     albertel  637:                 $remove{$key}++;
1.433     matthew   638:             }
                    639:         }
                    640:     }
1.783     albertel  641: 
1.619     albertel  642:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  643:     $env_loaded=1;
1.783     albertel  644:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   645:         &delenv($expired_key);
1.374     www       646:     }
1.1       albertel  647: }
                    648: 
1.916     albertel  649: # ---------------------------------------------------- Check for valid session 
                    650: sub check_for_valid_session {
1.1245    raeburn   651:     my ($r,$name,$userhashref) = @_;
1.916     albertel  652:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1337    raeburn   653:     my ($linkname,$pubname);
1.1155    raeburn   654:     if ($name eq '') {
                    655:         $name = 'lonID';
1.1337    raeburn   656:         $linkname = 'lonLinkID';
                    657:         $pubname = 'lonPubID';
1.1155    raeburn   658:     }
                    659:     my $lonid=$cookies{$name};
1.1337    raeburn   660:     if (!$lonid) {
                    661:         if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
                    662:             $lonid=$cookies{$linkname};
                    663:         }
                    664:         if (!$lonid) {
                    665:             if (($name eq 'lonID') && ($pubname)) {
                    666:                 $lonid=$cookies{$pubname};
                    667:             }
                    668:         }
                    669:     }
1.916     albertel  670:     return undef if (!$lonid);
                    671: 
                    672:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   673:     my $lonidsdir;
                    674:     if ($name eq 'lonDAV') {
                    675:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    676:     } else {
                    677:         $lonidsdir=$r->dir_config('lonIDsDir');
                    678:     }
1.916     albertel  679:     return undef if (!-e "$lonidsdir/$handle.id");
                    680: 
1.917     albertel  681:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    682:     return undef if (!$opened);
1.916     albertel  683: 
                    684:     flock($idf,LOCK_SH);
                    685:     my %disk_env;
                    686:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    687: 	    &GDBM_READER(),0640)) {
                    688: 	return undef;	
                    689:     }
                    690: 
                    691:     if (!defined($disk_env{'user.name'})
                    692: 	|| !defined($disk_env{'user.domain'})) {
                    693: 	return undef;
                    694:     }
1.1245    raeburn   695: 
                    696:     if (ref($userhashref) eq 'HASH') {
                    697:         $userhashref->{'name'} = $disk_env{'user.name'};
                    698:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   699:     }
1.1245    raeburn   700: 
1.916     albertel  701:     return $handle;
                    702: }
                    703: 
1.830     albertel  704: sub timed_flock {
                    705:     my ($file,$lock_type) = @_;
                    706:     my $failed=0;
                    707:     eval {
                    708: 	local $SIG{__DIE__}='DEFAULT';
                    709: 	local $SIG{ALRM}=sub {
                    710: 	    $failed=1;
                    711: 	    die("failed lock");
                    712: 	};
                    713: 	alarm(13);
                    714: 	flock($file,$lock_type);
                    715: 	alarm(0);
                    716:     };
                    717:     if ($failed) {
                    718: 	return undef;
                    719:     } else {
                    720: 	return 1;
                    721:     }
                    722: }
                    723: 
1.5       www       724: # ---------------------------------------------------------- Append Environment
                    725: 
                    726: sub appenv {
1.949     raeburn   727:     my ($newenv,$roles) = @_;
                    728:     if (ref($newenv) eq 'HASH') {
                    729:         foreach my $key (keys(%{$newenv})) {
                    730:             my $refused = 0;
                    731: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    732:                 $refused = 1;
                    733:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   734:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   735:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    736:                         $refused = 0;
                    737:                     }
                    738:                 }
                    739:             }
                    740:             if ($refused) {
                    741:                 &logthis("<font color=\"blue\">WARNING: ".
                    742:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    743:                          .'</font>');
                    744: 	        delete($newenv->{$key});
                    745:             } else {
                    746:                 $env{$key}=$newenv->{$key};
                    747:             }
                    748:         }
                    749:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    750:         if ($opened
                    751: 	    && &timed_flock($env_file,LOCK_EX)
                    752: 	    &&
                    753: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    754: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    755: 	    while (my ($key,$value) = each(%{$newenv})) {
                    756: 	        $disk_env{$key} = $value;
                    757: 	    }
                    758: 	    untie(%disk_env);
1.35      www       759:         }
1.191     harris41  760:     }
1.56      www       761:     return 'ok';
                    762: }
                    763: # ----------------------------------------------------- Delete from Environment
                    764: 
                    765: sub delenv {
1.1104    raeburn   766:     my ($delthis,$regexp,$roles) = @_;
                    767:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    768:         my $refused = 1;
                    769:         if (ref($roles) eq 'ARRAY') {
                    770:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    771:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    772:                 $refused = 0;
                    773:             }
                    774:         }
                    775:         if ($refused) {
                    776:             &logthis("<font color=\"blue\">WARNING: ".
                    777:                      "Attempt to delete from environment ".$delthis);
                    778:             return 'error';
                    779:         }
1.56      www       780:     }
1.917     albertel  781:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    782:     if ($opened
1.915     albertel  783: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  784: 	&&
                    785: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    786: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  787: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   788: 	    if ($regexp) {
                    789:                 if ($key=~/^$delthis/) {
                    790:                     delete($env{$key});
                    791:                     delete($disk_env{$key});
                    792:                 } 
                    793:             } else {
                    794:                 if ($key=~/^\Q$delthis\E/) {
                    795: 		    delete($env{$key});
                    796: 		    delete($disk_env{$key});
                    797: 	        }
                    798:             }
1.448     albertel  799: 	}
1.783     albertel  800: 	untie(%disk_env);
1.5       www       801:     }
                    802:     return 'ok';
1.369     albertel  803: }
                    804: 
1.790     albertel  805: sub get_env_multiple {
                    806:     my ($name) = @_;
                    807:     my @values;
                    808:     if (defined($env{$name})) {
                    809:         # exists is it an array
                    810:         if (ref($env{$name})) {
                    811:             @values=@{ $env{$name} };
                    812:         } else {
                    813:             $values[0]=$env{$name};
                    814:         }
                    815:     }
                    816:     return(@values);
                    817: }
                    818: 
1.958     www       819: # ------------------------------------------------------------------- Locking
                    820: 
                    821: sub set_lock {
                    822:     my ($text)=@_;
                    823:     $locknum++;
                    824:     my $id=$$.'-'.$locknum;
                    825:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    826:              'session.lock.'.$id => $text});
                    827:     return $id;
                    828: }
                    829: 
                    830: sub get_locks {
                    831:     my $num=0;
                    832:     my %texts=();
                    833:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    834:        if ($lock=~/\w/) {
                    835:           $num++;
                    836:           $texts{$lock}=$env{'session.lock.'.$lock};
                    837:        }
                    838:    }
                    839:    return ($num,%texts);
                    840: }
                    841: 
                    842: sub remove_lock {
                    843:     my ($id)=@_;
                    844:     my $newlocks='';
                    845:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    846:        if (($lock=~/\w/) && ($lock ne $id)) {
                    847:           $newlocks.=','.$lock;
                    848:        }
                    849:     }
                    850:     &appenv({'session.locks' => $newlocks});
                    851:     &delenv('session.lock.'.$id);
                    852: }
                    853: 
                    854: sub remove_all_locks {
                    855:     my $activelocks=$env{'session.locks'};
                    856:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    857:        if ($lock=~/\w/) {
                    858:           &remove_lock($lock);
                    859:        }
                    860:     }
                    861: }
                    862: 
                    863: 
1.369     albertel  864: # ------------------------------------------ Find out current server userload
                    865: sub userload {
                    866:     my $numusers=0;
                    867:     {
                    868: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    869: 	my $filename;
                    870: 	my $curtime=time;
                    871: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  872: 	    next if ($filename eq '.' || $filename eq '..');
                    873: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  874: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  875: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  876: 	}
                    877: 	closedir(LONIDS);
                    878:     }
                    879:     my $userloadpercent=0;
                    880:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    881:     if ($maxuserload) {
1.371     albertel  882: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  883:     }
1.372     albertel  884:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  885:     return $userloadpercent;
1.283     www       886: }
                    887: 
1.1       albertel  888: # ------------------------------ Find server with least workload from spare.tab
1.11      www       889: 
1.1       albertel  890: sub spareserver {
1.1083    raeburn   891:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  892:     my $spare_server;
1.370     albertel  893:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  894:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    895:                                                      :  $userloadpercent;
1.1083    raeburn   896:     my ($uint_dom,$remotesessions);
                    897:     if (($udom ne '') && (&domain($udom) ne '')) {
                    898:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    899:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    900:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    901:         $remotesessions = $udomdefaults{'remotesessions'};
                    902:     }
1.1123    raeburn   903:     my $spareshash = &this_host_spares($udom);
                    904:     if (ref($spareshash) eq 'HASH') {
                    905:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    906:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   907:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    908:                                              $try_server));
1.1123    raeburn   909: 	        ($spare_server, $lowest_load) =
                    910: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    911:             }
1.1083    raeburn   912:         }
1.784     albertel  913: 
1.1123    raeburn   914:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    915: 
                    916:         if (!$found_server) {
                    917:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    918: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   919:                     next unless (&spare_can_host($udom,$uint_dom,
                    920:                                                  $remotesessions,$try_server));
1.1123    raeburn   921: 	            ($spare_server, $lowest_load) =
                    922: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    923:                 }
                    924: 	    }
                    925:         }
1.784     albertel  926:     }
                    927: 
                    928:     if (!$want_server_name) {
1.968     raeburn   929:         my $protocol = 'http';
                    930:         if ($protocol{$spare_server} eq 'https') {
                    931:             $protocol = $protocol{$spare_server};
                    932:         }
1.1001    raeburn   933:         if (defined($spare_server)) {
                    934:             my $hostname = &hostname($spare_server);
1.1083    raeburn   935:             if (defined($hostname)) {
1.1001    raeburn   936: 	        $spare_server = $protocol.'://'.$hostname;
                    937:             }
                    938:         }
1.784     albertel  939:     }
                    940:     return $spare_server;
                    941: }
                    942: 
                    943: sub compare_server_load {
1.1253    raeburn   944:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    945: 
                    946:     if ($required) {
                    947:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    948:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    949:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    950:         if (($major eq '' && $minor eq '') ||
                    951:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    952:             return ($spare_server,$lowest_load);
                    953:         }
                    954:     }
1.784     albertel  955: 
                    956:     my $loadans     = &reply('load',    $try_server);
                    957:     my $userloadans = &reply('userload',$try_server);
                    958: 
                    959:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   960: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  961:     }
                    962: 
                    963:     my $load;
                    964:     if ($loadans =~ /\d/) {
                    965: 	if ($userloadans =~ /\d/) {
                    966: 	    #both are numbers, pick the bigger one
                    967: 	    $load = ($loadans > $userloadans) ? $loadans 
                    968: 		                              : $userloadans;
1.411     albertel  969: 	} else {
1.784     albertel  970: 	    $load = $loadans;
1.411     albertel  971: 	}
1.784     albertel  972:     } else {
                    973: 	$load = $userloadans;
                    974:     }
                    975: 
                    976:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    977: 	$spare_server = $try_server;
                    978: 	$lowest_load  = $load;
1.370     albertel  979:     }
1.784     albertel  980:     return ($spare_server,$lowest_load);
1.202     matthew   981: }
1.914     albertel  982: 
                    983: # --------------------------- ask offload servers if user already has a session
                    984: sub find_existing_session {
                    985:     my ($udom,$uname) = @_;
1.1123    raeburn   986:     my $spareshash = &this_host_spares($udom);
                    987:     if (ref($spareshash) eq 'HASH') {
                    988:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    989:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    990:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    991:             }
                    992:         }
                    993:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    994:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    995:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    996:             }
                    997:         }
1.914     albertel  998:     }
                    999:     return;
                   1000: }
                   1001: 
                   1002: # -------------------------------- ask if server already has a session for user
                   1003: sub has_user_session {
                   1004:     my ($lonid,$udom,$uname) = @_;
                   1005:     my $result = &reply(join(':','userhassession',
                   1006: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1007:     return 1 if ($result eq 'ok');
                   1008: 
                   1009:     return 0;
                   1010: }
                   1011: 
1.1076    raeburn  1012: # --------- determine least loaded server in a user's domain which allows login
                   1013: 
                   1014: sub choose_server {
1.1259    raeburn  1015:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1016:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1017:     my %servers = &get_servers($udom);
1.1076    raeburn  1018:     my $lowest_load = 30000;
1.1259    raeburn  1019:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1020:     if ($skiploadbal) {
                   1021:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1022:         unless (defined($cached)) {
                   1023:             my $cachetime = 60*60*24;
                   1024:             my %domconfig =
                   1025:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1026:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1027:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1028:                                            $cachetime);
                   1029:             }
                   1030:         }
                   1031:     }
1.1076    raeburn  1032:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1033:         if ($skiploadbal) {
                   1034:             if (ref($balancers) eq 'HASH') {
                   1035:                 next if (exists($balancers->{$lonhost}));
                   1036:             }
                   1037:         }   
1.1115    raeburn  1038:         my $loginvia;
                   1039:         if ($checkloginvia) {
                   1040:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1041:             if ($loginvia) {
                   1042:                 my ($server,$path) = split(/:/,$loginvia);
                   1043:                 ($login_host, $lowest_load) =
1.1253    raeburn  1044:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1045:                 if ($login_host eq $server) {
                   1046:                     $portal_path = $path;
1.1151    raeburn  1047:                     $isredirect = 1;
1.1116    raeburn  1048:                 }
                   1049:             } else {
                   1050:                 ($login_host, $lowest_load) =
1.1253    raeburn  1051:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1052:                 if ($login_host eq $lonhost) {
                   1053:                     $portal_path = '';
1.1151    raeburn  1054:                     $isredirect = ''; 
1.1116    raeburn  1055:                 }
                   1056:             }
                   1057:         } else {
1.1076    raeburn  1058:             ($login_host, $lowest_load) =
1.1253    raeburn  1059:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1060:         }
                   1061:     }
                   1062:     if ($login_host ne '') {
1.1116    raeburn  1063:         $hostname = &hostname($login_host);
1.1076    raeburn  1064:     }
1.1331    raeburn  1065:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1066: }
                   1067: 
1.202     matthew  1068: # --------------------------------------------- Try to change a user's password
                   1069: 
                   1070: sub changepass {
1.799     raeburn  1071:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1072:     $currentpass = &escape($currentpass);
                   1073:     $newpass     = &escape($newpass);
1.1030    raeburn  1074:     my $lonhost = $perlvar{'lonHostID'};
                   1075:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1076: 		       $server);
                   1077:     if (! $answer) {
                   1078: 	&logthis("No reply on password change request to $server ".
                   1079: 		 "by $uname in domain $udom.");
                   1080:     } elsif ($answer =~ "^ok") {
                   1081:         &logthis("$uname in $udom successfully changed their password ".
                   1082: 		 "on $server.");
                   1083:     } elsif ($answer =~ "^pwchange_failure") {
                   1084: 	&logthis("$uname in $udom was unable to change their password ".
                   1085: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1086: 		 "or pwchange");
                   1087:     } elsif ($answer =~ "^non_authorized") {
                   1088:         &logthis("$uname in $udom did not get their password correct when ".
                   1089: 		 "attempting to change it on $server.");
                   1090:     } elsif ($answer =~ "^auth_mode_error") {
                   1091:         &logthis("$uname in $udom attempted to change their password despite ".
                   1092: 		 "not being locally or internally authenticated on $server.");
                   1093:     } elsif ($answer =~ "^unknown_user") {
                   1094:         &logthis("$uname in $udom attempted to change their password ".
                   1095: 		 "on $server but were unable to because $server is not ".
                   1096: 		 "their home server.");
                   1097:     } elsif ($answer =~ "^refused") {
                   1098: 	&logthis("$server refused to change $uname in $udom password because ".
                   1099: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1100:     } elsif ($answer =~ "invalid_client") {
                   1101:         &logthis("$server refused to change $uname in $udom password because ".
                   1102:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1103:     }
                   1104:     return $answer;
1.1       albertel 1105: }
                   1106: 
1.169     harris41 1107: # ----------------------- Try to determine user's current authentication scheme
                   1108: 
                   1109: sub queryauthenticate {
                   1110:     my ($uname,$udom)=@_;
1.456     albertel 1111:     my $uhome=&homeserver($uname,$udom);
                   1112:     if (!$uhome) {
                   1113: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1114: 	return 'no_host';
                   1115:     }
                   1116:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1117:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1118: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1119:     }
1.456     albertel 1120:     return $answer;
1.169     harris41 1121: }
                   1122: 
1.1       albertel 1123: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1124: 
1.1       albertel 1125: sub authenticate {
1.1073    raeburn  1126:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1127:     $upass=&escape($upass);
                   1128:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1129:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1130:     my $newhome;
1.836     www      1131:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1132: # Maybe the machine was offline and only re-appeared again recently?
                   1133:         &reconlonc();
                   1134: # One more
1.952     raeburn  1135: 	$uhome=&homeserver($uname,$udom,1);
                   1136:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1137:             if (defined(&domain($udom,'primary'))) {
                   1138:                 $newhome=&domain($udom,'primary');
                   1139:             }
                   1140:             if ($newhome ne '') {
                   1141:                 $uhome = $newhome;
                   1142:             }
                   1143:         }
1.836     www      1144: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1145: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1146: 	    return 'no_host';
                   1147:         }
1.1       albertel 1148:     }
1.1073    raeburn  1149:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1150:     if ($answer eq 'authorized') {
1.952     raeburn  1151:         if ($newhome) {
                   1152:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1153:             return 'no_account_on_host'; 
                   1154:         } else {
                   1155:             &logthis("User $uname at $udom authorized by $uhome");
                   1156:             return $uhome;
                   1157:         }
1.471     albertel 1158:     }
                   1159:     if ($answer eq 'non_authorized') {
                   1160: 	&logthis("User $uname at $udom rejected by $uhome");
                   1161: 	return 'no_host'; 
1.9       www      1162:     }
1.471     albertel 1163:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1164:     return 'no_host';
                   1165: }
                   1166: 
1.1073    raeburn  1167: sub can_host_session {
1.1074    raeburn  1168:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1169:     my $canhost = 1;
1.1074    raeburn  1170:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1171:     if (ref($remotesessions) eq 'HASH') {
                   1172:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1173:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1174:                 $canhost = 0;
                   1175:             } else {
                   1176:                 $canhost = 1;
                   1177:             }
                   1178:         }
                   1179:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1180:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1181:                 $canhost = 1;
                   1182:             } else {
                   1183:                 $canhost = 0;
                   1184:             }
                   1185:         }
                   1186:         if ($canhost) {
                   1187:             if ($remotesessions->{'version'} ne '') {
                   1188:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1189:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1190:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1191:                         my $major = $1;
                   1192:                         my $minor = $2;
                   1193:                         if (($major < $reqmajor ) ||
                   1194:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1195:                             $canhost = 0;
                   1196:                         }
                   1197:                     } else {
                   1198:                         $canhost = 0;
                   1199:                     }
                   1200:                 }
                   1201:             }
                   1202:         }
                   1203:     }
                   1204:     if ($canhost) {
                   1205:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1206:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1207:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1208:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1209:                 if (($uint_dom ne '') && 
                   1210:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1211:                     $canhost = 0;
                   1212:                 } else {
                   1213:                     $canhost = 1;
                   1214:                 }
                   1215:             }
                   1216:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1217:                 if (($uint_dom ne '') && 
                   1218:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1219:                     $canhost = 1;
                   1220:                 } else {
                   1221:                     $canhost = 0;
                   1222:                 }
                   1223:             }
                   1224:         }
                   1225:     }
                   1226:     return $canhost;
                   1227: }
                   1228: 
1.1083    raeburn  1229: sub spare_can_host {
                   1230:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1231:     my $canhost=1;
1.1279    raeburn  1232:     my $try_server_hostname = &hostname($try_server);
                   1233:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1234:     my $serverhomedom = &host_domain($serverhomeID);
                   1235:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1236:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1237:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1238:             $canhost = 0;
                   1239:         }
                   1240:     }
                   1241:     if (($canhost) && ($uint_dom)) {
                   1242:         my @intdoms;
                   1243:         my $internet_names = &get_internet_names($try_server);
                   1244:         if (ref($internet_names) eq 'ARRAY') {
                   1245:             @intdoms = @{$internet_names};
                   1246:         }
                   1247:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1248:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1249:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1250:                                          $remotesessions,
                   1251:                                          $defdomdefaults{'hostedsessions'});
                   1252:         }
1.1083    raeburn  1253:     }
                   1254:     return $canhost;
                   1255: }
                   1256: 
1.1123    raeburn  1257: sub this_host_spares {
                   1258:     my ($dom) = @_;
1.1126    raeburn  1259:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1260:     my @hosts = &current_machine_ids();
                   1261:     foreach my $lonhost (@hosts) {
                   1262:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1263:             $dom_in_use = $dom;
                   1264:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1265:             last;
                   1266:         }
                   1267:     }
1.1126    raeburn  1268:     if ($dom_in_use ne '') {
                   1269:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1270:     }
                   1271:     if (ref($result) ne 'HASH') {
                   1272:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1273:         $dom_in_use = &host_domain($lonhost_in_use);
                   1274:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1275:         if (ref($result) ne 'HASH') {
                   1276:             $result = \%spareid;
                   1277:         }
                   1278:     }
                   1279:     return $result;
                   1280: }
                   1281: 
                   1282: sub spares_for_offload  {
                   1283:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1284:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1285:     if (defined($cached)) {
                   1286:         return $result;
                   1287:     } else {
1.1126    raeburn  1288:         my $cachetime = 60*60*24;
                   1289:         my %domconfig =
                   1290:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1291:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1292:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1293:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1294:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1295:                 }
                   1296:             }
                   1297:         }
                   1298:     }
1.1126    raeburn  1299:     return;
1.1123    raeburn  1300: }
                   1301: 
1.1129    raeburn  1302: sub get_lonbalancer_config {
                   1303:     my ($servers) = @_;
                   1304:     my ($currbalancer,$currtargets);
                   1305:     if (ref($servers) eq 'HASH') {
                   1306:         foreach my $server (keys(%{$servers})) {
                   1307:             my %what = (
                   1308:                          spareid => 1,
                   1309:                          perlvar => 1,
                   1310:                        );
                   1311:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1312:             if ($result eq 'ok') {
                   1313:                 if (ref($returnhash) eq 'HASH') {
                   1314:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1315:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1316:                             $currbalancer = $server;
                   1317:                             $currtargets = {};
                   1318:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1319:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1320:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1321:                                 }
                   1322:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1323:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1324:                                 }
                   1325:                             }
                   1326:                             last;
                   1327:                         }
                   1328:                     }
                   1329:                 }
                   1330:             }
                   1331:         }
                   1332:     }
                   1333:     return ($currbalancer,$currtargets);
                   1334: }
                   1335: 
                   1336: sub check_loadbalancing {
1.1331    raeburn  1337:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1338:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1339:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1340:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1341:     my @hosts = &current_machine_ids();
1.1129    raeburn  1342:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1343:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1344:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1345:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1346:     my $domneedscache;
1.1129    raeburn  1347:     my $cachetime = 60*60*24;
                   1348: 
                   1349:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1350:         $dom_in_use = $udom;
                   1351:         $homeintdom = 1;
                   1352:     } else {
                   1353:         $dom_in_use = $serverhomedom;
                   1354:     }
                   1355:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1356:     unless (defined($cached)) {
                   1357:         my %domconfig =
                   1358:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1359:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1360:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1361:         } else {
                   1362:             $domneedscache = $dom_in_use;
1.1129    raeburn  1363:         }
                   1364:     }
                   1365:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1366:         ($is_balancer,$currtargets,$currrules) = 
                   1367:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1368:         if ($is_balancer) {
                   1369:             if (ref($currrules) eq 'HASH') {
                   1370:                 if ($homeintdom) {
                   1371:                     if ($uname ne '') {
                   1372:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1373:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1374:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1375:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1376:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1377:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1378:                             }
                   1379:                         }
                   1380:                         if ($rule_in_effect eq '') {
                   1381:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1382:                             if ($userenv{'inststatus'} ne '') {
                   1383:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1384:                                 my ($othertitle,$usertypes,$types) =
                   1385:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1386:                                 if (ref($types) eq 'ARRAY') {
                   1387:                                     foreach my $type (@{$types}) {
                   1388:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1389:                                             if (exists($currrules->{$type})) {
                   1390:                                                 $rule_in_effect = $currrules->{$type};
                   1391:                                             }
                   1392:                                         }
                   1393:                                     }
                   1394:                                 }
                   1395:                             } else {
                   1396:                                 if (exists($currrules->{'default'})) {
                   1397:                                     $rule_in_effect = $currrules->{'default'};
                   1398:                                 }
                   1399:                             }
                   1400:                         }
                   1401:                     } else {
                   1402:                         if (exists($currrules->{'default'})) {
                   1403:                             $rule_in_effect = $currrules->{'default'};
                   1404:                         }
                   1405:                     }
                   1406:                 } else {
                   1407:                     if ($currrules->{'_LC_external'} ne '') {
                   1408:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1409:                     }
                   1410:                 }
                   1411:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1412:                                                        $uname,$udom);
                   1413:             }
                   1414:         }
                   1415:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1416:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1417:         unless (defined($cached)) {
                   1418:             my %domconfig =
                   1419:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1420:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1421:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1422:             } else {
                   1423:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1424:             }
                   1425:         }
                   1426:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1427:             ($is_balancer,$currtargets,$currrules) = 
                   1428:                 &check_balancer_result($result,@hosts);
                   1429:             if ($is_balancer) {
1.1129    raeburn  1430:                 if (ref($currrules) eq 'HASH') {
                   1431:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1432:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1433:                     }
                   1434:                 }
                   1435:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1436:                                                        $uname,$udom);
                   1437:             }
                   1438:         } else {
                   1439:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1440:                 $is_balancer = 1;
                   1441:                 $offloadto = &this_host_spares($dom_in_use);
                   1442:             }
1.1307    raeburn  1443:             unless (defined($cached)) {
                   1444:                 $domneedscache = $serverhomedom;
                   1445:             }
1.1129    raeburn  1446:         }
                   1447:     } else {
                   1448:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1449:             $is_balancer = 1;
                   1450:             $offloadto = &this_host_spares($dom_in_use);
                   1451:         }
1.1307    raeburn  1452:         unless (defined($cached)) {
                   1453:             $domneedscache = $serverhomedom;
                   1454:         }
                   1455:     }
                   1456:     if ($domneedscache) {
                   1457:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1458:     }
1.1176    raeburn  1459:     if ($is_balancer) {
                   1460:         my $lowest_load = 30000;
                   1461:         if (ref($offloadto) eq 'HASH') {
                   1462:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1463:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1464:                     ($otherserver,$lowest_load) =
                   1465:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1466:                 }
1.1129    raeburn  1467:             }
1.1176    raeburn  1468:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1469: 
1.1176    raeburn  1470:             if (!$found_server) {
                   1471:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1472:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1473:                         ($otherserver,$lowest_load) =
                   1474:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1475:                     }
                   1476:                 }
                   1477:             }
                   1478:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1479:             if (@{$offloadto} == 1) {
                   1480:                 $otherserver = $offloadto->[0];
                   1481:             } elsif (@{$offloadto} > 1) {
                   1482:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1483:                     ($otherserver,$lowest_load) =
                   1484:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1485:                 }
                   1486:             }
                   1487:         }
1.1331    raeburn  1488:         unless ($caller eq 'login') {
                   1489:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1490:                 $is_balancer = 0;
                   1491:                 if ($uname ne '' && $udom ne '') {
                   1492:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1493:                     
1.1331    raeburn  1494:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1495:                                  'user.loadbalcheck.time' => time});
                   1496:                     }
1.1176    raeburn  1497:                 }
1.1129    raeburn  1498:             }
                   1499:         }
                   1500:     }
                   1501:     return ($is_balancer,$otherserver);
                   1502: }
                   1503: 
1.1191    raeburn  1504: sub check_balancer_result {
                   1505:     my ($result,@hosts) = @_;
                   1506:     my ($is_balancer,$currtargets,$currrules);
                   1507:     if (ref($result) eq 'HASH') {
                   1508:         if ($result->{'lonhost'} ne '') {
                   1509:             my $currbalancer = $result->{'lonhost'};
                   1510:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1511:                 $is_balancer = 1;
                   1512:                 $currtargets = $result->{'targets'};
                   1513:                 $currrules = $result->{'rules'};
                   1514:             }
                   1515:         } else {
                   1516:             foreach my $key (keys(%{$result})) {
                   1517:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1518:                     (ref($result->{$key}) eq 'HASH')) {
                   1519:                     $is_balancer = 1;
                   1520:                     $currrules = $result->{$key}{'rules'};
                   1521:                     $currtargets = $result->{$key}{'targets'};
                   1522:                     last;
                   1523:                 }
                   1524:             }
                   1525:         }
                   1526:     }
                   1527:     return ($is_balancer,$currtargets,$currrules);
                   1528: }
                   1529: 
1.1129    raeburn  1530: sub get_loadbalancer_targets {
                   1531:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1532:     my $offloadto;
1.1175    raeburn  1533:     if ($rule_in_effect eq 'none') {
                   1534:         return [$perlvar{'lonHostID'}];
                   1535:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1536:         $offloadto = $currtargets;
                   1537:     } else {
                   1538:         if ($rule_in_effect eq 'homeserver') {
                   1539:             my $homeserver = &homeserver($uname,$udom);
                   1540:             if ($homeserver ne 'no_host') {
                   1541:                 $offloadto = [$homeserver];
                   1542:             }
                   1543:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1544:             my %domconfig =
                   1545:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1546:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1547:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1548:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1549:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1550:                     }
                   1551:                 }
                   1552:             } else {
1.1178    raeburn  1553:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1554:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1555:                 if (&hostname($remotebalancer) ne '') {
                   1556:                     $offloadto = [$remotebalancer];
                   1557:                 }
                   1558:             }
                   1559:         } elsif (&hostname($rule_in_effect) ne '') {
                   1560:             $offloadto = [$rule_in_effect];
                   1561:         }
                   1562:     }
                   1563:     return $offloadto;
                   1564: }
                   1565: 
1.1127    raeburn  1566: sub internet_dom_servers {
                   1567:     my ($dom) = @_;
                   1568:     my (%uniqservers,%servers);
                   1569:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1570:     my @machinedoms = &machine_domains($primaryserver);
                   1571:     foreach my $mdom (@machinedoms) {
                   1572:         my %currservers = %servers;
                   1573:         my %server = &get_servers($mdom);
                   1574:         %servers = (%currservers,%server);
                   1575:     }
                   1576:     my %by_hostname;
                   1577:     foreach my $id (keys(%servers)) {
                   1578:         push(@{$by_hostname{$servers{$id}}},$id);
                   1579:     }
                   1580:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1581:         if (@{$by_hostname{$hostname}} > 1) {
                   1582:             my $match = 0;
                   1583:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1584:                 if (&host_domain($id) eq $dom) {
                   1585:                     $uniqservers{$id} = $hostname;
                   1586:                     $match = 1;
                   1587:                 }
                   1588:             }
                   1589:             unless ($match) {
                   1590:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1591:             }
                   1592:         } else {
                   1593:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1594:         }
                   1595:     }
                   1596:     return %uniqservers;
                   1597: }
                   1598: 
1.1       albertel 1599: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1600: 
1.599     albertel 1601: my %homecache;
1.1       albertel 1602: sub homeserver {
1.230     stredwic 1603:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1604:     my $index="$uname:$udom";
1.426     albertel 1605: 
1.599     albertel 1606:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1607: 
                   1608:     my %servers = &get_servers($udom,'library');
                   1609:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1610:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1611: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1612: 
                   1613: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1614: 	if ($answer eq 'found') {
                   1615: 	    delete($badServerCache{$tryserver}); 
                   1616: 	    return $homecache{$index}=$tryserver;
                   1617: 	} elsif ($answer eq 'no_host') {
                   1618: 	    $badServerCache{$tryserver}=1;
                   1619: 	}
1.1       albertel 1620:     }    
                   1621:     return 'no_host';
1.70      www      1622: }
                   1623: 
1.1300    raeburn  1624: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1625: 
                   1626: sub idget {
1.1300    raeburn  1627:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1628:     my %returnhash=();
1.1300    raeburn  1629:     my @ids=(); 
                   1630:     if (ref($idsref) eq 'ARRAY') {
                   1631:         @ids = @{$idsref};
                   1632:     } else {
                   1633:         return %returnhash; 
                   1634:     }
                   1635:     if ($namespace eq '') {
                   1636:         $namespace = 'ids';
                   1637:     }
1.70      www      1638:     
1.841     albertel 1639:     my %servers = &get_servers($udom,'library');
                   1640:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1641: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1642: 	if ($namespace eq 'ids') {
                   1643: 	    $idlist=~tr/A-Z/a-z/;
                   1644: 	}
                   1645: 	my $reply;
                   1646: 	if ($namespace eq 'ids') {
                   1647: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1648: 	} else {
                   1649: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1650: 	}
1.841     albertel 1651: 	my @answer=();
                   1652: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1653: 	    @answer=split(/\&/,$reply);
                   1654: 	}                    ;
                   1655: 	my $i;
                   1656: 	for ($i=0;$i<=$#ids;$i++) {
                   1657: 	    if ($answer[$i]) {
1.1299    raeburn  1658: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1659: 	    }
1.841     albertel 1660: 	}
1.1300    raeburn  1661:     }
1.70      www      1662:     return %returnhash;
                   1663: }
                   1664: 
                   1665: # ------------------------------------- Find the IDs behind a list of usernames
                   1666: 
                   1667: sub idrget {
                   1668:     my ($udom,@unames)=@_;
                   1669:     my %returnhash=();
1.800     albertel 1670:     foreach my $uname (@unames) {
                   1671:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1672:     }
1.70      www      1673:     return %returnhash;
                   1674: }
                   1675: 
1.1300    raeburn  1676: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1677: 
                   1678: sub idput {
1.1300    raeburn  1679:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1680:     my %servers=();
1.1300    raeburn  1681:     my %ids=();
                   1682:     my %byid = ();
                   1683:     if (ref($idsref) eq 'HASH') {
                   1684:         %ids=%{$idsref};
                   1685:     }
                   1686:     if ($namespace eq '') {
                   1687:         $namespace = 'ids'; 
                   1688:     }
1.800     albertel 1689:     foreach my $uname (keys(%ids)) {
                   1690: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1691:         if ($uhom eq '') {
                   1692:             $uhom=&homeserver($uname,$udom);
                   1693:         }
1.70      www      1694:         if ($uhom ne 'no_host') {
1.800     albertel 1695:             my $esc_unam=&escape($uname);
1.1300    raeburn  1696:             if ($namespace eq 'ids') {
                   1697:                 my $id=&escape($ids{$uname});
                   1698:                 $id=~tr/A-Z/a-z/;
                   1699:                 my $esc_unam=&escape($uname);
                   1700:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1701:             } else {
1.1300    raeburn  1702:                 my @currids = split(/,/,$ids{$uname});
                   1703:                 foreach my $id (@currids) {
                   1704:                     $byid{$uhom}{$id} .= $uname.',';
                   1705:                 }
                   1706:             }
                   1707:         }
                   1708:     }
                   1709:     if ($namespace eq 'clickers') {
                   1710:         foreach my $server (keys(%byid)) {
                   1711:             if (ref($byid{$server}) eq 'HASH') {
                   1712:                 foreach my $id (keys(%{$byid{$server}})) {
                   1713:                     $byid{$server} =~ s/,$//;
                   1714:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1715:                 }
1.70      www      1716:             }
                   1717:         }
1.191     harris41 1718:     }
1.800     albertel 1719:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1720:         $servers{$server} =~ s/\&$//;
                   1721:         if ($namespace eq 'ids') {     
                   1722:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1723:         } else {
                   1724:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1725:         }
1.191     harris41 1726:     }
1.344     www      1727: }
                   1728: 
1.1300    raeburn  1729: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1730: 
                   1731: sub iddel {
1.1300    raeburn  1732:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1733:     my %result=();
1.1300    raeburn  1734:     my %ids=();
                   1735:     my %byid = ();
                   1736:     if (ref($idshashref) eq 'HASH') {
                   1737:         %ids=%{$idshashref};
                   1738:     } else {
1.1231    raeburn  1739:         return %result;
                   1740:     }
1.1300    raeburn  1741:     if ($namespace eq '') {
                   1742:         $namespace = 'ids';
                   1743:     }
1.1231    raeburn  1744:     my %servers=();
1.1300    raeburn  1745:     while (my ($id,$unamestr) = each(%ids)) {
                   1746:         if ($namespace eq 'ids') {
                   1747:             my $uhom = $uhome;
                   1748:             if ($uhom eq '') { 
                   1749:                 $uhom=&homeserver($unamestr,$udom);
                   1750:             }
                   1751:             if ($uhom ne 'no_host') {
                   1752:                 $servers{$uhom}.='&'.&escape($id);
                   1753:             }
                   1754:          } else {
                   1755:             my @curritems = split(/,/,$ids{$id});
                   1756:             foreach my $uname (@curritems) {
                   1757:                 my $uhom = $uhome;
                   1758:                 if ($uhom eq '') {
                   1759:                     $uhom=&homeserver($uname,$udom);
                   1760:                 }
                   1761:                 if ($uhom ne 'no_host') { 
                   1762:                     $byid{$uhom}{$id} .= $uname.',';
                   1763:                 }
                   1764:             }
1.1231    raeburn  1765:         }
1.1300    raeburn  1766:     }
                   1767:     if ($namespace eq 'clickers') {
                   1768:         foreach my $server (keys(%byid)) {
                   1769:             if (ref($byid{$server}) eq 'HASH') {
                   1770:                 foreach my $id (keys(%{$byid{$server}})) {
                   1771:                     $byid{$server}{$id} =~ s/,$//;
                   1772:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1773:                 }
1.1231    raeburn  1774:             }
                   1775:         }
                   1776:     }
                   1777:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1778:         $servers{$server} =~ s/\&$//;
                   1779:         if ($namespace eq 'ids') {
                   1780:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1781:         } elsif ($namespace eq 'clickers') {
                   1782:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1783:         }
1.1231    raeburn  1784:     }
                   1785:     return %result;
                   1786: }
                   1787: 
1.1300    raeburn  1788: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1789: 
                   1790: sub updateclickers {
                   1791:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1792:     my %clickers;
                   1793:     if (ref($idshashref) eq 'HASH') {
                   1794:         %clickers=%{$idshashref};
                   1795:     } else {
                   1796:         return;
                   1797:     }
                   1798:     my $items='';
                   1799:     foreach my $item (keys(%clickers)) {
                   1800:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1801:     }
                   1802:     $items=~s/\&$//;
                   1803:     my $request = "updateclickers:$udom:$action:$items";
                   1804:     if ($critical) {
                   1805:         return &critical($request,$uhome);
                   1806:     } else {
                   1807:         return &reply($request,$uhome);
                   1808:     }
                   1809: }
                   1810: 
1.1023    raeburn  1811: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1812: sub dump_dom {
1.1165    droeschl 1813:     my ($namespace, $udom, $regexp) = @_;
                   1814: 
                   1815:     $udom ||= $env{'user.domain'};
                   1816: 
                   1817:     return () unless $udom;
                   1818: 
                   1819:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1820: }
                   1821: 
1.1023    raeburn  1822: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1823: 
                   1824: sub get_dom {
1.860     raeburn  1825:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1826:     return if ($udom eq 'public');
1.806     raeburn  1827:     my $items='';
                   1828:     foreach my $item (@$storearr) {
                   1829:         $items.=&escape($item).'&';
                   1830:     }
                   1831:     $items=~s/\&$//;
1.860     raeburn  1832:     if (!$udom) {
                   1833:         $udom=$env{'user.domain'};
1.1267    raeburn  1834:         return if ($udom eq 'public');
1.860     raeburn  1835:         if (defined(&domain($udom,'primary'))) {
                   1836:             $uhome=&domain($udom,'primary');
                   1837:         } else {
1.874     albertel 1838:             undef($uhome);
1.860     raeburn  1839:         }
                   1840:     } else {
                   1841:         if (!$uhome) {
                   1842:             if (defined(&domain($udom,'primary'))) {
                   1843:                 $uhome=&domain($udom,'primary');
                   1844:             }
                   1845:         }
                   1846:     }
                   1847:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1848:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1849:         my %returnhash;
1.875     albertel 1850:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1851:             return %returnhash;
                   1852:         }
1.806     raeburn  1853:         my @pairs=split(/\&/,$rep);
                   1854:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1855:             return @pairs;
                   1856:         }
                   1857:         my $i=0;
                   1858:         foreach my $item (@$storearr) {
                   1859:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1860:             $i++;
                   1861:         }
                   1862:         return %returnhash;
                   1863:     } else {
1.880     banghart 1864:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1865:     }
                   1866: }
                   1867: 
                   1868: # -------------------------------------------- put items in domain db files 
                   1869: 
                   1870: sub put_dom {
1.860     raeburn  1871:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1872:     if (!$udom) {
                   1873:         $udom=$env{'user.domain'};
                   1874:         if (defined(&domain($udom,'primary'))) {
                   1875:             $uhome=&domain($udom,'primary');
                   1876:         } else {
1.874     albertel 1877:             undef($uhome);
1.860     raeburn  1878:         }
                   1879:     } else {
                   1880:         if (!$uhome) {
                   1881:             if (defined(&domain($udom,'primary'))) {
                   1882:                 $uhome=&domain($udom,'primary');
                   1883:             }
                   1884:         }
                   1885:     } 
                   1886:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1887:         my $items='';
                   1888:         foreach my $item (keys(%$storehash)) {
                   1889:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1890:         }
                   1891:         $items=~s/\&$//;
                   1892:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1893:     } else {
1.860     raeburn  1894:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1895:     }
                   1896: }
                   1897: 
1.1023    raeburn  1898: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1899: sub newput_dom {
1.1023    raeburn  1900:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1901:     my $result;
                   1902:     if (!$udom) {
                   1903:         $udom=$env{'user.domain'};
                   1904:     }
1.1023    raeburn  1905:     if ($udom) {
                   1906:         my $uname = &get_domainconfiguser($udom);
                   1907:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1908:     }
                   1909:     return $result;
                   1910: }
                   1911: 
1.1023    raeburn  1912: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1913: sub del_dom {
1.1023    raeburn  1914:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1915:     if (ref($storearr) eq 'ARRAY') {
                   1916:         if (!$udom) {
                   1917:             $udom=$env{'user.domain'};
                   1918:         }
1.1023    raeburn  1919:         if ($udom) {
                   1920:             my $uname = &get_domainconfiguser($udom); 
                   1921:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1922:         }
                   1923:     }
                   1924: }
                   1925: 
1.1023    raeburn  1926: # ----------------------------------construct domainconfig user for a domain 
                   1927: sub get_domainconfiguser {
                   1928:     my ($udom) = @_;
                   1929:     return $udom.'-domainconfig';
                   1930: }
                   1931: 
1.837     raeburn  1932: sub retrieve_inst_usertypes {
                   1933:     my ($udom) = @_;
                   1934:     my (%returnhash,@order);
1.989     raeburn  1935:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1936:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1937:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1938:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1939:     } else {
                   1940:         if (defined(&domain($udom,'primary'))) {
                   1941:             my $uhome=&domain($udom,'primary');
                   1942:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1943:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1944:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1945:                 return (\%returnhash,\@order);
                   1946:             }
                   1947:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1948:             my @pairs=split(/\&/,$hashitems);
                   1949:             foreach my $item (@pairs) {
                   1950:                 my ($key,$value)=split(/=/,$item,2);
                   1951:                 $key = &unescape($key);
                   1952:                 next if ($key =~ /^error: 2 /);
                   1953:                 $returnhash{$key}=&thaw_unescape($value);
                   1954:             }
                   1955:             my @esc_order = split(/\&/,$orderitems);
                   1956:             foreach my $item (@esc_order) {
                   1957:                 push(@order,&unescape($item));
                   1958:             }
                   1959:         } else {
1.1256    raeburn  1960:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1961:         }
1.1256    raeburn  1962:         return (\%returnhash,\@order);
1.837     raeburn  1963:     }
                   1964: }
                   1965: 
1.868     raeburn  1966: sub is_domainimage {
                   1967:     my ($url) = @_;
1.1306    raeburn  1968:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1969:         if (&domain($1) ne '') {
                   1970:             return '1';
                   1971:         }
                   1972:     }
                   1973:     return;
                   1974: }
                   1975: 
1.899     raeburn  1976: sub inst_directory_query {
                   1977:     my ($srch) = @_;
                   1978:     my $udom = $srch->{'srchdomain'};
                   1979:     my %results;
                   1980:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1981:     my $outcome;
1.899     raeburn  1982:     if ($homeserver ne '') {
1.904     albertel 1983: 	my $queryid=&reply("querysend:instdirsearch:".
                   1984: 			   &escape($srch->{'srchby'}).':'.
                   1985: 			   &escape($srch->{'srchterm'}).':'.
                   1986: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1987: 	my $host=&hostname($homeserver);
                   1988: 	if ($queryid !~/^\Q$host\E\_/) {
                   1989: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1990: 	    return;
                   1991: 	}
                   1992: 	my $response = &get_query_reply($queryid);
                   1993: 	my $maxtries = 5;
                   1994: 	my $tries = 1;
                   1995: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1996: 	    $response = &get_query_reply($queryid);
                   1997: 	    $tries ++;
                   1998: 	}
                   1999: 
                   2000:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2001:             if ($response eq 'unavailable') {
                   2002:                 $outcome = $response;
                   2003:             } else {
                   2004:                 $outcome = 'ok';
                   2005:                 my @matches = split(/\n/,$response);
                   2006:                 foreach my $match (@matches) {
                   2007:                     my ($key,$value) = split(/=/,$match);
                   2008:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2009:                 }
1.899     raeburn  2010:             }
                   2011:         }
                   2012:     }
1.909     raeburn  2013:     return ($outcome,%results);
1.899     raeburn  2014: }
                   2015: 
                   2016: sub usersearch {
                   2017:     my ($srch) = @_;
                   2018:     my $dom = $srch->{'srchdomain'};
                   2019:     my %results;
                   2020:     my %libserv = &all_library();
                   2021:     my $query = 'usersearch';
                   2022:     foreach my $tryserver (keys(%libserv)) {
                   2023:         if (&host_domain($tryserver) eq $dom) {
                   2024:             my $host=&hostname($tryserver);
                   2025:             my $queryid=
1.911     raeburn  2026:                 &reply("querysend:".&escape($query).':'.
                   2027:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2028:                        &escape($srch->{'srchtype'}).':'.
                   2029:                        &escape($srch->{'srchterm'}),$tryserver);
                   2030:             if ($queryid !~/^\Q$host\E\_/) {
                   2031:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2032:                 next;
1.899     raeburn  2033:             }
                   2034:             my $reply = &get_query_reply($queryid);
                   2035:             my $maxtries = 1;
                   2036:             my $tries = 1;
                   2037:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2038:                 $reply = &get_query_reply($queryid);
                   2039:                 $tries ++;
                   2040:             }
                   2041:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2042:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2043:             } else {
1.911     raeburn  2044:                 my @matches;
                   2045:                 if ($reply =~ /\n/) {
                   2046:                     @matches = split(/\n/,$reply);
                   2047:                 } else {
                   2048:                     @matches = split(/\&/,$reply);
                   2049:                 }
1.899     raeburn  2050:                 foreach my $match (@matches) {
                   2051:                     my ($uname,$udom,%userhash);
1.911     raeburn  2052:                     foreach my $entry (split(/:/,$match)) {
                   2053:                         my ($key,$value) =
                   2054:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2055:                         $userhash{$key} = $value;
                   2056:                         if ($key eq 'username') {
                   2057:                             $uname = $value;
                   2058:                         } elsif ($key eq 'domain') {
                   2059:                             $udom = $value;
1.911     raeburn  2060:                         }
1.899     raeburn  2061:                     }
                   2062:                     $results{$uname.':'.$udom} = \%userhash;
                   2063:                 }
                   2064:             }
                   2065:         }
                   2066:     }
                   2067:     return %results;
                   2068: }
                   2069: 
1.912     raeburn  2070: sub get_instuser {
                   2071:     my ($udom,$uname,$id) = @_;
                   2072:     my $homeserver = &domain($udom,'primary');
                   2073:     my ($outcome,%results);
                   2074:     if ($homeserver ne '') {
                   2075:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2076:                            &escape($id).':'.&escape($udom),$homeserver);
                   2077:         my $host=&hostname($homeserver);
                   2078:         if ($queryid !~/^\Q$host\E\_/) {
                   2079:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2080:             return;
                   2081:         }
                   2082:         my $response = &get_query_reply($queryid);
                   2083:         my $maxtries = 5;
                   2084:         my $tries = 1;
                   2085:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2086:             $response = &get_query_reply($queryid);
                   2087:             $tries ++;
                   2088:         }
                   2089:         if (!&error($response) && $response ne 'refused') {
                   2090:             if ($response eq 'unavailable') {
                   2091:                 $outcome = $response;
                   2092:             } else {
                   2093:                 $outcome = 'ok';
                   2094:                 my @matches = split(/\n/,$response);
                   2095:                 foreach my $match (@matches) {
                   2096:                     my ($key,$value) = split(/=/,$match);
                   2097:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2098:                 }
                   2099:             }
                   2100:         }
                   2101:     }
                   2102:     my %userinfo;
                   2103:     if (ref($results{$uname}) eq 'HASH') {
                   2104:         %userinfo = %{$results{$uname}};
                   2105:     } 
                   2106:     return ($outcome,%userinfo);
                   2107: }
                   2108: 
1.1290    raeburn  2109: sub get_multiple_instusers {
                   2110:     my ($udom,$users,$caller) = @_;
                   2111:     my ($outcome,$results);
                   2112:     if (ref($users) eq 'HASH') {
                   2113:         my $count = keys(%{$users}); 
                   2114:         my $requested = &freeze_escape($users);
                   2115:         my $homeserver = &domain($udom,'primary');
                   2116:         if ($homeserver ne '') {
                   2117:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2118:             my $host=&hostname($homeserver);
                   2119:             if ($queryid !~/^\Q$host\E\_/) {
                   2120:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2121:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2122:                 return ($outcome,$results);
                   2123:             }
                   2124:             my $response = &get_query_reply($queryid);
                   2125:             my $maxtries = 5;
                   2126:             if ($count > 100) {
                   2127:                 $maxtries = 1+int($count/20);
                   2128:             }
                   2129:             my $tries = 1;
                   2130:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2131:                 $response = &get_query_reply($queryid);
                   2132:                 $tries ++;
                   2133:             }
                   2134:             if ($response eq '') {
                   2135:                 $results = {};
                   2136:                 foreach my $key (keys(%{$users})) {
                   2137:                     my ($uname,$id);
                   2138:                     if ($caller eq 'id') {
                   2139:                         $id = $key;
                   2140:                     } else {
                   2141:                         $uname = $key;
                   2142:                     }
                   2143:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2144:                     $outcome = $resp;
1.1290    raeburn  2145:                     if ($resp eq 'ok') {
                   2146:                         %{$results} = (%{$results}, %info);
                   2147:                     } else {
                   2148:                         last;
                   2149:                     }
                   2150:                 }
                   2151:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2152:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2153:                     $outcome = $response;
                   2154:                 } else {
1.1291    raeburn  2155:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2156:                     if ($outcome eq 'ok') {
                   2157:                         $results = &thaw_unescape($userdata); 
                   2158:                     }
                   2159:                 }
                   2160:             }
                   2161:         }
                   2162:     }
                   2163:     return ($outcome,$results);
                   2164: }
                   2165: 
1.912     raeburn  2166: sub inst_rulecheck {
1.923     raeburn  2167:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2168:     my %returnhash;
                   2169:     if ($udom ne '') {
                   2170:         if (ref($rules) eq 'ARRAY') {
                   2171:             @{$rules} = map {&escape($_);} (@{$rules});
                   2172:             my $rulestr = join(':',@{$rules});
                   2173:             my $homeserver=&domain($udom,'primary');
                   2174:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2175:                 my $response;
                   2176:                 if ($item eq 'username') {                
                   2177:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2178:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2179:                                               $homeserver));
1.923     raeburn  2180:                 } elsif ($item eq 'id') {
                   2181:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2182:                                               ':'.&escape($id).':'.$rulestr,
                   2183:                                               $homeserver));
1.945     raeburn  2184:                 } elsif ($item eq 'selfcreate') {
                   2185:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2186:                                                &escape($udom).':'.&escape($uname).
                   2187:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2188:                 }
1.912     raeburn  2189:                 if ($response ne 'refused') {
                   2190:                     my @pairs=split(/\&/,$response);
                   2191:                     foreach my $item (@pairs) {
                   2192:                         my ($key,$value)=split(/=/,$item,2);
                   2193:                         $key = &unescape($key);
                   2194:                         next if ($key =~ /^error: 2 /);
                   2195:                         $returnhash{$key}=&thaw_unescape($value);
                   2196:                     }
                   2197:                 }
                   2198:             }
                   2199:         }
                   2200:     }
                   2201:     return %returnhash;
                   2202: }
                   2203: 
                   2204: sub inst_userrules {
1.923     raeburn  2205:     my ($udom,$check) = @_;
1.912     raeburn  2206:     my (%ruleshash,@ruleorder);
                   2207:     if ($udom ne '') {
                   2208:         my $homeserver=&domain($udom,'primary');
                   2209:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2210:             my $response;
                   2211:             if ($check eq 'id') {
                   2212:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2213:                                  $homeserver);
1.943     raeburn  2214:             } elsif ($check eq 'email') {
                   2215:                 $response=&reply('instemailrules:'.&escape($udom),
                   2216:                                  $homeserver);
1.923     raeburn  2217:             } else {
                   2218:                 $response=&reply('instuserrules:'.&escape($udom),
                   2219:                                  $homeserver);
                   2220:             }
1.912     raeburn  2221:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2222:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2223:                 ($response ne 'no_such_host')) {
                   2224:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2225:                 my @pairs=split(/\&/,$hashitems);
                   2226:                 foreach my $item (@pairs) {
                   2227:                     my ($key,$value)=split(/=/,$item,2);
                   2228:                     $key = &unescape($key);
                   2229:                     next if ($key =~ /^error: 2 /);
                   2230:                     $ruleshash{$key}=&thaw_unescape($value);
                   2231:                 }
                   2232:                 my @esc_order = split(/\&/,$orderitems);
                   2233:                 foreach my $item (@esc_order) {
                   2234:                     push(@ruleorder,&unescape($item));
                   2235:                 }
                   2236:             }
                   2237:         }
                   2238:     }
                   2239:     return (\%ruleshash,\@ruleorder);
                   2240: }
                   2241: 
1.976     raeburn  2242: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2243: 
                   2244: sub get_domain_defaults {
1.1240    raeburn  2245:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2246:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2247:     my $cachetime = 60*60*24;
1.1240    raeburn  2248:     unless ($ignore_cache) {
                   2249:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2250:         if (defined($cached)) {
                   2251:             if (ref($result) eq 'HASH') {
                   2252:                 return %{$result};
                   2253:             }
1.943     raeburn  2254:         }
                   2255:     }
                   2256:     my %domdefaults;
                   2257:     my %domconfig =
1.989     raeburn  2258:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2259:                                   'requestcourses','inststatus',
1.1183    raeburn  2260:                                   'coursedefaults','usersessions',
1.1258    raeburn  2261:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2262:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2263:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2264:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2265:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2266:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2267:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2268:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2269:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2270:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2271:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340  ! raeburn  2272:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
        !          2273:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
        !          2274:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2275:     } else {
                   2276:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2277:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2278:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2279:     }
1.976     raeburn  2280:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2281:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2282:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2283:         } else {
                   2284:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2285:         }
1.1177    raeburn  2286:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2287:         foreach my $item (@usertools) {
                   2288:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2289:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2290:             }
                   2291:         }
1.1229    raeburn  2292:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2293:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2294:         }
1.976     raeburn  2295:     }
1.985     raeburn  2296:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2297:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2298:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2299:         }
                   2300:     }
1.1183    raeburn  2301:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2302:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2303:     }
1.989     raeburn  2304:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2305:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2306:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2307:         }
                   2308:     }
1.1047    raeburn  2309:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2310:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2311:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2312:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2313:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2314:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2315:         }
1.1254    raeburn  2316:         foreach my $type (@coursetypes) {
                   2317:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2318:                 unless ($type eq 'community') {
                   2319:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2320:                 }
                   2321:             }
                   2322:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2323:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2324:             }
1.1277    raeburn  2325:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2326:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2327:                     $domdefaults{$type.'postsubtimeout'} = 
                   2328:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2329:                 }
                   2330:             }
1.1230    raeburn  2331:         }
1.1286    raeburn  2332:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2333:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2334:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2335:                 if (@clonecodes) {
                   2336:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2337:                 }
                   2338:             }
                   2339:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2340:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2341:         }
1.1047    raeburn  2342:     }
1.1073    raeburn  2343:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2344:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2345:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2346:         }
                   2347:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2348:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2349:         }
1.1279    raeburn  2350:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2351:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2352:         }
1.1073    raeburn  2353:     }
1.1254    raeburn  2354:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2355:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2356:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2357:                             'approval','limit');
                   2358:             foreach my $type (@coursetypes) {
                   2359:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2360:                     my @mgrdc = ();
                   2361:                     foreach my $item (@settings) {
                   2362:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2363:                             push(@mgrdc,$item);
                   2364:                         }
                   2365:                     }
                   2366:                     if (@mgrdc) {
                   2367:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2368:                     }
                   2369:                 }
                   2370:             }
                   2371:         }
                   2372:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2373:             foreach my $type (@coursetypes) {
                   2374:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2375:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2376:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2377:                     }
                   2378:                 }
                   2379:             }
                   2380:         }
                   2381:     }
1.1258    raeburn  2382:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2383:         $domdefaults{'catauth'} = 'std';
                   2384:         $domdefaults{'catunauth'} = 'std';
                   2385:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2386:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2387:         }
                   2388:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2389:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2390:         }
                   2391:     }
1.1315    raeburn  2392:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2393:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2394:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2395:         }
1.1338    raeburn  2396:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2397:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2398:         }
                   2399:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2400:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2401:         }
                   2402:     }
1.1320    raeburn  2403:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2404:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2405:         foreach my $prefix (@prefixes) {
                   2406:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2407:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2408:             }
                   2409:         }
                   2410:     }
1.1314    raeburn  2411:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2412:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2413:     }
1.1332    raeburn  2414:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2415:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2416:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2417:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2418:         }
                   2419:     }
1.1219    raeburn  2420:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2421:     return %domdefaults;
                   2422: }
                   2423: 
1.1311    raeburn  2424: sub course_portal_url {
                   2425:     my ($cnum,$cdom) = @_;
                   2426:     my $chome = &homeserver($cnum,$cdom);
                   2427:     my $hostname = &hostname($chome);
                   2428:     my $protocol = $protocol{$chome};
                   2429:     $protocol = 'http' if ($protocol ne 'https');
                   2430:     my %domdefaults = &get_domain_defaults($cdom);
                   2431:     my $firsturl;
                   2432:     if ($domdefaults{'portal_def'}) {
                   2433:         $firsturl = $domdefaults{'portal_def'};
                   2434:     } else {
                   2435:         $firsturl = $protocol.'://'.$hostname;
                   2436:     }
                   2437:     return $firsturl;
                   2438: }
                   2439: 
1.344     www      2440: # --------------------------------------------------- Assign a key to a student
                   2441: 
                   2442: sub assign_access_key {
1.364     www      2443: #
                   2444: # a valid key looks like uname:udom#comments
                   2445: # comments are being appended
                   2446: #
1.498     www      2447:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2448:     $kdom=
1.620     albertel 2449:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2450:     $knum=
1.620     albertel 2451:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2452:     $cdom=
1.620     albertel 2453:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2454:     $cnum=
1.620     albertel 2455:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2456:     $udom=$env{'user.name'} unless (defined($udom));
                   2457:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2458:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2459:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2460:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2461:                                                   # assigned to this person
                   2462:                                                   # - this should not happen,
1.345     www      2463:                                                   # unless something went wrong
                   2464:                                                   # the first time around
                   2465: # ready to assign
1.364     www      2466:         $logentry=$1.'; '.$logentry;
1.496     www      2467:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2468:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2469: # key now belongs to user
1.346     www      2470: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2471:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2472:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2473:                 return 'ok';
                   2474:             } else {
                   2475:                 return 
                   2476:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2477: 	    }
                   2478:         } else {
                   2479:             return 'error: Could not assign key, try again later.';
                   2480:         }
1.364     www      2481:     } elsif (!$existing{$ckey}) {
1.345     www      2482: # the key does not exist
                   2483: 	return 'error: The key does not exist';
                   2484:     } else {
                   2485: # the key is somebody else's
                   2486: 	return 'error: The key is already in use';
                   2487:     }
1.344     www      2488: }
                   2489: 
1.364     www      2490: # ------------------------------------------ put an additional comment on a key
                   2491: 
                   2492: sub comment_access_key {
                   2493: #
                   2494: # a valid key looks like uname:udom#comments
                   2495: # comments are being appended
                   2496: #
                   2497:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2498:     $cdom=
1.620     albertel 2499:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2500:     $cnum=
1.620     albertel 2501:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2502:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2503:     if ($existing{$ckey}) {
                   2504:         $existing{$ckey}.='; '.$logentry;
                   2505: # ready to assign
1.367     www      2506:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2507:                                                  $cdom,$cnum) eq 'ok') {
                   2508: 	    return 'ok';
                   2509:         } else {
                   2510: 	    return 'error: Count not store comment.';
                   2511:         }
                   2512:     } else {
                   2513: # the key does not exist
                   2514: 	return 'error: The key does not exist';
                   2515:     }
                   2516: }
                   2517: 
1.344     www      2518: # ------------------------------------------------------ Generate a set of keys
                   2519: 
                   2520: sub generate_access_keys {
1.364     www      2521:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2522:     $cdom=
1.620     albertel 2523:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2524:     $cnum=
1.620     albertel 2525:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2526:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2527:     unless (($cdom) && ($cnum)) { return 0; }
                   2528:     if ($number>10000) { return 0; }
                   2529:     sleep(2); # make sure don't get same seed twice
                   2530:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2531:     my $total=0;
                   2532:     for (my $i=1;$i<=$number;$i++) {
                   2533:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2534:                   sprintf("%lx",int(100000*rand)).'-'.
                   2535:                   sprintf("%lx",int(100000*rand));
                   2536:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2537:        $newkey=~s/0/h/g; # and also 0 and O
                   2538:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2539:        if ($existing{$newkey}) {
                   2540:            $i--;
                   2541:        } else {
1.364     www      2542: 	  if (&put('accesskeys',
                   2543:               { $newkey => '# generated '.localtime().
1.620     albertel 2544:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2545:                            '; '.$logentry },
                   2546: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2547:               $total++;
                   2548: 	  }
                   2549:        }
                   2550:     }
1.620     albertel 2551:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2552:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2553:     return $total;
                   2554: }
                   2555: 
                   2556: # ------------------------------------------------------- Validate an accesskey
                   2557: 
                   2558: sub validate_access_key {
                   2559:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2560:     $cdom=
1.620     albertel 2561:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2562:     $cnum=
1.620     albertel 2563:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2564:     $udom=$env{'user.domain'} unless (defined($udom));
                   2565:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2566:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2567:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2568: }
                   2569: 
                   2570: # ------------------------------------- Find the section of student in a course
1.652     albertel 2571: sub devalidate_getsection_cache {
                   2572:     my ($udom,$unam,$courseid)=@_;
                   2573:     my $hashid="$udom:$unam:$courseid";
                   2574:     &devalidate_cache_new('getsection',$hashid);
                   2575: }
1.298     matthew  2576: 
1.815     albertel 2577: sub courseid_to_courseurl {
                   2578:     my ($courseid) = @_;
                   2579:     #already url style courseid
                   2580:     return $courseid if ($courseid =~ m{^/});
                   2581: 
                   2582:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2583: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2584: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2585: 	return "/$cdom/$cnum";
                   2586:     }
                   2587: 
                   2588:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2589:     if (exists($courseinfo{'num'})) {
                   2590: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2591:     }
                   2592: 
                   2593:     return undef;
                   2594: }
                   2595: 
1.298     matthew  2596: sub getsection {
                   2597:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2598:     my $cachetime=1800;
1.551     albertel 2599: 
                   2600:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2601:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2602:     if (defined($cached)) { return $result; }
                   2603: 
1.298     matthew  2604:     my %Pending; 
                   2605:     my %Expired;
                   2606:     #
                   2607:     # Each role can either have not started yet (pending), be active, 
                   2608:     #    or have expired.
                   2609:     #
                   2610:     # If there is an active role, we are done.
                   2611:     #
                   2612:     # If there is more than one role which has not started yet, 
                   2613:     #     choose the one which will start sooner
                   2614:     # If there is one role which has not started yet, return it.
                   2615:     #
                   2616:     # If there is more than one expired role, choose the one which ended last.
                   2617:     # If there is a role which has expired, return it.
                   2618:     #
1.815     albertel 2619:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2620:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2621:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2622:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2623:         my $section=$1;
                   2624:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2625:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2626:         my $now=time;
1.548     albertel 2627:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2628:             $Expired{$end}=$section;
                   2629:             next;
                   2630:         }
1.548     albertel 2631:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2632:             $Pending{$start}=$section;
                   2633:             next;
                   2634:         }
1.599     albertel 2635:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2636:     }
                   2637:     #
                   2638:     # Presumedly there will be few matching roles from the above
                   2639:     # loop and the sorting time will be negligible.
                   2640:     if (scalar(keys(%Pending))) {
                   2641:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2642:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2643:     } 
                   2644:     if (scalar(keys(%Expired))) {
                   2645:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2646:         my $time = pop(@sorted);
1.599     albertel 2647:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2648:     }
1.599     albertel 2649:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2650: }
1.70      www      2651: 
1.599     albertel 2652: sub save_cache {
                   2653:     &purge_remembered();
1.722     albertel 2654:     #&Apache::loncommon::validate_page();
1.620     albertel 2655:     undef(%env);
1.780     albertel 2656:     undef($env_loaded);
1.599     albertel 2657: }
1.452     albertel 2658: 
1.599     albertel 2659: my $to_remember=-1;
                   2660: my %remembered;
                   2661: my %accessed;
                   2662: my $kicks=0;
                   2663: my $hits=0;
1.849     albertel 2664: sub make_key {
                   2665:     my ($name,$id) = @_;
1.872     albertel 2666:     if (length($id) > 65 
                   2667: 	&& length(&escape($id)) > 200) {
                   2668: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2669:     }
1.849     albertel 2670:     return &escape($name.':'.$id);
                   2671: }
                   2672: 
1.599     albertel 2673: sub devalidate_cache_new {
                   2674:     my ($name,$id,$debug) = @_;
                   2675:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2676:     my $remembered_id=$name.':'.$id;
1.849     albertel 2677:     $id=&make_key($name,$id);
1.599     albertel 2678:     $memcache->delete($id);
1.1319    damieng  2679:     delete($remembered{$remembered_id});
                   2680:     delete($accessed{$remembered_id});
1.599     albertel 2681: }
                   2682: 
                   2683: sub is_cached_new {
                   2684:     my ($name,$id,$debug) = @_;
1.1319    damieng  2685:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2686:     if (exists($remembered{$remembered_id})) {
                   2687: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2688: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2689: 	$hits++;
1.1319    damieng  2690: 	return ($remembered{$remembered_id},1);
1.599     albertel 2691:     }
1.1319    damieng  2692:     $id=&make_key($name,$id);
1.599     albertel 2693:     my $value = $memcache->get($id);
                   2694:     if (!(defined($value))) {
                   2695: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2696: 	return (undef,undef);
1.416     albertel 2697:     }
1.599     albertel 2698:     if ($value eq '__undef__') {
                   2699: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2700: 	$value=undef;
                   2701:     }
1.1319    damieng  2702:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2703:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2704:     return ($value,1);
                   2705: }
                   2706: 
                   2707: sub do_cache_new {
                   2708:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2709:     my $remembered_id=$name.':'.$id;
1.849     albertel 2710:     $id=&make_key($name,$id);
1.599     albertel 2711:     my $setvalue=$value;
                   2712:     if (!defined($setvalue)) {
                   2713: 	$setvalue='__undef__';
                   2714:     }
1.623     albertel 2715:     if (!defined($time) ) {
                   2716: 	$time=600;
                   2717:     }
1.599     albertel 2718:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2719:     my $result = $memcache->set($id,$setvalue,$time);
                   2720:     if (! $result) {
1.872     albertel 2721: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2722: 	$memcache->disconnect_all();
1.872     albertel 2723:     }
1.600     albertel 2724:     # need to make a copy of $value
1.1319    damieng  2725:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2726:     return $value;
                   2727: }
                   2728: 
                   2729: sub make_room {
1.1319    damieng  2730:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2731: 
1.1319    damieng  2732:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2733:                                     : $value;
1.599     albertel 2734:     if ($to_remember<0) { return; }
1.1319    damieng  2735:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2736:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2737:     my $to_kick;
                   2738:     my $max_time=0;
                   2739:     foreach my $other (keys(%accessed)) {
                   2740: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2741: 	    $to_kick=$other;
                   2742: 	    $max_time=&tv_interval($accessed{$other});
                   2743: 	}
                   2744:     }
                   2745:     delete($remembered{$to_kick});
                   2746:     delete($accessed{$to_kick});
                   2747:     $kicks++;
                   2748:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2749:     return;
                   2750: }
                   2751: 
1.599     albertel 2752: sub purge_remembered {
1.604     albertel 2753:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2754:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2755:     undef(%remembered);
                   2756:     undef(%accessed);
1.428     albertel 2757: }
1.70      www      2758: # ------------------------------------- Read an entry from a user's environment
                   2759: 
                   2760: sub userenvironment {
                   2761:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2762:     my $items;
                   2763:     foreach my $item (@what) {
                   2764:         $items.=&escape($item).'&';
                   2765:     }
                   2766:     $items=~s/\&$//;
1.70      www      2767:     my %returnhash=();
1.1009    raeburn  2768:     my $uhome = &homeserver($unam,$udom);
                   2769:     unless ($uhome eq 'no_host') {
                   2770:         my @answer=split(/\&/, 
                   2771:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2772:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2773:             return %returnhash;
                   2774:         }
1.1009    raeburn  2775:         my $i;
                   2776:         for ($i=0;$i<=$#what;$i++) {
                   2777: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2778:         }
1.70      www      2779:     }
                   2780:     return %returnhash;
1.1       albertel 2781: }
                   2782: 
1.617     albertel 2783: # ---------------------------------------------------------- Get a studentphoto
                   2784: sub studentphoto {
                   2785:     my ($udom,$unam,$ext) = @_;
                   2786:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2787:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2788:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2789:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2790:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2791:             } else {
                   2792:                 my ($result,$perm_reqd)=
1.707     albertel 2793: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2794:                 if ($result eq 'ok') {
                   2795:                     if (!($perm_reqd eq 'yes')) {
                   2796:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2797:                     }
                   2798:                 }
                   2799:             }
                   2800:         }
                   2801:     } else {
                   2802:         my ($result,$perm_reqd) = 
1.707     albertel 2803: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2804:         if ($result eq 'ok') {
                   2805:             if (!($perm_reqd eq 'yes')) {
                   2806:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2807:             }
                   2808:         }
                   2809:     }
                   2810:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2811: }
                   2812: 
                   2813: sub retrievestudentphoto {
                   2814:     my ($udom,$unam,$ext,$type) = @_;
                   2815:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2816:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2817:     if ($ret eq 'ok') {
                   2818:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2819:         if ($type eq 'thumbnail') {
                   2820:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2821:         }
                   2822:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2823:         return $tokenurl;
                   2824:     } else {
                   2825:         if ($type eq 'thumbnail') {
                   2826:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2827:         } else { 
                   2828:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2829:         }
1.617     albertel 2830:     }
                   2831: }
                   2832: 
1.263     www      2833: # -------------------------------------------------------------------- New chat
                   2834: 
                   2835: sub chatsend {
1.724     raeburn  2836:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2837:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2838:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2839:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2840:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2841: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2842: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2843: }
                   2844: 
                   2845: # ------------------------------------------ Find current version of a resource
                   2846: 
                   2847: sub getversion {
                   2848:     my $fname=&clutter(shift);
1.1189    raeburn  2849:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2850:     return &currentversion(&filelocation('',$fname));
                   2851: }
                   2852: 
                   2853: sub currentversion {
                   2854:     my $fname=shift;
                   2855:     my $author=$fname;
                   2856:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2857:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2858:     my $home=&homeserver($uname,$udom);
1.292     www      2859:     if ($home eq 'no_host') { 
                   2860:         return -1; 
                   2861:     }
1.1112    www      2862:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2863:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2864: 	return -1;
                   2865:     }
1.1112    www      2866:     return $answer;
1.263     www      2867: }
                   2868: 
1.1111    www      2869: #
                   2870: # Return special version number of resource if set by override, empty otherwise
                   2871: #
                   2872: sub usedversion {
                   2873:     my $fname=shift;
                   2874:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2875:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2876:     if ($urlversion) { return $urlversion; }
                   2877:     return '';
                   2878: }
                   2879: 
1.1       albertel 2880: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2881: 
1.1       albertel 2882: sub subscribe {
                   2883:     my $fname=shift;
1.761     raeburn  2884:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2885:     $fname=~s/[\n\r]//g;
1.1       albertel 2886:     my $author=$fname;
                   2887:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2888:     my ($udom,$uname)=split(/\//,$author);
                   2889:     my $home=homeserver($uname,$udom);
1.335     albertel 2890:     if ($home eq 'no_host') {
                   2891:         return 'not_found';
1.1       albertel 2892:     }
                   2893:     my $answer=reply("sub:$fname",$home);
1.64      www      2894:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2895: 	$answer.=' by '.$home;
                   2896:     }
1.1       albertel 2897:     return $answer;
                   2898: }
                   2899:     
1.8       www      2900: # -------------------------------------------------------------- Replicate file
                   2901: 
                   2902: sub repcopy {
                   2903:     my $filename=shift;
1.23      www      2904:     $filename=~s/\/+/\//g;
1.1142    raeburn  2905:     my $londocroot = $perlvar{'lonDocRoot'};
                   2906:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2907:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2908:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2909: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2910: 	return &repcopy_userfile($filename);
                   2911:     }
1.532     albertel 2912:     $filename=~s/[\n\r]//g;
1.8       www      2913:     my $transname="$filename.in.transfer";
1.828     www      2914: # FIXME: this should flock
1.607     raeburn  2915:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2916:     my $remoteurl=subscribe($filename);
1.64      www      2917:     if ($remoteurl =~ /^con_lost by/) {
                   2918: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2919:            return 'unavailable';
1.8       www      2920:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2921: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2922: 	   return 'not_found';
1.64      www      2923:     } elsif ($remoteurl =~ /^rejected by/) {
                   2924: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2925:            return 'forbidden';
1.20      www      2926:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2927:            return 'ok';
1.8       www      2928:     } else {
1.290     www      2929:         my $author=$filename;
                   2930:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2931:         my ($udom,$uname)=split(/\//,$author);
                   2932:         my $home=homeserver($uname,$udom);
                   2933:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2934:            my @parts=split(/\//,$filename);
                   2935:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2936:            if ($path ne "$londocroot/res") {
1.8       www      2937:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2938: 	       return 'bad_request';
1.8       www      2939:            }
                   2940:            my $count;
                   2941:            for ($count=5;$count<$#parts;$count++) {
                   2942:                $path.="/$parts[$count]";
                   2943:                if ((-e $path)!=1) {
                   2944: 		   mkdir($path,0777);
                   2945:                }
                   2946:            }
                   2947:            my $ua=new LWP::UserAgent;
                   2948:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2949:            my $response=$ua->request($request,$transname);
                   2950:            if ($response->is_error()) {
                   2951: 	       unlink($transname);
                   2952:                my $message=$response->status_line;
1.672     albertel 2953:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2954:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2955:                return 'unavailable';
1.8       www      2956:            } else {
1.16      www      2957: 	       if ($remoteurl!~/\.meta$/) {
                   2958:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2959:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2960:                   if ($mresponse->is_error()) {
                   2961: 		      unlink($filename.'.meta');
                   2962:                       &logthis(
1.672     albertel 2963:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2964:                   }
                   2965: 	       }
1.8       www      2966:                rename($transname,$filename);
1.607     raeburn  2967:                return 'ok';
1.8       www      2968:            }
1.290     www      2969:        }
1.8       www      2970:     }
1.330     www      2971: }
                   2972: 
                   2973: # ------------------------------------------------ Get server side include body
                   2974: sub ssi_body {
1.381     albertel 2975:     my ($filelink,%form)=@_;
1.606     matthew  2976:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2977:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2978:     }
1.953     www      2979:     my $output='';
                   2980:     my $response;
1.980     raeburn  2981:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2982:        ($output,$response)=&externalssi($filelink);
1.953     www      2983:     } else {
1.1004    droeschl 2984:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2985:        $filelink .= 'inhibitmenu=yes';
1.953     www      2986:        ($output,$response)=&ssi($filelink,%form);
                   2987:     }
1.778     albertel 2988:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2989:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2990:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2991:     if (wantarray) {
                   2992:         return ($output, $response);
                   2993:     } else {
                   2994:         return $output;
                   2995:     }
1.8       www      2996: }
                   2997: 
1.15      www      2998: # --------------------------------------------------------- Server Side Include
                   2999: 
1.782     albertel 3000: sub absolute_url {
                   3001:     my ($host_name) = @_;
                   3002:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3003:     if ($host_name eq '') {
                   3004: 	$host_name = $ENV{'SERVER_NAME'};
                   3005:     }
                   3006:     return $protocol.$host_name;
                   3007: }
                   3008: 
1.942     foxr     3009: #
                   3010: #   Server side include.
                   3011: # Parameters:
                   3012: #  fn     Possibly encrypted resource name/id.
                   3013: #  form   Hash that describes how the rendering should be done
                   3014: #         and other things.
1.944     foxr     3015: # Returns:
1.950     raeburn  3016: #   Scalar context: The content of the response.
                   3017: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3018: #     
1.15      www      3019: sub ssi {
                   3020: 
1.944     foxr     3021:     my ($fn,%form)=@_;
1.15      www      3022:     my $ua=new LWP::UserAgent;
1.23      www      3023:     my $request;
1.711     albertel 3024: 
                   3025:     $form{'no_update_last_known'}=1;
1.895     albertel 3026:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3027:     if (%form) {
1.782     albertel 3028:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3029:       $request->content(join('&',map { 
                   3030:             my $name = escape($_);
                   3031:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3032:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3033:             : &escape($form{$_}) );    
                   3034:         } keys(%form)));
1.23      www      3035:     } else {
1.782     albertel 3036:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3037:     }
                   3038: 
1.15      www      3039:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     3040:     my $response= $ua->request($request);
1.1182    foxr     3041:     my $content = $response->content;
                   3042: 
                   3043: 
1.944     foxr     3044:     if (wantarray) {
1.1173    foxr     3045: 	return ($content, $response);
1.944     foxr     3046:     } else {
1.1173    foxr     3047: 	return $content;
1.942     foxr     3048:     }
1.324     www      3049: }
                   3050: 
                   3051: sub externalssi {
                   3052:     my ($url)=@_;
                   3053:     my $ua=new LWP::UserAgent;
                   3054:     my $request=new HTTP::Request('GET',$url);
                   3055:     my $response=$ua->request($request);
1.954     raeburn  3056:     if (wantarray) {
                   3057:         return ($response->content, $response);
                   3058:     } else {
                   3059:         return $response->content;
                   3060:     }
1.15      www      3061: }
1.254     www      3062: 
1.492     albertel 3063: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3064: 
                   3065: sub allowuploaded {
                   3066:     my ($srcurl,$url)=@_;
                   3067:     $url=&clutter(&declutter($url));
                   3068:     my $dir=$url;
                   3069:     $dir=~s/\/[^\/]+$//;
                   3070:     my %httpref=();
                   3071:     my $httpurl=&hreflocation('',$url);
                   3072:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3073:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3074: }
1.477     raeburn  3075: 
1.1193    raeburn  3076: #
                   3077: # Determine if the current user should be able to edit a particular resource,
                   3078: # when viewing in course context.
                   3079: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3080: #     Functions.
                   3081: # (b) When displaying folder contents in course editor, used to determine if
                   3082: #     "Edit" link will be displayed alongside resource.
                   3083: #
1.1196    raeburn  3084: #  input: six args -- filename (decluttered), course number, course domain,
                   3085: #                   url, symb (if registered) and group (if this is a group
                   3086: #                   item -- e.g., bulletin board, group page etc.).
                   3087: #  output: array of five scalars -- 
1.1193    raeburn  3088: #          $cfile -- url for file editing if editable on current server
                   3089: #          $home -- homeserver of resource (i.e., for author if published,
                   3090: #                                           or course if uploaded.).
                   3091: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3092: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3093: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3094: #
                   3095: 
                   3096: sub can_edit_resource {
1.1194    raeburn  3097:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3098:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3099: #
                   3100: # For aboutme pages user can only edit his/her own.
                   3101: #
1.1199    raeburn  3102:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3103:         my ($sdom,$sname) = ($1,$2);
                   3104:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3105:             $home = $env{'user.home'};
                   3106:             $cfile = $resurl;
                   3107:             if ($env{'form.forceedit'}) {
                   3108:                 $forceview = 1;
                   3109:             } else {
                   3110:                 $forceedit = 1;
                   3111:             }
                   3112:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3113:         } else {
                   3114:             return;
                   3115:         }
                   3116:     }
                   3117: 
                   3118:     if ($env{'request.course.id'}) {
                   3119:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3120:         if ($group ne '') {
                   3121: # if this is a group homepage or group bulletin board, check group privs
                   3122:             my $allowed = 0;
1.1197    raeburn  3123:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3124:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3125:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3126:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3127:                     $allowed = 1;
                   3128:                 }
1.1197    raeburn  3129:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3130:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3131:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3132:                     $allowed = 1;
                   3133:                 }
                   3134:             }
                   3135:             if ($allowed) {
                   3136:                 $home=&homeserver($cnum,$cdom);
                   3137:                 if ($env{'form.forceedit'}) {
                   3138:                     $forceview = 1;
                   3139:                 } else {
                   3140:                     $forceedit = 1;
                   3141:                 }
                   3142:                 $cfile = $resurl;
                   3143:             } else {
                   3144:                 return;
                   3145:             }
                   3146:         } else {
1.1208    raeburn  3147:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3148:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3149:                     return;
                   3150:                 }
                   3151:             } elsif (!$crsedit) {
1.1194    raeburn  3152: #
                   3153: # No edit allowed where CC has switched to student role.
                   3154: #
                   3155:                 return;
                   3156:             }
                   3157:         }
                   3158:     }
                   3159: 
1.1193    raeburn  3160:     if ($file ne '') {
                   3161:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3162:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3163:                 $uploaded = 1;
                   3164:                 $incourse = 1;
1.1193    raeburn  3165:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3166:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3167:                     if ($env{'form.forceedit'}) {
                   3168:                         $forceview = 1;
                   3169:                     } else {
                   3170:                         $forceedit = 1;
                   3171:                     }
1.1194    raeburn  3172:                 }
                   3173:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3174:                 $incourse = 1;
                   3175:                 if ($env{'form.forceedit'}) {
                   3176:                     $forceview = 1;
                   3177:                 } else {
                   3178:                     $forceedit = 1;
                   3179:                 }
                   3180:                 $cfile = $resurl;
                   3181:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3182:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3183:                     $incourse = 1;
                   3184:                     if ($env{'form.forceedit'}) {
                   3185:                         $forceview = 1;
                   3186:                     } else {
                   3187:                         $forceedit = 1;
                   3188:                     }
                   3189:                     $cfile = $resurl;
1.1199    raeburn  3190:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3191:                     $incourse = 1;
                   3192:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3193:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3194:                     $incourse = 1;
1.1199    raeburn  3195:                     if ($env{'form.forceedit'}) {
                   3196:                         $forceview = 1;
                   3197:                     } else {
                   3198:                         $forceedit = 1;
                   3199:                     }
                   3200:                     $cfile = $resurl;
1.1298    raeburn  3201:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3202:                     $incourse = 1;
                   3203:                     if ($env{'form.forceedit'}) {
                   3204:                         $forceview = 1;
                   3205:                     } else {
                   3206:                         $forceedit = 1;
                   3207:                     }
                   3208:                     $cfile = $resurl;
1.1208    raeburn  3209:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3210:                     $incourse = 1;
                   3211:                     if ($env{'form.forceedit'}) {
                   3212:                         $forceview = 1;
                   3213:                     } else {
                   3214:                         $forceedit = 1;
                   3215:                     }
                   3216:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3217:                 }
                   3218:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3219:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3220:                 if (&is_on_map($template)) { 
                   3221:                     $incourse = 1;
                   3222:                     $forceview = 1;
                   3223:                     $cfile = $template;
1.1193    raeburn  3224:                 }
1.1199    raeburn  3225:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3226:                     $incourse = 1;
                   3227:                     if ($env{'form.forceedit'}) {
                   3228:                         $forceview = 1;
                   3229:                     } else {
                   3230:                         $forceedit = 1;
                   3231:                     }
                   3232:                     $cfile = $resurl;
1.1298    raeburn  3233:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3234:                 $incourse = 1;
                   3235:                 if ($env{'form.forceedit'}) {
                   3236:                     $forceview = 1;
                   3237:                 } else {
                   3238:                     $forceedit = 1;
                   3239:                 }
                   3240:                 $cfile = $resurl;
1.1199    raeburn  3241:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3242:                 $incourse = 1;
                   3243:                 $forceview = 1;
                   3244:                 if ($symb) {
                   3245:                     my ($map,$id,$res)=&decode_symb($symb);
                   3246:                     $env{'request.symb'} = $symb;
                   3247:                     $cfile = &clutter($res);
                   3248:                 } else {
                   3249:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3250:                     my $escfile = &unescape($cfile);
                   3251:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3252:                         $cfile = '/adm/wrapper'.$escfile;
                   3253:                     } else {
                   3254:                         $escfile =~ s{^http://}{};
                   3255:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3256:                     }
1.1199    raeburn  3257:                 }
1.1234    raeburn  3258:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3259:                 if ($env{'form.forceedit'}) {
                   3260:                     $forceview = 1;
                   3261:                 } else {
                   3262:                     $forceedit = 1;
                   3263:                 }
                   3264:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3265:             }
                   3266:         }
1.1194    raeburn  3267:         if ($uploaded || $incourse) {
                   3268:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3269:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3270:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3271:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3272:             # Check that the user has permission to edit this resource
                   3273:             my $setpriv = 1;
                   3274:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3275:             if (defined($cfudom)) {
                   3276:                 $home=&homeserver($cfuname,$cfudom);
                   3277:                 $cfile=$file;
                   3278:             }
                   3279:         }
1.1194    raeburn  3280:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3281:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3282:             my @ids=&current_machine_ids();
                   3283:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3284:                 $switchserver=1;
                   3285:             }
                   3286:         }
                   3287:     }
1.1194    raeburn  3288:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3289: }
                   3290: 
                   3291: sub is_course_upload {
                   3292:     my ($file,$cnum,$cdom) = @_;
                   3293:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3294:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3295:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3296:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3297:         return 1;
                   3298:     }
                   3299:     return;
                   3300: }
                   3301: 
1.1194    raeburn  3302: sub in_course {
1.1195    raeburn  3303:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3304:     if ($hideprivileged) {
                   3305:         my $skipuser;
1.1219    raeburn  3306:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3307:         my @possdoms = ($cdom);  
                   3308:         if ($coursehash{'checkforpriv'}) { 
                   3309:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3310:         }
                   3311:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3312:             $skipuser = 1;
                   3313:             if ($coursehash{'nothideprivileged'}) {
                   3314:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3315:                     my $user;
                   3316:                     if ($item =~ /:/) {
                   3317:                         $user = $item;
                   3318:                     } else {
                   3319:                         $user = join(':',split(/[\@]/,$item));
                   3320:                     }
                   3321:                     if ($user eq $uname.':'.$udom) {
                   3322:                         undef($skipuser);
                   3323:                         last;
                   3324:                     }
                   3325:                 }
                   3326:             }
                   3327:             if ($skipuser) {
                   3328:                 return 0;
                   3329:             }
                   3330:         }
                   3331:     }
1.1194    raeburn  3332:     $type ||= 'any';
                   3333:     if (!defined($cdom) || !defined($cnum)) {
                   3334:         my $cid  = $env{'request.course.id'};
                   3335:         $cdom = $env{'course.'.$cid.'.domain'};
                   3336:         $cnum = $env{'course.'.$cid.'.num'};
                   3337:     }
                   3338:     my $typesref;
1.1195    raeburn  3339:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3340:         $typesref = ['active','previous','future'];
                   3341:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3342:         $typesref = [$type];
                   3343:     }
                   3344:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3345:                               $typesref,undef,[$cdom]);
                   3346:     my ($tmp) = keys(%roles);
                   3347:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3348:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3349:     if (@course_roles > 0) {
                   3350:         return 1;
                   3351:     }
                   3352:     return 0;
                   3353: }
                   3354: 
1.478     albertel 3355: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3356: # input: action, courseID, current domain, intended
1.637     raeburn  3357: #        path to file, source of file, instruction to parse file for objects,
                   3358: #        ref to hash for embedded objects,
                   3359: #        ref to hash for codebase of java objects.
1.1095    raeburn  3360: #        reference to scalar to accommodate mime type determined
                   3361: #          from File::MMagic if $parser = parse.
1.637     raeburn  3362: #
1.485     raeburn  3363: # output: url to file (if action was uploaddoc), 
                   3364: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3365: #
1.478     albertel 3366: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3367: # course.
1.477     raeburn  3368: #
1.478     albertel 3369: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3370: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3371: #          course's home server.
1.477     raeburn  3372: #
1.478     albertel 3373: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3374: #          be copied from $source (current location) to 
                   3375: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3376: #         and will then be copied to
                   3377: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3378: #         course's home server.
1.485     raeburn  3379: #
1.481     raeburn  3380: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3381: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3382: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3383: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3384: #         in course's home server.
1.637     raeburn  3385: #
1.477     raeburn  3386: 
                   3387: sub process_coursefile {
1.1095    raeburn  3388:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3389:         $mimetype)=@_;
1.477     raeburn  3390:     my $fetchresult;
1.638     albertel 3391:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3392:     if ($action eq 'propagate') {
1.638     albertel 3393:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3394: 			     $home);
1.481     raeburn  3395:     } else {
1.477     raeburn  3396:         my $fpath = '';
                   3397:         my $fname = $file;
1.478     albertel 3398:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3399:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3400:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3401:         if ($action eq 'copy') {
                   3402:             if ($source eq '') {
                   3403:                 $fetchresult = 'no source file';
                   3404:                 return $fetchresult;
                   3405:             } else {
                   3406:                 my $destination = $filepath.'/'.$fname;
                   3407:                 rename($source,$destination);
                   3408:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3409:                                  $home);
1.481     raeburn  3410:             }
                   3411:         } elsif ($action eq 'uploaddoc') {
                   3412:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3413:             print $fh $env{'form.'.$source};
1.481     raeburn  3414:             close($fh);
1.637     raeburn  3415:             if ($parser eq 'parse') {
1.1024    raeburn  3416:                 my $mm = new File::MMagic;
1.1095    raeburn  3417:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3418:                 if ($type eq 'text/html') {
1.1024    raeburn  3419:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3420:                     unless ($parse_result eq 'ok') {
                   3421:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3422:                     }
1.637     raeburn  3423:                 }
1.1095    raeburn  3424:                 if (ref($mimetype)) {
                   3425:                     $$mimetype = $type;
                   3426:                 } 
1.637     raeburn  3427:             }
1.477     raeburn  3428:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3429:                                  $home);
1.481     raeburn  3430:             if ($fetchresult eq 'ok') {
                   3431:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3432:             } else {
                   3433:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3434:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3435:                 return '/adm/notfound.html';
                   3436:             }
1.477     raeburn  3437:         }
                   3438:     }
1.485     raeburn  3439:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3440:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3441:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3442:     }
                   3443:     return $fetchresult;
                   3444: }
                   3445: 
1.637     raeburn  3446: sub build_filepath {
                   3447:     my ($fpath) = @_;
                   3448:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3449:     unless ($fpath eq '') {
                   3450:         my @parts=split('/',$fpath);
                   3451:         foreach my $part (@parts) {
                   3452:             $filepath.= '/'.$part;
                   3453:             if ((-e $filepath)!=1) {
                   3454:                 mkdir($filepath,0777);
                   3455:             }
                   3456:         }
                   3457:     }
                   3458:     return $filepath;
                   3459: }
                   3460: 
                   3461: sub store_edited_file {
1.638     albertel 3462:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3463:     my $file = $primary_url;
                   3464:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3465:     my $fpath = '';
                   3466:     my $fname = $file;
                   3467:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3468:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3469:     my $filepath = &build_filepath($fpath);
                   3470:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3471:     print $fh $content;
                   3472:     close($fh);
1.638     albertel 3473:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3474:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3475: 			  $home);
1.637     raeburn  3476:     if ($$fetchresult eq 'ok') {
                   3477:         return '/uploaded/'.$fpath.'/'.$fname;
                   3478:     } else {
1.638     albertel 3479:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3480: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3481:         return '/adm/notfound.html';
                   3482:     }
                   3483: }
                   3484: 
1.531     albertel 3485: sub clean_filename {
1.831     albertel 3486:     my ($fname,$args)=@_;
1.315     www      3487: # Replace Windows backslashes by forward slashes
1.257     www      3488:     $fname=~s/\\/\//g;
1.831     albertel 3489:     if (!$args->{'keep_path'}) {
                   3490:         # Get rid of everything but the actual filename
                   3491: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3492:     }
1.315     www      3493: # Replace spaces by underscores
                   3494:     $fname=~s/\s+/\_/g;
                   3495: # Replace all other weird characters by nothing
1.831     albertel 3496:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3497: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3498: # numbers
                   3499:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3500:     return $fname;
                   3501: }
1.1051    raeburn  3502: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3503: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3504: # image with the same aspect ratio as the original, but with dimensions which do 
                   3505: # not exceed $resizewidth and $resizeheight.
                   3506:  
1.984     neumanie 3507: sub resizeImage {
1.1051    raeburn  3508:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3509:     my $ima = Image::Magick->new;
                   3510:     my $resized;
                   3511:     if (-e $img_path) {
                   3512:         $ima->Read($img_path);
                   3513:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3514:             my $width = $ima->Get('width');
                   3515:             my $height = $ima->Get('height');
                   3516:             if ($width > $resizewidth) {
                   3517: 	        my $factor = $width/$resizewidth;
                   3518:                 my $newheight = $height/$factor;
                   3519:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3520:                 $resized = 1;
                   3521:             }
                   3522:         }
                   3523:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3524:             my $width = $ima->Get('width');
                   3525:             my $height = $ima->Get('height');
                   3526:             if ($height > $resizeheight) {
                   3527:                 my $factor = $height/$resizeheight;
                   3528:                 my $newwidth = $width/$factor;
                   3529:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3530:                 $resized = 1;
                   3531:             }
                   3532:         }
                   3533:         if ($resized) {
                   3534:             $ima->Write($img_path);
                   3535:         }
                   3536:     }
                   3537:     return;
1.977     amueller 3538: }
                   3539: 
1.608     albertel 3540: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3541: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3542: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3543: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3544: #                                    canceloverwrite, or ''. 
                   3545: #                   if 'coursedoc': upload to the current course
                   3546: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3547: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3548: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3549: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3550: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3551: #        $allfiles - reference to hash for embedded objects
                   3552: #        $codebase - reference to hash for codebase of java objects
                   3553: #        $desuname - username for permanent storage of uploaded file
                   3554: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3555: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3556: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3557: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3558: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3559: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3560: #                    from File::MMagic.
1.858     raeburn  3561: # 
1.686     albertel 3562: # output: url of file in userspace, or error: <message> 
                   3563: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3564: 
1.531     albertel 3565: sub userfileupload {
1.1090    raeburn  3566:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3567:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3568:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3569:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3570:     $fname=&clean_filename($fname);
1.1090    raeburn  3571:     # See if there is anything left
1.257     www      3572:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3573:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3574:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3575:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3576:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3577:         my $now = time;
1.1090    raeburn  3578:         my $filepath;
1.1095    raeburn  3579:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3580:              $filepath = 'tmp/helprequests/'.$now;
                   3581:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3582:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3583:                          '_'.$env{'user.domain'}.'/pending';
                   3584:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3585:             my ($docuname,$docudom);
                   3586:             if ($destudom) {
                   3587:                 $docudom = $destudom;
                   3588:             } else {
                   3589:                 $docudom = $env{'user.domain'};
                   3590:             }
                   3591:             if ($destuname) {
                   3592:                 $docuname = $destuname;
                   3593:             } else {
                   3594:                 $docuname = $env{'user.name'};
                   3595:             }
                   3596:             if (exists($env{'form.group'})) {
                   3597:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3598:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3599:             }
                   3600:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3601:             if ($context eq 'canceloverwrite') {
                   3602:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3603:                 if (-e  $tempfile) {
                   3604:                     my @info = stat($tempfile);
                   3605:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3606:                         unlink($tempfile);
                   3607:                     }
                   3608:                 }
                   3609:                 return;
1.523     raeburn  3610:             }
                   3611:         }
1.1090    raeburn  3612:         # Create the directory if not present
1.741     raeburn  3613:         my @parts=split(/\//,$filepath);
                   3614:         my $fullpath = $perlvar{'lonDaemons'};
                   3615:         for (my $i=0;$i<@parts;$i++) {
                   3616:             $fullpath .= '/'.$parts[$i];
                   3617:             if ((-e $fullpath)!=1) {
                   3618:                 mkdir($fullpath,0777);
                   3619:             }
                   3620:         }
                   3621:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3622:         print $fh $env{'form.'.$formname};
                   3623:         close($fh);
1.1090    raeburn  3624:         if ($context eq 'existingfile') {
                   3625:             my @info = stat($fullpath.'/'.$fname);
                   3626:             return ($fullpath.'/'.$fname,$info[9]);
                   3627:         } else {
                   3628:             return $fullpath.'/'.$fname;
                   3629:         }
1.523     raeburn  3630:     }
1.995     raeburn  3631:     if ($subdir eq 'scantron') {
                   3632:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3633:     } else {
1.995     raeburn  3634:         $fname="$subdir/$fname";
                   3635:     }
1.1090    raeburn  3636:     if ($context eq 'coursedoc') {
1.638     albertel 3637: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3638: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3639:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3640:             return &finishuserfileupload($docuname,$docudom,
                   3641: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3642: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3643:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3644:         } else {
1.1218    raeburn  3645:             if ($env{'form.folder'}) {
                   3646:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3647:             }
1.638     albertel 3648:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3649: 				       $fname,$formname,$parser,
1.1095    raeburn  3650: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3651:         }
1.719     banghart 3652:     } elsif (defined($destuname)) {
                   3653:         my $docuname=$destuname;
                   3654:         my $docudom=$destudom;
1.860     raeburn  3655: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3656: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3657:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3658:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3659:     } else {
1.638     albertel 3660:         my $docuname=$env{'user.name'};
                   3661:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3662:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3663:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3664:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3665:         }
1.860     raeburn  3666: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3667: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3668:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3669:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3670:     }
1.271     www      3671: }
                   3672: 
                   3673: sub finishuserfileupload {
1.860     raeburn  3674:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3675:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3676:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3677:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3678:   
1.860     raeburn  3679:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3680:     $file=$fname;
                   3681:     if ($fname=~m|/|) {
                   3682:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3683: 	$path.=$fnamepath.'/';
                   3684:     }
1.259     www      3685:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3686:     my $count;
                   3687:     for ($count=4;$count<=$#parts;$count++) {
                   3688:         $filepath.="/$parts[$count]";
                   3689:         if ((-e $filepath)!=1) {
                   3690: 	    mkdir($filepath,0777);
                   3691:         }
                   3692:     }
1.984     neumanie 3693: 
1.258     www      3694: # Save the file
                   3695:     {
1.701     albertel 3696: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3697: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3698: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3699: 	    return '/adm/notfound.html';
                   3700: 	}
1.1090    raeburn  3701:         if ($context eq 'overwrite') {
1.1117    foxr     3702:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3703:             my $target = $filepath.'/'.$file;
                   3704:             if (-e $source) {
                   3705:                 my @info = stat($source);
                   3706:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3707:                     unless (&File::Copy::move($source,$target)) {
                   3708:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3709:                         return "Moving from $source failed";
                   3710:                     }
                   3711:                 } else {
                   3712:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3713:                 }
                   3714:             } else {
                   3715:                 return "Temporary file: $source missing";
                   3716:             }
                   3717:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3718: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3719: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3720: 	    return '/adm/notfound.html';
                   3721: 	}
1.570     albertel 3722: 	close(FH);
1.1051    raeburn  3723:         if ($resizewidth && $resizeheight) {
                   3724:             my $mm = new File::MMagic;
                   3725:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3726:             if ($mime_type =~ m{^image/}) {
                   3727: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3728:             }  
1.977     amueller 3729: 	}
1.258     www      3730:     }
1.1152    raeburn  3731:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3732:         if (ref($mimetype)) {
                   3733:             if ($$mimetype eq '') {
                   3734:                 my $mm = new File::MMagic;
                   3735:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3736:                 $$mimetype = $type;
                   3737:             }
                   3738:         }
                   3739:     }
1.637     raeburn  3740:     if ($parser eq 'parse') {
1.1152    raeburn  3741:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3742:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3743:                                                        $allfiles,$codebase);
                   3744:             unless ($parse_result eq 'ok') {
                   3745:                 &logthis('Failed to parse '.$filepath.$file.
                   3746: 	   	         ' for embedded media: '.$parse_result); 
                   3747:             }
1.637     raeburn  3748:         }
                   3749:     }
1.860     raeburn  3750:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3751:         my $input = $filepath.'/'.$file;
                   3752:         my $output = $filepath.'/'.'tn-'.$file;
                   3753:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3754:         system("convert -sample $thumbsize $input $output");
                   3755:         if (-e $filepath.'/'.'tn-'.$file) {
                   3756:             $fetchthumb  = 1; 
                   3757:         }
                   3758:     }
1.858     raeburn  3759:  
1.259     www      3760: # Notify homeserver to grep it
                   3761: #
1.984     neumanie 3762:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3763:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3764:     if ($fetchresult eq 'ok') {
1.860     raeburn  3765:         if ($fetchthumb) {
                   3766:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3767:             if ($thumbresult ne 'ok') {
                   3768:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3769:                          $docuhome.': '.$thumbresult);
                   3770:             }
                   3771:         }
1.259     www      3772: #
1.258     www      3773: # Return the URL to it
1.494     albertel 3774:         return '/uploaded/'.$path.$file;
1.263     www      3775:     } else {
1.494     albertel 3776:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3777: 		 ': '.$fetchresult);
1.263     www      3778:         return '/adm/notfound.html';
1.858     raeburn  3779:     }
1.493     albertel 3780: }
                   3781: 
1.637     raeburn  3782: sub extract_embedded_items {
1.961     raeburn  3783:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3784:     my @state = ();
1.1164    raeburn  3785:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3786:     my %javafiles = (
                   3787:                       codebase => '',
                   3788:                       code => '',
                   3789:                       archive => ''
                   3790:                     );
                   3791:     my %mediafiles = (
                   3792:                       src => '',
                   3793:                       movie => '',
                   3794:                      );
1.648     raeburn  3795:     my $p;
                   3796:     if ($content) {
                   3797:         $p = HTML::LCParser->new($content);
                   3798:     } else {
1.961     raeburn  3799:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3800:     }
1.641     albertel 3801:     while (my $t=$p->get_token()) {
1.640     albertel 3802: 	if ($t->[0] eq 'S') {
                   3803: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3804: 	    push(@state, $tagname);
1.648     raeburn  3805:             if (lc($tagname) eq 'allow') {
                   3806:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3807:             }
1.640     albertel 3808: 	    if (lc($tagname) eq 'img') {
                   3809: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3810: 	    }
1.886     albertel 3811: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3812:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3813:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3814:                 }
1.886     albertel 3815: 	    }
1.645     raeburn  3816:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3817:                 my $src;
1.645     raeburn  3818:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3819:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3820:                 } else {
1.1164    raeburn  3821:                     if ($attr->{'src'} ne '') {
                   3822:                         $src = $attr->{'src'};
                   3823:                         &add_filetype($allfiles,$src,'src');
                   3824:                     }
                   3825:                 }
                   3826:                 my $text = $p->get_trimmed_text();
                   3827:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3828:                     my @swfargs = split(/,/,$1);
                   3829:                     foreach my $item (@swfargs) {
                   3830:                         $item =~ s/["']//g;
                   3831:                         $item =~ s/^\s+//;
                   3832:                         $item =~ s/\s+$//;
                   3833:                     }
                   3834:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3835:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3836:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3837:                         } else {
                   3838:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3839:                         }
                   3840:                     }
1.645     raeburn  3841:                 }
                   3842:             }
                   3843:             if (lc($tagname) eq 'link') {
                   3844:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3845:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3846:                 }
                   3847:             }
1.640     albertel 3848: 	    if (lc($tagname) eq 'object' ||
                   3849: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3850: 		foreach my $item (keys(%javafiles)) {
                   3851: 		    $javafiles{$item} = '';
                   3852: 		}
1.1164    raeburn  3853:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3854:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3855:                 }
1.640     albertel 3856: 	    }
                   3857: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3858: 		my $name = lc($attr->{'name'});
                   3859: 		foreach my $item (keys(%javafiles)) {
                   3860: 		    if ($name eq $item) {
                   3861: 			$javafiles{$item} = $attr->{'value'};
                   3862: 			last;
                   3863: 		    }
                   3864: 		}
1.1164    raeburn  3865:                 my $pathfrom;
1.640     albertel 3866: 		foreach my $item (keys(%mediafiles)) {
                   3867: 		    if ($name eq $item) {
1.1164    raeburn  3868:                         $pathfrom = $attr->{'value'};
                   3869:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3870: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3871: 			last;
                   3872: 		    }
                   3873: 		}
1.1164    raeburn  3874:                 if ($name eq 'flashvars') {
                   3875:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3876:                 }
                   3877:                 if ($pathfrom ne '') {
                   3878:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3879:                                          $pathfrom);
                   3880:                 }
1.640     albertel 3881: 	    }
                   3882: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3883: 		foreach my $item (keys(%javafiles)) {
                   3884: 		    if ($attr->{$item}) {
                   3885: 			$javafiles{$item} = $attr->{$item};
                   3886: 			last;
                   3887: 		    }
                   3888: 		}
                   3889: 		foreach my $item (keys(%mediafiles)) {
                   3890: 		    if ($attr->{$item}) {
                   3891: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3892: 			last;
                   3893: 		    }
                   3894: 		}
1.1164    raeburn  3895:                 if (lc($tagname) eq 'embed') {
                   3896:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3897:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3898:                                              $attr->{'src'});
                   3899:                     }
                   3900:                 }
1.640     albertel 3901: 	    }
1.1243    raeburn  3902:             if (lc($tagname) eq 'iframe') {
                   3903:                 my $src = $attr->{'src'} ;
                   3904:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3905:                     &add_filetype($allfiles,$src,'src');
                   3906:                 } elsif ($src =~ m{^/}) {
                   3907:                     if ($env{'request.course.id'}) {
                   3908:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3909:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3910:                         my $url = &hreflocation('',$fullpath);
                   3911:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3912:                             my $relpath = $1;
                   3913:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3914:                                 &add_filetype($allfiles,$1,'src');
                   3915:                             }
                   3916:                         }
                   3917:                     }
                   3918:                 }
                   3919:             }
1.1164    raeburn  3920:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3921:                 pop(@state);
1.1164    raeburn  3922:             }
1.640     albertel 3923: 	} elsif ($t->[0] eq 'E') {
                   3924: 	    my ($tagname) = ($t->[1]);
                   3925: 	    if ($javafiles{'codebase'} ne '') {
                   3926: 		$javafiles{'codebase'} .= '/';
                   3927: 	    }  
                   3928: 	    if (lc($tagname) eq 'applet' ||
                   3929: 		lc($tagname) eq 'object' ||
                   3930: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3931: 		) {
                   3932: 		foreach my $item (keys(%javafiles)) {
                   3933: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3934: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3935: 			&add_filetype($allfiles,$file,$item);
                   3936: 		    }
                   3937: 		}
                   3938: 	    } 
                   3939: 	    pop @state;
                   3940: 	}
                   3941:     }
1.1164    raeburn  3942:     foreach my $id (sort(keys(%flashvars))) {
                   3943:         if ($shockwave{$id} ne '') {
                   3944:             my @pairs = split(/\&/,$flashvars{$id});
                   3945:             foreach my $pair (@pairs) {
                   3946:                 my ($key,$value) = split(/\=/,$pair);
                   3947:                 if ($key eq 'thumb') {
                   3948:                     &add_filetype($allfiles,$value,$key);
                   3949:                 } elsif ($key eq 'content') {
                   3950:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3951:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3952:                     if ($ext ne '') {
                   3953:                         &add_filetype($allfiles,$path.$value,$ext);
                   3954:                     }
                   3955:                 }
                   3956:             }
                   3957:         }
                   3958:     }
1.637     raeburn  3959:     return 'ok';
                   3960: }
                   3961: 
1.639     albertel 3962: sub add_filetype {
                   3963:     my ($allfiles,$file,$type)=@_;
                   3964:     if (exists($allfiles->{$file})) {
                   3965: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3966: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3967: 	}
                   3968:     } else {
                   3969: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3970:     }
                   3971: }
                   3972: 
1.1164    raeburn  3973: sub embedded_dependency {
                   3974:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3975:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3976:         if (($identifier ne '') &&
                   3977:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3978:             ($pathfrom ne '')) {
                   3979:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3980:             foreach my $dep (@{$related->{$identifier}}) {
                   3981:                 &add_filetype($allfiles,$path.$dep,'object');
                   3982:             }
                   3983:         }
                   3984:     }
                   3985:     return;
                   3986: }
                   3987: 
1.493     albertel 3988: sub removeuploadedurl {
1.984     neumanie 3989:     my ($url)=@_;	
                   3990:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3991:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3992: }
                   3993: 
                   3994: sub removeuserfile {
                   3995:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3996:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3997:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3998:     if ($result eq 'ok') {	
1.798     raeburn  3999:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4000:             my $metafile = $fname.'.meta';
                   4001:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4002: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4003:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4004:             my $sqlresult = 
1.823     albertel 4005:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4006:                                         'portfolio_metadata',$group,
                   4007:                                         'delete');
1.798     raeburn  4008:         }
                   4009:     }
                   4010:     return $result;
1.257     www      4011: }
1.15      www      4012: 
1.530     albertel 4013: sub mkdiruserfile {
                   4014:     my ($docuname,$docudom,$dir)=@_;
                   4015:     my $home=&homeserver($docuname,$docudom);
                   4016:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4017: }
                   4018: 
1.531     albertel 4019: sub renameuserfile {
                   4020:     my ($docuname,$docudom,$old,$new)=@_;
                   4021:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4022:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4023:                         &escape("$old").':'.&escape("$new"),$home);
                   4024:     if ($result eq 'ok') {
                   4025:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4026:             my $oldmeta = $old.'.meta';
                   4027:             my $newmeta = $new.'.meta';
                   4028:             my $metaresult = 
                   4029:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4030: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4031:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4032:             my $sqlresult = 
1.823     albertel 4033:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4034:                                         'portfolio_metadata',$group,
                   4035:                                         'delete');
1.798     raeburn  4036:         }
                   4037:     }
                   4038:     return $result;
1.531     albertel 4039: }
                   4040: 
1.14      www      4041: # ------------------------------------------------------------------------- Log
                   4042: 
                   4043: sub log {
                   4044:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4045:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4046: }
                   4047: 
                   4048: # ------------------------------------------------------------------ Course Log
1.352     www      4049: #
                   4050: # This routine flushes several buffers of non-mission-critical nature
                   4051: #
1.157     www      4052: 
                   4053: sub flushcourselogs {
1.352     www      4054:     &logthis('Flushing log buffers');
                   4055: #
                   4056: # course logs
                   4057: # This is a log of all transactions in a course, which can be used
                   4058: # for data mining purposes
                   4059: #
                   4060: # It also collects the courseid database, which lists last transaction
                   4061: # times and course titles for all courseids
                   4062: #
                   4063:     my %courseidbuffer=();
1.921     raeburn  4064:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4065:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4066: 		          &escape($courselogs{$crsid}),
                   4067: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4068: 	    delete $courselogs{$crsid};
                   4069:         } else {
                   4070:             &logthis('Failed to flush log buffer for '.$crsid);
                   4071:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4072:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4073:                         " exceeded maximum size, deleting.</font>");
                   4074:                delete $courselogs{$crsid};
                   4075:             }
1.352     www      4076:         }
1.920     raeburn  4077:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4078:             'description' => $coursedescrbuf{$crsid},
                   4079:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4080:             'type'        => $coursetypebuf{$crsid},
                   4081:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4082:         };
1.191     harris41 4083:     }
1.352     www      4084: #
                   4085: # Write course id database (reverse lookup) to homeserver of courses 
                   4086: # Is used in pickcourse
                   4087: #
1.840     albertel 4088:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4089:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4090:                                     $courseidbuffer{$crs_home},
                   4091:                                     $crs_home,'timeonly');
1.352     www      4092:     }
                   4093: #
                   4094: # File accesses
                   4095: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4096: #
1.449     matthew  4097:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4098:         if ($entry =~ /___count$/) {
                   4099:             my ($dom,$name);
1.807     albertel 4100:             ($dom,$name,undef)=
1.811     albertel 4101: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4102:             if (! defined($dom) || $dom eq '' || 
                   4103:                 ! defined($name) || $name eq '') {
1.620     albertel 4104:                 my $cid = $env{'request.course.id'};
                   4105:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4106:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4107:             }
1.450     matthew  4108:             my $value = $accesshash{$entry};
                   4109:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4110:             my %temphash=($url => $value);
1.449     matthew  4111:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4112:             if ($result eq 'ok') {
                   4113:                 delete $accesshash{$entry};
                   4114:             }
                   4115:         } else {
1.811     albertel 4116:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4117:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4118:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4119:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4120:                 delete $accesshash{$entry};
                   4121:             }
1.185     www      4122:         }
1.191     harris41 4123:     }
1.352     www      4124: #
                   4125: # Roles
                   4126: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4127: #
1.800     albertel 4128:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4129:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4130: 	    split(/\:/,$entry);
                   4131:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4132:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4133:                 $rudom,$runame) eq 'ok') {
                   4134: 	    delete $userrolehash{$entry};
                   4135:         }
                   4136:     }
1.662     raeburn  4137: #
1.1334    raeburn  4138: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4139: #
                   4140:     my %domrolebuffer = ();
1.1000    raeburn  4141:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4142:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4143:         if ($domrolebuffer{$rudom}) {
                   4144:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4145:                       '='.&escape($domainrolehash{$entry});
                   4146:         } else {
                   4147:             $domrolebuffer{$rudom}.=&escape($entry).
                   4148:                       '='.&escape($domainrolehash{$entry});
                   4149:         }
                   4150:         delete $domainrolehash{$entry};
                   4151:     }
                   4152:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4153: 	my %servers;
                   4154: 	if (defined(&domain($dom,'primary'))) {
                   4155: 	    my $primary=&domain($dom,'primary');
                   4156: 	    my $hostname=&hostname($primary);
                   4157: 	    $servers{$primary} = $hostname;
                   4158: 	} else { 
                   4159: 	    %servers = &get_servers($dom,'library');
                   4160: 	}
1.841     albertel 4161: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4162: 	    if (&reply('domroleput:'.$dom.':'.
                   4163: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4164: 		last;
                   4165: 	    } else {  
1.841     albertel 4166: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4167: 	    }
1.662     raeburn  4168:         }
                   4169:     }
1.186     www      4170:     $dumpcount++;
1.157     www      4171: }
                   4172: 
                   4173: sub courselog {
                   4174:     my $what=shift;
1.158     www      4175:     $what=time.':'.$what;
1.620     albertel 4176:     unless ($env{'request.course.id'}) { return ''; }
                   4177:     $coursedombuf{$env{'request.course.id'}}=
                   4178:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4179:     $coursenumbuf{$env{'request.course.id'}}=
                   4180:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4181:     $coursehombuf{$env{'request.course.id'}}=
                   4182:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4183:     $coursedescrbuf{$env{'request.course.id'}}=
                   4184:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4185:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4186:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4187:     $courseownerbuf{$env{'request.course.id'}}=
                   4188:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4189:     $coursetypebuf{$env{'request.course.id'}}=
                   4190:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4191:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4192: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4193:     } else {
1.620     albertel 4194: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4195:     }
1.620     albertel 4196:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4197: 	&flushcourselogs();
                   4198:     }
1.158     www      4199: }
                   4200: 
                   4201: sub courseacclog {
                   4202:     my $fnsymb=shift;
1.620     albertel 4203:     unless ($env{'request.course.id'}) { return ''; }
                   4204:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4205:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4206:         $what.=':POST';
1.583     matthew  4207:         # FIXME: Probably ought to escape things....
1.800     albertel 4208: 	foreach my $key (keys(%env)) {
                   4209:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4210:                 my $formitem = $1;
                   4211:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4212:                     $what.=':'.$formitem.'='.$env{$key};
                   4213:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4214:                     $what.=':'.$formitem.'='.$env{$key};
                   4215:                 }
1.158     www      4216:             }
1.191     harris41 4217:         }
1.583     matthew  4218:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4219:         # FIXME: We should not be depending on a form parameter that someone
                   4220:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4221:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4222:             $what.= ':POST';
                   4223:             # FIXME: Probably ought to escape things....
                   4224:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4225:                                  'crsdiscuss') {
1.620     albertel 4226:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4227:             }
                   4228:         }
1.158     www      4229:     }
                   4230:     &courselog($what);
1.149     www      4231: }
                   4232: 
1.185     www      4233: sub countacc {
                   4234:     my $url=&declutter(shift);
1.458     matthew  4235:     return if (! defined($url) || $url eq '');
1.620     albertel 4236:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4237: #
                   4238: # Mark that this url was used in this course
                   4239: #
1.620     albertel 4240:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4241: #
                   4242: # Increase the access count for this resource in this child process
                   4243: #
1.281     www      4244:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4245:     $accesshash{$key}++;
1.185     www      4246: }
1.349     www      4247: 
1.361     www      4248: sub linklog {
                   4249:     my ($from,$to)=@_;
                   4250:     $from=&declutter($from);
                   4251:     $to=&declutter($to);
                   4252:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4253:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4254: }
1.1160    www      4255: 
                   4256: sub statslog {
                   4257:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4258:     if ($users<2) { return; }
                   4259:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4260:             'course'       => $env{'request.course.id'},
                   4261:             'sections'     => '"all"',
                   4262:             'num_students' => $users,
                   4263:             'part'         => $part,
                   4264:             'symb'         => $symb,
                   4265:             'mean_tries'   => $av_attempts,
                   4266:             'deg_of_diff'  => $degdiff});
                   4267:     foreach my $key (keys(%dynstore)) {
                   4268:         $accesshash{$key}=$dynstore{$key};
                   4269:     }
                   4270: }
1.361     www      4271:   
1.349     www      4272: sub userrolelog {
                   4273:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4274:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4275:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4276:        $userrolehash
                   4277:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4278:                     =$tend.':'.$tstart;
1.662     raeburn  4279:     }
1.1169    droeschl 4280:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4281:        $userrolehash
                   4282:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4283:                     =$tend.':'.$tstart;
                   4284:     }
1.1334    raeburn  4285:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4286:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4287:        $domainrolehash
                   4288:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4289:                     = $tend.':'.$tstart;
                   4290:     }
1.351     www      4291: }
                   4292: 
1.957     raeburn  4293: sub courserolelog {
                   4294:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4295:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4296:         my $cdom = $1;
                   4297:         my $cnum = $2;
                   4298:         my $sec = $3;
                   4299:         my $namespace = 'rolelog';
                   4300:         my %storehash = (
                   4301:                            role    => $trole,
                   4302:                            start   => $tstart,
                   4303:                            end     => $tend,
                   4304:                            selfenroll => $selfenroll,
                   4305:                            context    => $context,
                   4306:                         );
                   4307:         if ($trole eq 'gr') {
                   4308:             $namespace = 'groupslog';
                   4309:             $storehash{'group'} = $sec;
                   4310:         } else {
                   4311:             $storehash{'section'} = $sec;
                   4312:         }
1.1188    raeburn  4313:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4314:                    $domain,$cnum,$cdom);
1.1184    raeburn  4315:         if (($trole ne 'st') || ($sec ne '')) {
                   4316:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4317:         }
                   4318:     }
                   4319:     return;
                   4320: }
                   4321: 
1.1184    raeburn  4322: sub domainrolelog {
                   4323:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4324:     if ($area =~ m{^/($match_domain)/$}) {
                   4325:         my $cdom = $1;
                   4326:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4327:         my $namespace = 'rolelog';
                   4328:         my %storehash = (
                   4329:                            role    => $trole,
                   4330:                            start   => $tstart,
                   4331:                            end     => $tend,
                   4332:                            context => $context,
                   4333:                         );
1.1188    raeburn  4334:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4335:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4336:     }
                   4337:     return;
                   4338: 
                   4339: }
                   4340: 
                   4341: sub coauthorrolelog {
                   4342:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4343:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4344:         my $audom = $1;
                   4345:         my $auname = $2;
                   4346:         my $namespace = 'rolelog';
                   4347:         my %storehash = (
                   4348:                            role    => $trole,
                   4349:                            start   => $tstart,
                   4350:                            end     => $tend,
                   4351:                            context => $context,
                   4352:                         );
1.1188    raeburn  4353:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4354:                    $domain,$auname,$audom);
1.1184    raeburn  4355:     }
                   4356:     return;
                   4357: }
                   4358: 
1.351     www      4359: sub get_course_adv_roles {
1.948     raeburn  4360:     my ($cid,$codes) = @_;
1.620     albertel 4361:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4362:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4363:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4364:     my %nothide=();
1.800     albertel 4365:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4366:         if ($user !~ /:/) {
                   4367: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4368:         } else {
                   4369:             $nothide{$user}=1;
                   4370:         }
1.470     www      4371:     }
1.1219    raeburn  4372:     my @possdoms = ($coursehash{'domain'});
                   4373:     if ($coursehash{'checkforpriv'}) {
                   4374:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4375:     }
1.351     www      4376:     my %returnhash=();
                   4377:     my %dumphash=
                   4378:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4379:     my $now=time;
1.997     raeburn  4380:     my %privileged;
1.1000    raeburn  4381:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4382: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4383:         if (($tstart) && ($tstart<0)) { next; }
                   4384:         if (($tend) && ($tend<$now)) { next; }
                   4385:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4386:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4387: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4388:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4389:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4390: 	if ($role eq 'cr') { next; }
1.948     raeburn  4391:         if ($codes) {
                   4392:             if ($section) { $role .= ':'.$section; }
                   4393:             if ($returnhash{$role}) {
                   4394:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4395:             } else {
                   4396:                 $returnhash{$role}=$username.':'.$domain;
                   4397:             }
1.351     www      4398:         } else {
1.988     raeburn  4399:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4400:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4401:             if ($returnhash{$key}) {
                   4402: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4403:             } else {
                   4404:                 $returnhash{$key}=$username.':'.$domain;
                   4405:             }
1.351     www      4406:         }
1.948     raeburn  4407:     }
1.400     www      4408:     return %returnhash;
                   4409: }
                   4410: 
                   4411: sub get_my_roles {
1.937     raeburn  4412:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4413:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4414:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4415:     my (%dumphash,%nothide);
1.1086    raeburn  4416:     if ($context eq 'userroles') {
1.1166    raeburn  4417:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4418:     } else {
1.1219    raeburn  4419:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4420:         if ($hidepriv) {
                   4421:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4422:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4423:                 if ($user !~ /:/) {
                   4424:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4425:                 } else {
                   4426:                     $nothide{$user} = 1;
                   4427:                 }
                   4428:             }
                   4429:         }
1.858     raeburn  4430:     }
1.400     www      4431:     my %returnhash=();
                   4432:     my $now=time;
1.999     raeburn  4433:     my %privileged;
1.800     albertel 4434:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4435:         my ($role,$tend,$tstart);
                   4436:         if ($context eq 'userroles') {
1.1149    raeburn  4437:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4438: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4439:         } else {
                   4440:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4441:         }
1.400     www      4442:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4443:         my $status = 'active';
1.939     raeburn  4444:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4445:             $status = 'previous';
                   4446:         } 
                   4447:         if (($tstart) && ($now<$tstart)) {
                   4448:             $status = 'future';
                   4449:         }
                   4450:         if (ref($types) eq 'ARRAY') {
                   4451:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4452:                 next;
                   4453:             } 
                   4454:         } else {
                   4455:             if ($status ne 'active') {
                   4456:                 next;
                   4457:             }
                   4458:         }
1.867     raeburn  4459:         my ($rolecode,$username,$domain,$section,$area);
                   4460:         if ($context eq 'userroles') {
1.1186    raeburn  4461:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4462:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4463:         } else {
                   4464:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4465:         }
1.832     raeburn  4466:         if (ref($roledoms) eq 'ARRAY') {
                   4467:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4468:                 next;
                   4469:             }
                   4470:         }
                   4471:         if (ref($roles) eq 'ARRAY') {
                   4472:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4473:                 if ($role =~ /^cr\//) {
                   4474:                     if (!grep(/^cr$/,@{$roles})) {
                   4475:                         next;
                   4476:                     }
1.1104    raeburn  4477:                 } elsif ($role =~ /^gr\//) {
                   4478:                     if (!grep(/^gr$/,@{$roles})) {
                   4479:                         next;
                   4480:                     }
1.922     raeburn  4481:                 } else {
                   4482:                     next;
                   4483:                 }
1.832     raeburn  4484:             }
1.867     raeburn  4485:         }
1.937     raeburn  4486:         if ($hidepriv) {
1.1219    raeburn  4487:             my @privroles = ('dc','su');
1.999     raeburn  4488:             if ($context eq 'userroles') {
1.1219    raeburn  4489:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4490:             } else {
1.1219    raeburn  4491:                 my $possdoms = [$domain];
                   4492:                 if (ref($roledoms) eq 'ARRAY') {
                   4493:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4494:                 }
1.1219    raeburn  4495:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4496:                     if (!$nothide{$username.':'.$domain}) {
                   4497:                         next;
                   4498:                     }
                   4499:                 }
1.937     raeburn  4500:             }
                   4501:         }
1.933     raeburn  4502:         if ($withsec) {
                   4503:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4504:                 $tstart.':'.$tend;
                   4505:         } else {
                   4506:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4507:         }
1.832     raeburn  4508:     }
1.373     www      4509:     return %returnhash;
1.399     www      4510: }
                   4511: 
1.1333    raeburn  4512: sub get_all_adhocroles {
                   4513:     my ($dom) = @_;
                   4514:     my @roles_by_num = ();
                   4515:     my %domdefaults = &get_domain_defaults($dom);
                   4516:     my (%description,%access_in_dom,%access_info);
                   4517:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4518:         my $count = 0;
                   4519:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4520:         my %ordered;
                   4521:         foreach my $role (sort(keys(%domcurrent))) {
                   4522:             my ($order,$desc,$access_in_dom);
                   4523:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4524:                 $order = $domcurrent{$role}{'order'};
                   4525:                 $desc = $domcurrent{$role}{'desc'};
                   4526:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4527:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4528:             }
                   4529:             if ($order eq '') {
                   4530:                 $order = $count;
                   4531:             }
                   4532:             $ordered{$order} = $role;
                   4533:             if ($desc ne '') {
                   4534:                 $description{$role} = $desc;
                   4535:             } else {
                   4536:                 $description{$role}= $role;
                   4537:             }
                   4538:             $count++;
                   4539:         }
                   4540:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4541:             push(@roles_by_num,$ordered{$item});
                   4542:         }
                   4543:     }
                   4544:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4545: }
                   4546: 
1.1332    raeburn  4547: sub get_my_adhocroles {
1.1333    raeburn  4548:     my ($cid,$checkreg) = @_;
                   4549:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4550:     if ($env{'request.course.id'} eq $cid) {
                   4551:         $cdom = $env{'course.'.$cid.'.domain'};
                   4552:         $cnum = $env{'course.'.$cid.'.num'};
                   4553:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4554:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4555:         $cdom = $1;
                   4556:         $cnum = $2;
                   4557:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4558:                                      $cdom,$cnum);
                   4559:     }
                   4560:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4561:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4562:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4563:         if ($rosterhash{$user} ne '') {
                   4564:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4565:             return ([],{}) if ($type eq 'auto');
                   4566:         }
                   4567:     }
                   4568:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4569:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4570:             my $then=$env{'user.login.time'};
                   4571:             my $update=$env{'user.update.time'};
1.1335    raeburn  4572:             if (!$update) {
                   4573:                 $update = $then;
                   4574:             }
                   4575:             my @liveroles;
1.1334    raeburn  4576:             foreach my $role ('dh','da') {
                   4577:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4578:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4579:                     my $limit = $update;
                   4580:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4581:                         $limit = $then;
                   4582:                     }
1.1335    raeburn  4583:                     my $activerole = 1;
                   4584:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4585:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4586:                     if ($activerole) {
                   4587:                         push(@liveroles,$role);
                   4588:                     }
1.1334    raeburn  4589:                 }
1.1332    raeburn  4590:             }
1.1335    raeburn  4591:             if (@liveroles) {
1.1332    raeburn  4592:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4593:                     my ($accessref,$accessinfo,%access_in_dom);
                   4594:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4595:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4596:                         if (@{$roles_by_num}) {
1.1332    raeburn  4597:                             my %settings;
                   4598:                             if ($env{'request.course.id'} eq $cid) {
                   4599:                                 foreach my $envkey (keys(%env)) {
                   4600:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4601:                                         $settings{$1} = $env{$envkey};
                   4602:                                     }
                   4603:                                 }
                   4604:                             } else {
                   4605:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4606:                             }
                   4607:                             my %setincrs;
                   4608:                             if ($settings{'internal.adhocaccess'}) {
                   4609:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4610:                             }
                   4611:                             my @statuses;
                   4612:                             if ($env{'environment.inststatus'}) {
                   4613:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4614:                             }
                   4615:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4616:                             if (ref($accessref) eq 'HASH') {
                   4617:                                 %access_in_dom = %{$accessref};
                   4618:                             }
                   4619:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4620:                                 my ($curraccess,@okstatus,@personnel);
                   4621:                                 if ($setincrs{$role}) {
                   4622:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4623:                                     if ($curraccess eq 'status') {
                   4624:                                         @okstatus = split(/\&/,$rest);
                   4625:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4626:                                         @personnel = split(/\&/,$rest);
                   4627:                                     }
                   4628:                                 } else {
                   4629:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4630:                                     if (ref($accessinfo) eq 'HASH') {
                   4631:                                         if ($curraccess eq 'status') {
                   4632:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4633:                                                 @okstatus = @{$accessinfo->{$role}};
                   4634:                                             }
                   4635:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4636:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4637:                                                 @personnel = @{$accessinfo->{$role}};
                   4638:                                             }
1.1332    raeburn  4639:                                         }
                   4640:                                     }
                   4641:                                 }
                   4642:                                 if ($curraccess eq 'none') {
                   4643:                                     next;
                   4644:                                 } elsif ($curraccess eq 'all') {
                   4645:                                     push(@possroles,$role);
1.1336    raeburn  4646:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4647:                                     if (grep(/^dh$/,@liveroles)) {
                   4648:                                         push(@possroles,$role);
                   4649:                                     } else {
                   4650:                                         next;
                   4651:                                     }
1.1336    raeburn  4652:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4653:                                     if (grep(/^da$/,@liveroles)) {
                   4654:                                         push(@possroles,$role);
                   4655:                                     } else {
                   4656:                                         next;
                   4657:                                     }
1.1332    raeburn  4658:                                 } elsif ($curraccess eq 'status') {
                   4659:                                     if (@okstatus) {
                   4660:                                         if (!@statuses) {
                   4661:                                             if (grep(/^default$/,@okstatus)) {
                   4662:                                                 push(@possroles,$role);
                   4663:                                             }
                   4664:                                         } else {
                   4665:                                             foreach my $status (@okstatus) {
                   4666:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4667:                                                     push(@possroles,$role);
                   4668:                                                     last;
                   4669:                                                 }
                   4670:                                             }
                   4671:                                         }
                   4672:                                     }
                   4673:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4674:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4675:                                         if ($curraccess eq 'exc') {
                   4676:                                             push(@possroles,$role);
                   4677:                                         }
                   4678:                                     } elsif ($curraccess eq 'inc') {
                   4679:                                         push(@possroles,$role);
                   4680:                                     }
                   4681:                                 }
                   4682:                             }
                   4683:                         }
                   4684:                     }
                   4685:                 }
                   4686:             }
                   4687:         }
                   4688:     }
1.1333    raeburn  4689:     unless (ref($description) eq 'HASH') {
                   4690:         if (ref($roles_by_num) eq 'ARRAY') {
                   4691:             my %desc;
                   4692:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4693:             $description = \%desc;
                   4694:         } else {
                   4695:             $description = {};
                   4696:         }
                   4697:     }
                   4698:     return (\@possroles,$description);
1.1332    raeburn  4699: }
                   4700: 
1.399     www      4701: # ----------------------------------------------------- Frontpage Announcements
                   4702: #
                   4703: #
                   4704: 
                   4705: sub postannounce {
                   4706:     my ($server,$text)=@_;
1.844     albertel 4707:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4708:     unless ($text=~/\w/) { $text=''; }
                   4709:     return &reply('setannounce:'.&escape($text),$server);
                   4710: }
                   4711: 
                   4712: sub getannounce {
1.448     albertel 4713: 
                   4714:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4715: 	my $announcement='';
1.800     albertel 4716: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4717: 	close($fh);
1.399     www      4718: 	if ($announcement=~/\w/) { 
                   4719: 	    return 
                   4720:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4721:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4722: 	} else {
                   4723: 	    return '';
                   4724: 	}
                   4725:     } else {
                   4726: 	return '';
                   4727:     }
1.351     www      4728: }
1.353     www      4729: 
                   4730: # ---------------------------------------------------------- Course ID routines
                   4731: # Deal with domain's nohist_courseid.db files
                   4732: #
                   4733: 
                   4734: sub courseidput {
1.921     raeburn  4735:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4736:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4737:     my $outcome;
                   4738:     if ($caller eq 'timeonly') {
                   4739:         my $cids = '';
                   4740:         foreach my $item (keys(%$storehash)) {
                   4741:             $cids.=&escape($item).'&';
                   4742:         }
                   4743:         $cids=~s/\&$//;
                   4744:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4745:                           $coursehome);       
                   4746:     } else {
                   4747:         my $items = '';
                   4748:         foreach my $item (keys(%$storehash)) {
                   4749:             $items.= &escape($item).'='.
                   4750:                      &freeze_escape($$storehash{$item}).'&';
                   4751:         }
                   4752:         $items=~s/\&$//;
                   4753:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4754:                           $coursehome);
1.918     raeburn  4755:     }
                   4756:     if ($outcome eq 'unknown_cmd') {
                   4757:         my $what;
                   4758:         foreach my $cid (keys(%$storehash)) {
                   4759:             $what .= &escape($cid).'=';
1.921     raeburn  4760:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4761:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4762:             }
                   4763:             $what =~ s/\:$/&/;
                   4764:         }
                   4765:         $what =~ s/\&$//;  
                   4766:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4767:     } else {
                   4768:         return $outcome;
                   4769:     }
1.353     www      4770: }
                   4771: 
                   4772: sub courseiddump {
1.921     raeburn  4773:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4774:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4775:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4776:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4777:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4778:     my $as_hash = 1;
                   4779:     my %returnhash;
                   4780:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4781:     my %libserv = &all_library();
                   4782:     foreach my $tryserver (keys(%libserv)) {
                   4783:         if ( (  $hostidflag == 1 
                   4784: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4785: 	     || (!defined($hostidflag)) ) {
                   4786: 
1.918     raeburn  4787: 	    if (($domfilter eq '') ||
                   4788: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4789:                 my $rep;
                   4790:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4791:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4792:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4793:                                 &escape($descfilter), &escape($instcodefilter), 
                   4794:                                 &escape($ownerfilter), &escape($coursefilter),
                   4795:                                 &escape($typefilter), &escape($regexp_ok), 
                   4796:                                 $as_hash, &escape($selfenrollonly), 
                   4797:                                 &escape($catfilter), $showhidden, $caller, 
                   4798:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4799:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4800:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4801:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4802:                 } else {
                   4803:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4804:                              $sincefilter.':'.&escape($descfilter).':'.
                   4805:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4806:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4807:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4808:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4809:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4810:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4811:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4812:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4813:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4814:                 }
                   4815:                      
1.918     raeburn  4816:                 my @pairs=split(/\&/,$rep);
                   4817:                 foreach my $item (@pairs) {
                   4818:                     my ($key,$value)=split(/\=/,$item,2);
                   4819:                     $key = &unescape($key);
                   4820:                     next if ($key =~ /^error: 2 /);
                   4821:                     my $result = &thaw_unescape($value);
                   4822:                     if (ref($result) eq 'HASH') {
                   4823:                         $returnhash{$key}=$result;
                   4824:                     } else {
1.921     raeburn  4825:                         my @responses = split(/:/,$value);
                   4826:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4827:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4828:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4829:                         }
1.1008    raeburn  4830:                     }
1.353     www      4831:                 }
                   4832:             }
                   4833:         }
                   4834:     }
                   4835:     return %returnhash;
                   4836: }
                   4837: 
1.1055    raeburn  4838: sub courselastaccess {
                   4839:     my ($cdom,$cnum,$hostidref) = @_;
                   4840:     my %returnhash;
                   4841:     if ($cdom && $cnum) {
                   4842:         my $chome = &homeserver($cnum,$cdom);
                   4843:         if ($chome ne 'no_host') {
                   4844:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4845:             &extract_lastaccess(\%returnhash,$rep);
                   4846:         }
                   4847:     } else {
                   4848:         if (!$cdom) { $cdom=''; }
                   4849:         my %libserv = &all_library();
                   4850:         foreach my $tryserver (keys(%libserv)) {
                   4851:             if (ref($hostidref) eq 'ARRAY') {
                   4852:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4853:             } 
                   4854:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4855:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4856:                 &extract_lastaccess(\%returnhash,$rep);
                   4857:             }
                   4858:         }
                   4859:     }
                   4860:     return %returnhash;
                   4861: }
                   4862: 
                   4863: sub extract_lastaccess {
                   4864:     my ($returnhash,$rep) = @_;
                   4865:     if (ref($returnhash) eq 'HASH') {
                   4866:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4867:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4868:                  $rep eq '') {
                   4869:             my @pairs=split(/\&/,$rep);
                   4870:             foreach my $item (@pairs) {
                   4871:                 my ($key,$value)=split(/\=/,$item,2);
                   4872:                 $key = &unescape($key);
                   4873:                 next if ($key =~ /^error: 2 /);
                   4874:                 $returnhash->{$key} = &thaw_unescape($value);
                   4875:             }
                   4876:         }
                   4877:     }
                   4878:     return;
                   4879: }
                   4880: 
1.658     raeburn  4881: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4882: 
                   4883: sub dcmailput {
1.685     raeburn  4884:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4885:     my $status = &Apache::lonnet::critical(
1.740     www      4886:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4887:        &escape($message),$server);
1.662     raeburn  4888:     return $status;
                   4889: }
                   4890: 
1.658     raeburn  4891: sub dcmaildump {
                   4892:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4893:     my %returnhash=();
1.846     albertel 4894: 
                   4895:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4896:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4897:                                                          &escape($enddate).':';
                   4898: 	my @esc_senders=map { &escape($_)} @$senders;
                   4899: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4900: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4901:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4902:             if (($key) && ($value)) {
                   4903:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4904:             }
                   4905:         }
                   4906:     }
                   4907:     return %returnhash;
                   4908: }
1.662     raeburn  4909: # ---------------------------------------------------------- Domain roles
                   4910: 
                   4911: sub get_domain_roles {
                   4912:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4913:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4914:         $startdate = '.';
                   4915:     }
1.1018    raeburn  4916:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4917:         $enddate = '.';
                   4918:     }
1.922     raeburn  4919:     my $rolelist;
                   4920:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4921:         $rolelist = join('&',@{$roles});
1.922     raeburn  4922:     }
1.662     raeburn  4923:     my %personnel = ();
1.841     albertel 4924: 
                   4925:     my %servers = &get_servers($dom,'library');
                   4926:     foreach my $tryserver (keys(%servers)) {
                   4927: 	%{$personnel{$tryserver}}=();
                   4928: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4929: 					    &escape($startdate).':'.
                   4930: 					    &escape($enddate).':'.
                   4931: 					    &escape($rolelist), $tryserver))) {
                   4932: 	    my ($key,$value) = split(/\=/,$line,2);
                   4933: 	    if (($key) && ($value)) {
                   4934: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4935: 	    }
                   4936: 	}
1.662     raeburn  4937:     }
                   4938:     return %personnel;
                   4939: }
1.658     raeburn  4940: 
1.1332    raeburn  4941: sub get_active_domroles {
                   4942:     my ($dom,$roles) = @_;
                   4943:     return () unless (ref($roles) eq 'ARRAY');
                   4944:     my $now = time;
                   4945:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4946:     my %domroles;
                   4947:     foreach my $server (keys(%dompersonnel)) {
                   4948:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4949:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4950:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4951:         }
                   4952:     }
                   4953:     return %domroles;
                   4954: }
                   4955: 
1.1057    www      4956: # ----------------------------------------------------------- Interval timing 
1.149     www      4957: 
1.1153    www      4958: {
                   4959: # Caches needed for speedup of navmaps
                   4960: # We don't want to cache this for very long at all (5 seconds at most)
                   4961: # 
                   4962: # The user for whom we cache
                   4963: my $cachedkey='';
                   4964: # The cached times for this user
                   4965: my %cachedtimes=();
                   4966: # When this was last done
1.1282    raeburn  4967: my $cachedtime='';
1.1153    www      4968: 
                   4969: sub load_all_first_access {
1.1308    raeburn  4970:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4971:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4972:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4973:         (!$ignorecache)) {
1.1154    raeburn  4974:         return;
                   4975:     }
                   4976:     $cachedtime=time;
                   4977:     $cachedkey=$uname.':'.$udom;
                   4978:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4979: }
                   4980: 
1.504     albertel 4981: sub get_first_access {
1.1308    raeburn  4982:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4983:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4984:     if ($argsymb) { $symb=$argsymb; }
                   4985:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4986:     if ($argmap) { $map = $argmap; }
1.926     albertel 4987:     if ($type eq 'course') {
                   4988: 	$res='course';
                   4989:     } elsif ($type eq 'map') {
1.588     albertel 4990: 	$res=&symbread($map);
                   4991:     } else {
                   4992: 	$res=$symb;
                   4993:     }
1.1308    raeburn  4994:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4995:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4996: }
                   4997: 
                   4998: sub set_first_access {
1.1162    raeburn  4999:     my ($type,$interval)=@_;
1.790     albertel 5000:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5001:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5002:     if ($type eq 'course') {
                   5003: 	$res='course';
                   5004:     } elsif ($type eq 'map') {
1.588     albertel 5005: 	$res=&symbread($map);
                   5006:     } else {
                   5007: 	$res=$symb;
                   5008:     }
1.1153    www      5009:     $cachedkey='';
1.1162    raeburn  5010:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 5011:     if (!$firstaccess) {
1.1162    raeburn  5012:         my $start = time;
                   5013: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5014:                           $udom,$uname);
                   5015:         if ($putres eq 'ok') {
                   5016:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5017:                  $udom,$uname); 
                   5018:             &appenv(
                   5019:                      {
                   5020:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5021:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5022:                      }
                   5023:                   );
                   5024:         }
                   5025:         return $putres;
1.505     albertel 5026:     }
                   5027:     return 'already_set';
1.504     albertel 5028: }
1.1153    www      5029: }
1.1282    raeburn  5030: 
1.110     www      5031: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5032: 
                   5033: sub expirespread {
                   5034:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5035:     my $cid=$env{'request.course.id'}; 
1.110     www      5036:     if ($cid) {
                   5037:        my $now=time;
                   5038:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5039:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5040:                             $env{'course.'.$cid.'.num'}.
1.110     www      5041: 	        	    ':nohist_expirationdates:'.
                   5042:                             &escape($key).'='.$now,
1.620     albertel 5043:                             $env{'course.'.$cid.'.home'})
1.110     www      5044:     }
                   5045:     return 'ok';
1.14      www      5046: }
                   5047: 
1.109     www      5048: # ----------------------------------------------------- Devalidate Spreadsheets
                   5049: 
                   5050: sub devalidate {
1.325     www      5051:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5052:     my $cid=$env{'request.course.id'}; 
1.109     www      5053:     if ($cid) {
1.391     matthew  5054:         # delete the stored spreadsheets for
                   5055:         # - the student level sheet of this user in course's homespace
                   5056:         # - the assessment level sheet for this resource 
                   5057:         #   for this user in user's homespace
1.553     albertel 5058: 	# - current conditional state info
1.325     www      5059: 	my $key=$uname.':'.$udom.':';
1.109     www      5060:         my $status=
1.299     matthew  5061: 	    &del('nohist_calculatedsheets',
1.391     matthew  5062: 		 [$key.'studentcalc:'],
1.620     albertel 5063: 		 $env{'course.'.$cid.'.domain'},
                   5064: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5065: 		.' '.
                   5066: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5067: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5068:         unless ($status eq 'ok ok') {
                   5069:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5070:                     $uname.' at '.$udom.' for '.
1.109     www      5071: 		    $symb.': '.$status);
1.133     albertel 5072:         }
1.553     albertel 5073: 	&delenv('user.state.'.$cid);
1.109     www      5074:     }
                   5075: }
                   5076: 
1.265     albertel 5077: sub get_scalar {
                   5078:     my ($string,$end) = @_;
                   5079:     my $value;
                   5080:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5081: 	$value = $1;
                   5082:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5083: 	$value = $1;
                   5084:     }
                   5085:     return &unescape($value);
                   5086: }
                   5087: 
                   5088: sub array2str {
                   5089:   my (@array) = @_;
                   5090:   my $result=&arrayref2str(\@array);
                   5091:   $result=~s/^__ARRAY_REF__//;
                   5092:   $result=~s/__END_ARRAY_REF__$//;
                   5093:   return $result;
                   5094: }
                   5095: 
1.204     albertel 5096: sub arrayref2str {
                   5097:   my ($arrayref) = @_;
1.265     albertel 5098:   my $result='__ARRAY_REF__';
1.204     albertel 5099:   foreach my $elem (@$arrayref) {
1.265     albertel 5100:     if(ref($elem) eq 'ARRAY') {
                   5101:       $result.=&arrayref2str($elem).'&';
                   5102:     } elsif(ref($elem) eq 'HASH') {
                   5103:       $result.=&hashref2str($elem).'&';
                   5104:     } elsif(ref($elem)) {
                   5105:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5106:     } else {
                   5107:       $result.=&escape($elem).'&';
                   5108:     }
                   5109:   }
                   5110:   $result=~s/\&$//;
1.265     albertel 5111:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5112:   return $result;
                   5113: }
                   5114: 
1.168     albertel 5115: sub hash2str {
1.204     albertel 5116:   my (%hash) = @_;
                   5117:   my $result=&hashref2str(\%hash);
1.265     albertel 5118:   $result=~s/^__HASH_REF__//;
                   5119:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5120:   return $result;
                   5121: }
                   5122: 
                   5123: sub hashref2str {
                   5124:   my ($hashref)=@_;
1.265     albertel 5125:   my $result='__HASH_REF__';
1.800     albertel 5126:   foreach my $key (sort(keys(%$hashref))) {
                   5127:     if (ref($key) eq 'ARRAY') {
                   5128:       $result.=&arrayref2str($key).'=';
                   5129:     } elsif (ref($key) eq 'HASH') {
                   5130:       $result.=&hashref2str($key).'=';
                   5131:     } elsif (ref($key)) {
1.265     albertel 5132:       $result.='=';
1.800     albertel 5133:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5134:     } else {
1.1132    raeburn  5135: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5136:     }
                   5137: 
1.800     albertel 5138:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5139:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5140:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5141:       $result.=&hashref2str($hashref->{$key}).'&';
                   5142:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5143:        $result.='&';
1.800     albertel 5144:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5145:     } else {
1.800     albertel 5146:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5147:     }
                   5148:   }
1.168     albertel 5149:   $result=~s/\&$//;
1.265     albertel 5150:   $result .= '__END_HASH_REF__';
1.168     albertel 5151:   return $result;
                   5152: }
                   5153: 
                   5154: sub str2hash {
1.265     albertel 5155:     my ($string)=@_;
                   5156:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5157:     return %$hash;
                   5158: }
                   5159: 
                   5160: sub str2hashref {
1.168     albertel 5161:   my ($string) = @_;
1.265     albertel 5162: 
                   5163:   my %hash;
                   5164: 
                   5165:   if($string !~ /^__HASH_REF__/) {
                   5166:       if (! ($string eq '' || !defined($string))) {
                   5167: 	  $hash{'error'}='Not hash reference';
                   5168:       }
                   5169:       return (\%hash, $string);
                   5170:   }
                   5171: 
                   5172:   $string =~ s/^__HASH_REF__//;
                   5173: 
                   5174:   while($string !~ /^__END_HASH_REF__/) {
                   5175:       #key
                   5176:       my $key='';
                   5177:       if($string =~ /^__HASH_REF__/) {
                   5178:           ($key, $string)=&str2hashref($string);
                   5179:           if(defined($key->{'error'})) {
                   5180:               $hash{'error'}='Bad data';
                   5181:               return (\%hash, $string);
                   5182:           }
                   5183:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5184:           ($key, $string)=&str2arrayref($string);
                   5185:           if($key->[0] eq 'Array reference error') {
                   5186:               $hash{'error'}='Bad data';
                   5187:               return (\%hash, $string);
                   5188:           }
                   5189:       } else {
                   5190:           $string =~ s/^(.*?)=//;
1.267     albertel 5191: 	  $key=&unescape($1);
1.265     albertel 5192:       }
                   5193:       $string =~ s/^=//;
                   5194: 
                   5195:       #value
                   5196:       my $value='';
                   5197:       if($string =~ /^__HASH_REF__/) {
                   5198:           ($value, $string)=&str2hashref($string);
                   5199:           if(defined($value->{'error'})) {
                   5200:               $hash{'error'}='Bad data';
                   5201:               return (\%hash, $string);
                   5202:           }
                   5203:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5204:           ($value, $string)=&str2arrayref($string);
                   5205:           if($value->[0] eq 'Array reference error') {
                   5206:               $hash{'error'}='Bad data';
                   5207:               return (\%hash, $string);
                   5208:           }
                   5209:       } else {
                   5210: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5211:       }
                   5212:       $string =~ s/^&//;
                   5213: 
                   5214:       $hash{$key}=$value;
1.204     albertel 5215:   }
1.265     albertel 5216: 
                   5217:   $string =~ s/^__END_HASH_REF__//;
                   5218: 
                   5219:   return (\%hash, $string);
1.204     albertel 5220: }
                   5221: 
                   5222: sub str2array {
1.265     albertel 5223:     my ($string)=@_;
                   5224:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5225:     return @$array;
                   5226: }
                   5227: 
                   5228: sub str2arrayref {
1.204     albertel 5229:   my ($string) = @_;
1.265     albertel 5230:   my @array;
                   5231: 
                   5232:   if($string !~ /^__ARRAY_REF__/) {
                   5233:       if (! ($string eq '' || !defined($string))) {
                   5234: 	  $array[0]='Array reference error';
                   5235:       }
                   5236:       return (\@array, $string);
                   5237:   }
                   5238: 
                   5239:   $string =~ s/^__ARRAY_REF__//;
                   5240: 
                   5241:   while($string !~ /^__END_ARRAY_REF__/) {
                   5242:       my $value='';
                   5243:       if($string =~ /^__HASH_REF__/) {
                   5244:           ($value, $string)=&str2hashref($string);
                   5245:           if(defined($value->{'error'})) {
                   5246:               $array[0] ='Array reference error';
                   5247:               return (\@array, $string);
                   5248:           }
                   5249:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5250:           ($value, $string)=&str2arrayref($string);
                   5251:           if($value->[0] eq 'Array reference error') {
                   5252:               $array[0] ='Array reference error';
                   5253:               return (\@array, $string);
                   5254:           }
                   5255:       } else {
                   5256: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5257:       }
                   5258:       $string =~ s/^&//;
                   5259: 
                   5260:       push(@array, $value);
1.191     harris41 5261:   }
1.265     albertel 5262: 
                   5263:   $string =~ s/^__END_ARRAY_REF__//;
                   5264: 
                   5265:   return (\@array, $string);
1.168     albertel 5266: }
                   5267: 
1.167     albertel 5268: # -------------------------------------------------------------------Temp Store
                   5269: 
1.168     albertel 5270: sub tmpreset {
                   5271:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5272:   if (!$symb) {
                   5273:     $symb=&symbread();
1.620     albertel 5274:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5275:   }
                   5276:   $symb=escape($symb);
                   5277: 
1.620     albertel 5278:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5279:   $namespace=~s/\//\_/g;
                   5280:   $namespace=~s/\W//g;
                   5281: 
1.620     albertel 5282:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5283:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5284:   if ($domain eq 'public' && $stuname eq 'public') {
                   5285:       $stuname=$ENV{'REMOTE_ADDR'};
                   5286:   }
1.1117    foxr     5287:   my $path=LONCAPA::tempdir();
1.168     albertel 5288:   my %hash;
                   5289:   if (tie(%hash,'GDBM_File',
                   5290: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5291: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5292:     foreach my $key (keys(%hash)) {
1.180     albertel 5293:       if ($key=~ /:$symb/) {
1.168     albertel 5294: 	delete($hash{$key});
                   5295:       }
                   5296:     }
                   5297:   }
                   5298: }
                   5299: 
1.167     albertel 5300: sub tmpstore {
1.168     albertel 5301:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5302: 
                   5303:   if (!$symb) {
                   5304:     $symb=&symbread();
1.620     albertel 5305:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5306:   }
                   5307:   $symb=escape($symb);
                   5308: 
                   5309:   if (!$namespace) {
                   5310:     # I don't think we would ever want to store this for a course.
                   5311:     # it seems this will only be used if we don't have a course.
1.620     albertel 5312:     #$namespace=$env{'request.course.id'};
1.168     albertel 5313:     #if (!$namespace) {
1.620     albertel 5314:       $namespace=$env{'request.state'};
1.168     albertel 5315:     #}
                   5316:   }
                   5317:   $namespace=~s/\//\_/g;
                   5318:   $namespace=~s/\W//g;
1.620     albertel 5319:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5320:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5321:   if ($domain eq 'public' && $stuname eq 'public') {
                   5322:       $stuname=$ENV{'REMOTE_ADDR'};
                   5323:   }
1.168     albertel 5324:   my $now=time;
                   5325:   my %hash;
1.1117    foxr     5326:   my $path=LONCAPA::tempdir();
1.168     albertel 5327:   if (tie(%hash,'GDBM_File',
                   5328: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5329: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5330:     $hash{"version:$symb"}++;
                   5331:     my $version=$hash{"version:$symb"};
                   5332:     my $allkeys=''; 
                   5333:     foreach my $key (keys(%$storehash)) {
                   5334:       $allkeys.=$key.':';
1.591     albertel 5335:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5336:     }
                   5337:     $hash{"$version:$symb:timestamp"}=$now;
                   5338:     $allkeys.='timestamp';
                   5339:     $hash{"$version:keys:$symb"}=$allkeys;
                   5340:     if (untie(%hash)) {
                   5341:       return 'ok';
                   5342:     } else {
                   5343:       return "error:$!";
                   5344:     }
                   5345:   } else {
                   5346:     return "error:$!";
                   5347:   }
                   5348: }
1.167     albertel 5349: 
1.168     albertel 5350: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5351: 
1.168     albertel 5352: sub tmprestore {
                   5353:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5354: 
1.168     albertel 5355:   if (!$symb) {
                   5356:     $symb=&symbread();
1.620     albertel 5357:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5358:   }
                   5359:   $symb=escape($symb);
                   5360: 
1.620     albertel 5361:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5362: 
1.620     albertel 5363:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5364:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5365:   if ($domain eq 'public' && $stuname eq 'public') {
                   5366:       $stuname=$ENV{'REMOTE_ADDR'};
                   5367:   }
1.168     albertel 5368:   my %returnhash;
                   5369:   $namespace=~s/\//\_/g;
                   5370:   $namespace=~s/\W//g;
                   5371:   my %hash;
1.1117    foxr     5372:   my $path=LONCAPA::tempdir();
1.168     albertel 5373:   if (tie(%hash,'GDBM_File',
                   5374: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5375: 	  &GDBM_READER(),0640)) {
1.168     albertel 5376:     my $version=$hash{"version:$symb"};
                   5377:     $returnhash{'version'}=$version;
                   5378:     my $scope;
                   5379:     for ($scope=1;$scope<=$version;$scope++) {
                   5380:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5381:       my @keys=split(/:/,$vkeys);
                   5382:       my $key;
                   5383:       $returnhash{"$scope:keys"}=$vkeys;
                   5384:       foreach $key (@keys) {
1.591     albertel 5385: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5386: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5387:       }
                   5388:     }
1.168     albertel 5389:     if (!(untie(%hash))) {
                   5390:       return "error:$!";
                   5391:     }
                   5392:   } else {
                   5393:     return "error:$!";
                   5394:   }
                   5395:   return %returnhash;
1.167     albertel 5396: }
                   5397: 
1.9       www      5398: # ----------------------------------------------------------------------- Store
                   5399: 
                   5400: sub store {
1.1269    raeburn  5401:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5402:     my $home='';
                   5403: 
1.168     albertel 5404:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5405: 
1.213     www      5406:     $symb=&symbclean($symb);
1.122     albertel 5407:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5408: 
1.620     albertel 5409:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5410:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5411: 
                   5412:     &devalidate($symb,$stuname,$domain);
1.109     www      5413: 
                   5414:     $symb=escape($symb);
1.187     www      5415:     if (!$namespace) { 
1.620     albertel 5416:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5417:           return ''; 
                   5418:        } 
                   5419:     }
1.620     albertel 5420:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5421: 
                   5422:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5423:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5424: 
1.12      www      5425:     my $namevalue='';
1.800     albertel 5426:     foreach my $key (keys(%$storehash)) {
                   5427:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5428:     }
1.12      www      5429:     $namevalue=~s/\&$//;
1.187     www      5430:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5431:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5432: }
                   5433: 
1.47      www      5434: # -------------------------------------------------------------- Critical Store
                   5435: 
                   5436: sub cstore {
1.1269    raeburn  5437:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5438:     my $home='';
                   5439: 
1.168     albertel 5440:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5441: 
1.213     www      5442:     $symb=&symbclean($symb);
1.122     albertel 5443:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5444: 
1.620     albertel 5445:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5446:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5447: 
                   5448:     &devalidate($symb,$stuname,$domain);
1.109     www      5449: 
                   5450:     $symb=escape($symb);
1.187     www      5451:     if (!$namespace) { 
1.620     albertel 5452:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5453:           return ''; 
                   5454:        } 
                   5455:     }
1.620     albertel 5456:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5457: 
                   5458:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5459:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5460: 
1.47      www      5461:     my $namevalue='';
1.800     albertel 5462:     foreach my $key (keys(%$storehash)) {
                   5463:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5464:     }
1.47      www      5465:     $namevalue=~s/\&$//;
1.187     www      5466:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5467:     return critical
1.1269    raeburn  5468:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5469: }
                   5470: 
1.9       www      5471: # --------------------------------------------------------------------- Restore
                   5472: 
                   5473: sub restore {
1.124     www      5474:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5475:     my $home='';
                   5476: 
1.168     albertel 5477:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5478: 
1.122     albertel 5479:     if (!$symb) {
1.1224    raeburn  5480:         return if ($namespace eq 'courserequests');
                   5481:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5482:     } else {
1.1224    raeburn  5483:         unless ($namespace eq 'courserequests') {
                   5484:             $symb=&escape(&symbclean($symb));
                   5485:         }
1.122     albertel 5486:     }
1.188     www      5487:     if (!$namespace) { 
1.620     albertel 5488:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5489:           return ''; 
                   5490:        } 
                   5491:     }
1.620     albertel 5492:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5493:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5494:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5495:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5496: 
1.12      www      5497:     my %returnhash=();
1.800     albertel 5498:     foreach my $line (split(/\&/,$answer)) {
                   5499: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5500:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5501:     }
1.75      www      5502:     my $version;
                   5503:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5504:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5505:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5506:        }
1.75      www      5507:     }
1.13      www      5508:     return %returnhash;
1.34      www      5509: }
                   5510: 
                   5511: # ---------------------------------------------------------- Course Description
1.1118    foxr     5512: #
                   5513: #  
1.34      www      5514: 
                   5515: sub coursedescription {
1.731     albertel 5516:     my ($courseid,$args)=@_;
1.34      www      5517:     $courseid=~s/^\///;
1.49      www      5518:     $courseid=~s/\_/\//g;
1.34      www      5519:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5520:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5521:     my $normalid=$cdomain.'_'.$cnum;
                   5522:     # need to always cache even if we get errors otherwise we keep 
                   5523:     # trying and trying and trying to get the course description.
                   5524:     my %envhash=();
                   5525:     my %returnhash=();
1.731     albertel 5526:     
                   5527:     my $expiretime=600;
                   5528:     if ($env{'request.course.id'} eq $normalid) {
                   5529: 	$expiretime=120;
                   5530:     }
                   5531: 
                   5532:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5533:     if (!$args->{'freshen_cache'}
                   5534: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5535: 	foreach my $key (keys(%env)) {
                   5536: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5537: 	    my ($setting) = $1;
                   5538: 	    $returnhash{$setting} = $env{$key};
                   5539: 	}
                   5540: 	return %returnhash;
                   5541:     }
                   5542: 
1.1118    foxr     5543:     # get the data again
                   5544: 
1.731     albertel 5545:     if (!$args->{'one_time'}) {
                   5546: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5547:     }
1.811     albertel 5548: 
1.34      www      5549:     if ($chome ne 'no_host') {
1.302     albertel 5550:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5551:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5552: 	   my $username = $env{'user.name'}; # Defult username
                   5553: 	   if(defined $args->{'user'}) {
                   5554: 	       $username = $args->{'user'};
                   5555: 	   }
1.129     albertel 5556:            $returnhash{'home'}= $chome;
                   5557: 	   $returnhash{'domain'} = $cdomain;
                   5558: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5559:            if (!defined($returnhash{'type'})) {
                   5560:                $returnhash{'type'} = 'Course';
                   5561:            }
1.130     albertel 5562:            while (my ($name,$value) = each %returnhash) {
1.53      www      5563:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5564:            }
1.270     www      5565:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5566:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5567: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5568:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5569:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5570:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5571:        }
                   5572:     }
1.731     albertel 5573:     if (!$args->{'one_time'}) {
1.949     raeburn  5574: 	&appenv(\%envhash);
1.731     albertel 5575:     }
1.302     albertel 5576:     return %returnhash;
1.461     www      5577: }
                   5578: 
1.1080    raeburn  5579: sub update_released_required {
                   5580:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5581:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5582:         $cid = $env{'request.course.id'};
                   5583:         $cdom = $env{'course.'.$cid.'.domain'};
                   5584:         $cnum = $env{'course.'.$cid.'.num'};
                   5585:         $chome = $env{'course.'.$cid.'.home'};
                   5586:     }
                   5587:     if ($needsrelease) {
                   5588:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5589:         my $needsupdate;
                   5590:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5591:             $needsupdate = 1;
                   5592:         } else {
                   5593:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5594:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5595:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5596:                 $needsupdate = 1;
                   5597:             }
                   5598:         }
                   5599:         if ($needsupdate) {
                   5600:             my %needshash = (
                   5601:                              'internal.releaserequired' => $needsrelease,
                   5602:                             );
                   5603:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5604:             if ($putresult eq 'ok') {
                   5605:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5606:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5607:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5608:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5609:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5610:                 }
                   5611:             }
                   5612:         }
                   5613:     }
                   5614:     return;
                   5615: }
                   5616: 
1.461     www      5617: # -------------------------------------------------See if a user is privileged
                   5618: 
                   5619: sub privileged {
1.1219    raeburn  5620:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5621:     my $now = time;
1.1219    raeburn  5622:     my $roles;
                   5623:     if (ref($possroles) eq 'ARRAY') {
                   5624:         $roles = $possroles; 
                   5625:     } else {
                   5626:         $roles = ['dc','su'];
                   5627:     }
                   5628:     if (ref($possdomains) eq 'ARRAY') {
                   5629:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5630:         foreach my $dom (@{$possdomains}) {
                   5631:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5632:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5633:                 foreach my $role (@{$roles}) {
                   5634:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5635:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5636:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5637:                             return 1 unless (($end && $end < $now) ||
                   5638:                                              ($start && $start > $now));
                   5639:                         }
                   5640:                     }
                   5641:                 }
                   5642:             }
                   5643:         }
                   5644:     } else {
                   5645:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5646:         my $now = time;
1.1170    droeschl 5647: 
1.1275    musolffc 5648:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5649:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5650:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5651:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5652:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5653:             }
1.1219    raeburn  5654:         }
                   5655:     }
                   5656:     return 0;
                   5657: }
1.1170    droeschl 5658: 
1.1219    raeburn  5659: sub privileged_by_domain {
                   5660:     my ($domains,$roles) = @_;
                   5661:     my %privileged = ();
                   5662:     my $cachetime = 60*60*24;
                   5663:     my $now = time;
                   5664:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5665:         return %privileged;
                   5666:     }
                   5667:     foreach my $dom (@{$domains}) {
                   5668:         next if (ref($privileged{$dom}) eq 'HASH');
                   5669:         my $needroles;
                   5670:         foreach my $role (@{$roles}) {
                   5671:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5672:             if (defined($cached)) {
                   5673:                 if (ref($result) eq 'HASH') {
                   5674:                     $privileged{$dom}{$role} = $result;
                   5675:                 }
                   5676:             } else {
                   5677:                 $needroles = 1;
                   5678:             }
                   5679:         }
                   5680:         if ($needroles) {
                   5681:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5682:             $privileged{$dom} = {};
                   5683:             foreach my $server (keys(%dompersonnel)) {
                   5684:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5685:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5686:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5687:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5688:                         next if ($end && $end < $now);
                   5689:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5690:                             $dompersonnel{$server}{$item};
                   5691:                     }
                   5692:                 }
                   5693:             }
                   5694:             if (ref($privileged{$dom}) eq 'HASH') {
                   5695:                 foreach my $role (@{$roles}) {
                   5696:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5697:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5698:                     } else {
                   5699:                         my %hash = ();
                   5700:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5701:                     }
                   5702:                 }
                   5703:             }
                   5704:         }
                   5705:     }
                   5706:     return %privileged;
1.9       www      5707: }
1.1       albertel 5708: 
1.103     harris41 5709: # -------------------------------------------------------- Get user privileges
1.11      www      5710: 
                   5711: sub rolesinit {
1.1169    droeschl 5712:     my ($domain, $username) = @_;
                   5713:     my %userroles = ('user.login.time' => time);
                   5714:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5715: 
                   5716:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5717:     # also, blocking can be triggered by an activating timer
                   5718:     # it's saved in the user's %env.
                   5719:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5720:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5721:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5722:         %timerintchk, %timerintenv);
                   5723: 
1.1162    raeburn  5724:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5725:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5726:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5727:     }
1.1169    droeschl 5728: 
1.1162    raeburn  5729:     foreach my $key (keys(%timerinterval)) {
                   5730:         my ($cid,$rest) = split(/\0/,$key);
                   5731:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5732:     }
1.1169    droeschl 5733: 
1.11      www      5734:     my %allroles=();
1.1162    raeburn  5735:     my %allgroups=();
1.11      www      5736: 
1.1274    raeburn  5737:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5738:         my $role = $rolesdump{$area};
                   5739:         $area =~ s/\_\w\w$//;
                   5740: 
                   5741:         my ($trole, $tend, $tstart, $group_privs);
                   5742: 
                   5743:         if ($role =~ /^cr/) {
                   5744:         # Custom role, defined by a user 
                   5745:         # e.g., user.role.cr/msu/smith/mynewrole
                   5746:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5747:                 $trole = $1;
                   5748:                 ($tend, $tstart) = split('_', $2);
                   5749:             } else {
                   5750:                 $trole = $role;
                   5751:             }
                   5752:         } elsif ($role =~ m|^gr/|) {
                   5753:         # Role of member in a group, defined within a course/community
                   5754:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5755:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5756:             next if $tstart eq '-1';
                   5757:             ($trole, $group_privs) = split(/\//, $trole);
                   5758:             $group_privs = &unescape($group_privs);
                   5759:         } else {
                   5760:         # Just a normal role, defined in roles.tab
                   5761:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5762:         }
                   5763: 
                   5764:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5765:                  $username);
                   5766:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5767: 
                   5768:         # role expired or not available yet?
                   5769:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5770:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5771: 
                   5772:         next if $area eq '' or $trole eq '';
                   5773: 
                   5774:         my $spec = "$trole.$area";
                   5775:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5776: 
                   5777:         if ($trole =~ /^cr\//) {
                   5778:         # Custom role, defined by a user
                   5779:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5780:         } elsif ($trole eq 'gr') {
                   5781:         # Role of a member in a group, defined within a course/community
                   5782:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5783:             next;
                   5784:         } else {
                   5785:         # Normal role, defined in roles.tab
                   5786:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5787:         }
                   5788: 
                   5789:         my $cid = $tdomain.'_'.$trest;
                   5790:         unless ($firstaccchk{$cid}) {
                   5791:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5792:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5793:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5794:                         $coursetimerstarts{$cid}{$item}; 
                   5795:                 }
                   5796:             }
                   5797:             $firstaccchk{$cid} = 1;
                   5798:         }
                   5799:         unless ($timerintchk{$cid}) {
                   5800:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5801:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5802:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5803:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5804:                 }
1.12      www      5805:             }
1.1169    droeschl 5806:             $timerintchk{$cid} = 1;
1.191     harris41 5807:         }
1.11      www      5808:     }
1.1169    droeschl 5809: 
                   5810:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5811:         \%allroles, \%allgroups);
                   5812:     $env{'user.adv'} = $userroles{'user.adv'};
                   5813: 
1.1162    raeburn  5814:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5815: }
                   5816: 
1.567     raeburn  5817: sub set_arearole {
1.1215    raeburn  5818:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5819:     unless ($nolog) {
1.567     raeburn  5820: # log the associated role with the area
1.1215    raeburn  5821:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5822:     }
1.743     albertel 5823:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5824: }
                   5825: 
                   5826: sub custom_roleprivs {
                   5827:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5828:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5829:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5830:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5831:         my ($rdummy,$roledef)=
                   5832:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5833:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5834:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5835:             if (defined($syspriv)) {
1.1043    raeburn  5836:                 if ($trest =~ /^$match_community$/) {
                   5837:                     $syspriv =~ s/bre\&S//; 
                   5838:                 }
1.567     raeburn  5839:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5840:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5841:             }
                   5842:             if ($tdomain ne '') {
                   5843:                 if (defined($dompriv)) {
                   5844:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5845:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5846:                 }
                   5847:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  5848:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5849:                         my $rolename = $1;
                   5850:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5851:                     }
1.567     raeburn  5852:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5853:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5854:                 }
                   5855:             }
                   5856:         }
                   5857:     }
                   5858: }
                   5859: 
1.1332    raeburn  5860: sub course_adhocrole_privs {
                   5861:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5862:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5863:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5864:         my (%currprivs,%storeprivs);
                   5865:         foreach my $item (split(/:/,$coursepriv)) {
                   5866:             my ($priv,$restrict) = split(/\&/,$item);
                   5867:             $currprivs{$priv} = $restrict;
                   5868:         }
                   5869:         my (%possadd,%possremove,%full);
                   5870:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5871:             my ($priv,$restrict)=split(/\&/,$item);
                   5872:             $full{$priv} = $restrict;
                   5873:         }
                   5874:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5875:              next if ($item eq '');
                   5876:              my ($rule,$rest) = split(/=/,$item);
                   5877:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5878:              foreach my $priv (split(/:/,$rest)) {
                   5879:                  if ($priv ne '') {
                   5880:                      if ($rule eq 'off') {
                   5881:                          $possremove{$priv} = 1;
                   5882:                      } else {
                   5883:                          $possadd{$priv} = 1;
                   5884:                      }
                   5885:                  }
                   5886:              }
                   5887:          }
                   5888:          foreach my $priv (sort(keys(%full))) {
                   5889:              if (exists($currprivs{$priv})) {
                   5890:                  unless (exists($possremove{$priv})) {
                   5891:                      $storeprivs{$priv} = $currprivs{$priv};
                   5892:                  }
                   5893:              } elsif (exists($possadd{$priv})) {
                   5894:                  $storeprivs{$priv} = $full{$priv};
                   5895:              }
                   5896:          }
                   5897:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5898:      }
                   5899:      return $coursepriv;
                   5900: }
                   5901: 
1.678     raeburn  5902: sub group_roleprivs {
                   5903:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5904:     my $access = 1;
                   5905:     my $now = time;
                   5906:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5907:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5908:     if ($access) {
1.811     albertel 5909:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5910:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5911:     }
                   5912: }
1.567     raeburn  5913: 
                   5914: sub standard_roleprivs {
                   5915:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5916:     if (defined($pr{$trole.':s'})) {
                   5917:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5918:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5919:     }
                   5920:     if ($tdomain ne '') {
                   5921:         if (defined($pr{$trole.':d'})) {
                   5922:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5923:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5924:         }
                   5925:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5926:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5927:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5928:         }
                   5929:     }
                   5930: }
                   5931: 
                   5932: sub set_userprivs {
1.1064    raeburn  5933:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5934:     my $author=0;
                   5935:     my $adv=0;
1.678     raeburn  5936:     my %grouproles = ();
                   5937:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5938:         my @groupkeys; 
1.1000    raeburn  5939:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5940:             push(@groupkeys,$role);
                   5941:         }
                   5942:         if (ref($groups_roles) eq 'HASH') {
                   5943:             foreach my $key (keys(%{$groups_roles})) {
                   5944:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5945:                     push(@groupkeys,$key);
                   5946:                 }
                   5947:             }
                   5948:         }
                   5949:         if (@groupkeys > 0) {
                   5950:             foreach my $role (@groupkeys) {
                   5951:                 my ($trole,$area,$sec,$extendedarea);
                   5952:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5953:                     $trole = $1;
                   5954:                     $area = $2;
                   5955:                     $sec = $3;
                   5956:                     $extendedarea = $area.$sec;
                   5957:                     if (exists($$allgroups{$area})) {
                   5958:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5959:                             my $spec = $trole.'.'.$extendedarea;
                   5960:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5961:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5962:                         }
1.678     raeburn  5963:                     }
                   5964:                 }
                   5965:             }
                   5966:         }
                   5967:     }
1.800     albertel 5968:     foreach my $group (keys(%grouproles)) {
                   5969:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5970:     }
1.800     albertel 5971:     foreach my $role (keys(%{$allroles})) {
                   5972:         my %thesepriv;
1.941     raeburn  5973:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5974:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5975:             if ($item ne '') {
                   5976:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5977:                 if ($restrictions eq '') {
                   5978:                     $thesepriv{$privilege}='F';
                   5979:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5980:                     $thesepriv{$privilege}.=$restrictions;
                   5981:                 }
                   5982:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5983:             }
                   5984:         }
                   5985:         my $thesestr='';
1.1104    raeburn  5986:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5987: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5988: 	}
                   5989:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5990:     }
                   5991:     return ($author,$adv);
                   5992: }
                   5993: 
1.994     raeburn  5994: sub role_status {
1.1104    raeburn  5995:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5996:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5997:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5998:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5999:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6000:             $$where = '/'.$two;
1.994     raeburn  6001:             $$trolecode=$$role.'.'.$$where;
                   6002:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6003:             $$tstatus='is';
1.1104    raeburn  6004:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6005:                 $$tstatus='future';
1.1034    raeburn  6006:                 if ($$tstart<$now) {
                   6007:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6008:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6009:                             my (%allroles,%allgroups,$group_privs,
                   6010:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6011:                             my %userroles = (
                   6012:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6013:                             );
1.1064    raeburn  6014:                             @rolecodes = ('cm'); 
1.1002    raeburn  6015:                             my $spec=$$role.'.'.$$where;
                   6016:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6017:                             if ($$role =~ /^cr\//) {
                   6018:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6019:                                 push(@rolecodes,'cr');
1.1002    raeburn  6020:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6021:                                 push(@rolecodes,$$role);
1.1002    raeburn  6022:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6023:                                                     $env{'user.name'});
1.1064    raeburn  6024:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6025:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6026:                                 $group_privs = &unescape($group_privs);
                   6027:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6028:                                 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  6029:                                 &get_groups_roles($tdomain,$trest,
                   6030:                                                   \%course_roles,\@rolecodes,
                   6031:                                                   \%groups_roles);
1.1002    raeburn  6032:                             } else {
1.1064    raeburn  6033:                                 push(@rolecodes,$$role);
1.1002    raeburn  6034:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6035:                             }
1.1064    raeburn  6036:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   6037:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  6038:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   6039:                         }
                   6040:                     }
1.1034    raeburn  6041:                     $$tstatus = 'is';
1.1002    raeburn  6042:                 }
1.994     raeburn  6043:             }
                   6044:             if ($$tend) {
1.1104    raeburn  6045:                 if ($$tend<$update) {
1.994     raeburn  6046:                     $$tstatus='expired';
                   6047:                 } elsif ($$tend<$now) {
                   6048:                     $$tstatus='will_not';
                   6049:                 }
                   6050:             }
                   6051:         }
                   6052:     }
                   6053: }
                   6054: 
1.1104    raeburn  6055: sub get_groups_roles {
                   6056:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6057:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6058:                   (ref($rolecodes) eq 'ARRAY') && 
                   6059:                   (ref($groups_roles) eq 'HASH')); 
                   6060:     if (keys(%{$cdom_courseroles}) > 0) {
                   6061:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6062:         if ($cdom ne '' && $cnum ne '') {
                   6063:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6064:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6065:                     my $crsrole = $1;
                   6066:                     my $crssec = $2;
                   6067:                     if ($crsrole =~ /^cr/) {
                   6068:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6069:                             push(@{$rolecodes},'cr');
                   6070:                         }
                   6071:                     } else {
                   6072:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6073:                             push(@{$rolecodes},$crsrole);
                   6074:                         }
                   6075:                     }
                   6076:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6077:                     if ($crssec ne '') {
                   6078:                         $rolekey .= "/$crssec";
                   6079:                     }
                   6080:                     $rolekey .= './';
                   6081:                     $groups_roles->{$rolekey} = $rolecodes;
                   6082:                 }
                   6083:             }
                   6084:         }
                   6085:     }
                   6086:     return;
                   6087: }
                   6088: 
                   6089: sub delete_env_groupprivs {
                   6090:     my ($where,$courseroles,$possroles) = @_;
                   6091:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6092:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6093:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6094:         %{$courseroles->{$udom}} =
                   6095:             &get_my_roles('','','userroles',['active'],
                   6096:                           $possroles,[$udom],1);
                   6097:     }
                   6098:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6099:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6100:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6101:             my $area = '/'.$cdom.'/'.$cnum;
                   6102:             my $privkey = "user.priv.$crsrole.$area";
                   6103:             if ($crssec ne '') {
                   6104:                 $privkey .= '/'.$crssec;
                   6105:             }
                   6106:             $privkey .= ".$area/$group";
                   6107:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6108:         }
                   6109:     }
                   6110:     return;
                   6111: }
                   6112: 
1.994     raeburn  6113: sub check_adhoc_privs {
1.1329    raeburn  6114:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6115:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6116:     if ($sec) {
                   6117:         $cckey .= '/'.$sec;
                   6118:     } 
1.1185    raeburn  6119:     my $setprivs;
1.994     raeburn  6120:     if ($env{$cckey}) {
                   6121:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6122:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6123:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6124:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6125:             $setprivs = 1;
1.994     raeburn  6126:         }
                   6127:     } else {
1.1330    raeburn  6128:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6129:         $setprivs = 1;
1.994     raeburn  6130:     }
1.1185    raeburn  6131:     return $setprivs;
1.994     raeburn  6132: }
                   6133: 
                   6134: sub set_adhoc_privileges {
1.1326    raeburn  6135: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6136:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6137:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6138:     if ($sec ne '') {
                   6139:         $area .= '/'.$sec;
                   6140:     }
1.994     raeburn  6141:     my $spec = $role.'.'.$area;
                   6142:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6143:                                   $env{'user.name'},1);
1.1326    raeburn  6144:     my %rolehash = ();
1.1332    raeburn  6145:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6146:         my $rolename = $1;
1.1326    raeburn  6147:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6148:         my %domdef = &get_domain_defaults($dcdom);
                   6149:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6150:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6151:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6152:             }
                   6153:         }
1.1326    raeburn  6154:     } else {
                   6155:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6156:     }
                   6157:     my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6158:     &appenv(\%userroles,[$role,'cm']);
                   6159:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  6160:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6161:         &appenv( {'request.role'        => $spec,
                   6162:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6163:                   'request.course.sec'  => $sec,
1.1088    raeburn  6164:                  }
                   6165:                );
                   6166:         my $tadv=0;
                   6167:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6168:         &appenv({'request.role.adv'    => $tadv});
                   6169:     }
1.994     raeburn  6170: }
                   6171: 
1.12      www      6172: # --------------------------------------------------------------- get interface
                   6173: 
                   6174: sub get {
1.131     albertel 6175:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6176:    my $items='';
1.800     albertel 6177:    foreach my $item (@$storearr) {
                   6178:        $items.=&escape($item).'&';
1.191     harris41 6179:    }
1.12      www      6180:    $items=~s/\&$//;
1.620     albertel 6181:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6182:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6183:    my $uhome=&homeserver($uname,$udomain);
                   6184: 
1.133     albertel 6185:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6186:    my @pairs=split(/\&/,$rep);
1.273     albertel 6187:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6188:      return @pairs;
                   6189:    }
1.15      www      6190:    my %returnhash=();
1.42      www      6191:    my $i=0;
1.800     albertel 6192:    foreach my $item (@$storearr) {
                   6193:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6194:       $i++;
1.191     harris41 6195:    }
1.15      www      6196:    return %returnhash;
1.27      www      6197: }
                   6198: 
                   6199: # --------------------------------------------------------------- del interface
                   6200: 
                   6201: sub del {
1.133     albertel 6202:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6203:    my $items='';
1.800     albertel 6204:    foreach my $item (@$storearr) {
                   6205:        $items.=&escape($item).'&';
1.191     harris41 6206:    }
1.984     neumanie 6207: 
1.27      www      6208:    $items=~s/\&$//;
1.620     albertel 6209:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6210:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6211:    my $uhome=&homeserver($uname,$udomain);
                   6212:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6213: }
                   6214: 
                   6215: # -------------------------------------------------------------- dump interface
                   6216: 
1.1180    droeschl 6217: sub unserialize {
                   6218:     my ($rep, $escapedkeys) = @_;
                   6219: 
                   6220:     return {} if $rep =~ /^error/;
                   6221: 
                   6222:     my %returnhash=();
1.1252    raeburn  6223: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6224: 	    my ($key, $value) = split(/=/, $item, 2);
                   6225: 	    $key = unescape($key) unless $escapedkeys;
                   6226: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6227: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6228: 	}
                   6229:     #return %returnhash;
                   6230:     return \%returnhash;
                   6231: }        
                   6232: 
                   6233: # see Lond::dump_with_regexp
                   6234: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6235: sub dump {
1.1180    droeschl 6236:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6237:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6238:     if (!$uname) { $uname=$env{'user.name'}; }
                   6239:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6240: 
1.1266    raeburn  6241:     if ($regexp) {
                   6242:         $regexp=&escape($regexp);
                   6243:     } else {
                   6244:         $regexp='.';
                   6245:     }
1.1180    droeschl 6246:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6247:         # user is hosted on this machine
1.1266    raeburn  6248:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6249:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6250:         return %{unserialize($reply, $escapedkeys)};
                   6251:     }
1.1166    raeburn  6252:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6253:     my @pairs=split(/\&/,$rep);
                   6254:     my %returnhash=();
1.1098    foxr     6255:     if (!($rep =~ /^error/ )) {
                   6256: 	foreach my $item (@pairs) {
                   6257: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6258:         $key = unescape($key) unless $escapedkeys;
                   6259:         #$key = &unescape($key);
1.1098    foxr     6260: 	    next if ($key =~ /^error: 2 /);
                   6261: 	    $returnhash{$key}=&thaw_unescape($value);
                   6262: 	}
1.755     albertel 6263:     }
                   6264:     return %returnhash;
1.407     www      6265: }
                   6266: 
1.1098    foxr     6267: 
1.717     albertel 6268: # --------------------------------------------------------- dumpstore interface
                   6269: 
                   6270: sub dumpstore {
                   6271:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6272:    # same as dump but keys must be escaped. They may contain colon separated
                   6273:    # lists of values that may themself contain colons (e.g. symbs).
                   6274:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6275: }
                   6276: 
1.407     www      6277: # -------------------------------------------------------------- keys interface
                   6278: 
                   6279: sub getkeys {
                   6280:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6281:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6282:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6283:    my $uhome=&homeserver($uname,$udomain);
                   6284:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6285:    my @keyarray=();
1.800     albertel 6286:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6287:       next if ($key =~ /^error: 2 /);
1.800     albertel 6288:       push(@keyarray,&unescape($key));
1.407     www      6289:    }
                   6290:    return @keyarray;
1.318     matthew  6291: }
                   6292: 
1.319     matthew  6293: # --------------------------------------------------------------- currentdump
                   6294: sub currentdump {
1.328     matthew  6295:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6296:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6297:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6298:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6299:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6300:    my $rep;
                   6301: 
                   6302:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6303:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6304:                    $courseid)));
                   6305:    } else {
                   6306:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6307:    }
                   6308: 
1.318     matthew  6309:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6310:    #
1.318     matthew  6311:    my %returnhash=();
1.319     matthew  6312:    #
                   6313:    if ($rep eq "unknown_cmd") { 
                   6314:        # an old lond will not know currentdump
                   6315:        # Do a dump and make it look like a currentdump
1.822     albertel 6316:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6317:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6318:        my %hash = @tmp;
                   6319:        @tmp=();
1.424     matthew  6320:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6321:    } else {
                   6322:        my @pairs=split(/\&/,$rep);
1.800     albertel 6323:        foreach my $pair (@pairs) {
                   6324:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6325:            my ($symb,$param) = split(/:/,$key);
                   6326:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6327:                                                         &thaw_unescape($value);
1.319     matthew  6328:        }
1.191     harris41 6329:    }
1.12      www      6330:    return %returnhash;
1.424     matthew  6331: }
                   6332: 
                   6333: sub convert_dump_to_currentdump{
                   6334:     my %hash = %{shift()};
                   6335:     my %returnhash;
                   6336:     # Code ripped from lond, essentially.  The only difference
                   6337:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6338:     # we might run in to problems with parameter names =~ /^v\./
                   6339:     while (my ($key,$value) = each(%hash)) {
                   6340:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6341: 	$symb  = &unescape($symb);
                   6342: 	$param = &unescape($param);
1.424     matthew  6343:         next if ($v eq 'version' || $symb eq 'keys');
                   6344:         next if (exists($returnhash{$symb}) &&
                   6345:                  exists($returnhash{$symb}->{$param}) &&
                   6346:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6347:         $returnhash{$symb}->{$param}=$value;
                   6348:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6349:     }
                   6350:     #
                   6351:     # Remove all of the keys in the hashes which keep track of
                   6352:     # the version of the parameter.
                   6353:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6354:         # use a foreach because we are going to delete from the hash.
                   6355:         foreach my $key (keys(%$param_hash)) {
                   6356:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6357:         }
                   6358:     }
                   6359:     return \%returnhash;
1.12      www      6360: }
                   6361: 
1.627     albertel 6362: # ------------------------------------------------------ critical inc interface
                   6363: 
                   6364: sub cinc {
                   6365:     return &inc(@_,'critical');
                   6366: }
                   6367: 
1.449     matthew  6368: # --------------------------------------------------------------- inc interface
                   6369: 
                   6370: sub inc {
1.627     albertel 6371:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6372:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6373:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6374:     my $uhome=&homeserver($uname,$udomain);
                   6375:     my $items='';
                   6376:     if (! ref($store)) {
                   6377:         # got a single value, so use that instead
                   6378:         $items = &escape($store).'=&';
                   6379:     } elsif (ref($store) eq 'SCALAR') {
                   6380:         $items = &escape($$store).'=&';        
                   6381:     } elsif (ref($store) eq 'ARRAY') {
                   6382:         $items = join('=&',map {&escape($_);} @{$store});
                   6383:     } elsif (ref($store) eq 'HASH') {
                   6384:         while (my($key,$value) = each(%{$store})) {
                   6385:             $items.= &escape($key).'='.&escape($value).'&';
                   6386:         }
                   6387:     }
                   6388:     $items=~s/\&$//;
1.627     albertel 6389:     if ($critical) {
                   6390: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6391:     } else {
                   6392: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6393:     }
1.449     matthew  6394: }
                   6395: 
1.12      www      6396: # --------------------------------------------------------------- put interface
                   6397: 
                   6398: sub put {
1.134     albertel 6399:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6400:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6401:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6402:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6403:    my $items='';
1.800     albertel 6404:    foreach my $item (keys(%$storehash)) {
                   6405:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6406:    }
1.12      www      6407:    $items=~s/\&$//;
1.134     albertel 6408:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6409: }
                   6410: 
1.631     albertel 6411: # ------------------------------------------------------------ newput interface
                   6412: 
                   6413: sub newput {
                   6414:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6415:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6416:    if (!$uname) { $uname=$env{'user.name'}; }
                   6417:    my $uhome=&homeserver($uname,$udomain);
                   6418:    my $items='';
                   6419:    foreach my $key (keys(%$storehash)) {
                   6420:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6421:    }
                   6422:    $items=~s/\&$//;
                   6423:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6424: }
                   6425: 
                   6426: # ---------------------------------------------------------  putstore interface
                   6427: 
1.524     raeburn  6428: sub putstore {
1.1269    raeburn  6429:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6430:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6431:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6432:    my $uhome=&homeserver($uname,$udomain);
                   6433:    my $items='';
1.715     albertel 6434:    foreach my $key (keys(%$storehash)) {
                   6435:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6436:    }
1.715     albertel 6437:    $items=~s/\&$//;
1.716     albertel 6438:    my $esc_symb=&escape($symb);
                   6439:    my $esc_v=&escape($version);
1.715     albertel 6440:    my $reply =
1.716     albertel 6441:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6442: 	      $uhome);
1.1269    raeburn  6443:    if (($tolog) && ($reply eq 'ok')) {
                   6444:        my $namevalue='';
                   6445:        foreach my $key (keys(%{$storehash})) {
                   6446:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6447:        }
                   6448:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6449:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6450:                      '&version='.$esc_v.
                   6451:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6452:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6453:    }
1.715     albertel 6454:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6455:        # gfall back to way things use to be done
1.715     albertel 6456:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6457: 			    $uname);
1.524     raeburn  6458:    }
1.715     albertel 6459:    return $reply;
                   6460: }
                   6461: 
                   6462: sub old_putstore {
1.716     albertel 6463:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6464:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6465:     if (!$uname) { $uname=$env{'user.name'}; }
                   6466:     my $uhome=&homeserver($uname,$udomain);
                   6467:     my %newstorehash;
1.800     albertel 6468:     foreach my $item (keys(%$storehash)) {
                   6469: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6470: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6471:     }
                   6472:     my $items='';
                   6473:     my %allitems = ();
1.800     albertel 6474:     foreach my $item (keys(%newstorehash)) {
                   6475: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6476: 	    my $key = $1.':keys:'.$2;
                   6477: 	    $allitems{$key} .= $3.':';
                   6478: 	}
1.800     albertel 6479: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6480:     }
1.800     albertel 6481:     foreach my $item (keys(%allitems)) {
                   6482: 	$allitems{$item} =~ s/\:$//;
                   6483: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6484:     }
                   6485:     $items=~s/\&$//;
                   6486:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6487: }
                   6488: 
1.47      www      6489: # ------------------------------------------------------ critical put interface
                   6490: 
                   6491: sub cput {
1.134     albertel 6492:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6493:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6494:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6495:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6496:    my $items='';
1.800     albertel 6497:    foreach my $item (keys(%$storehash)) {
                   6498:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6499:    }
1.47      www      6500:    $items=~s/\&$//;
1.134     albertel 6501:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6502: }
                   6503: 
                   6504: # -------------------------------------------------------------- eget interface
                   6505: 
                   6506: sub eget {
1.133     albertel 6507:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6508:    my $items='';
1.800     albertel 6509:    foreach my $item (@$storearr) {
                   6510:        $items.=&escape($item).'&';
1.191     harris41 6511:    }
1.12      www      6512:    $items=~s/\&$//;
1.620     albertel 6513:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6514:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6515:    my $uhome=&homeserver($uname,$udomain);
                   6516:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6517:    my @pairs=split(/\&/,$rep);
                   6518:    my %returnhash=();
1.42      www      6519:    my $i=0;
1.800     albertel 6520:    foreach my $item (@$storearr) {
                   6521:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6522:       $i++;
1.191     harris41 6523:    }
1.12      www      6524:    return %returnhash;
                   6525: }
                   6526: 
1.667     albertel 6527: # ------------------------------------------------------------ tmpput interface
                   6528: sub tmpput {
1.802     raeburn  6529:     my ($storehash,$server,$context)=@_;
1.667     albertel 6530:     my $items='';
1.800     albertel 6531:     foreach my $item (keys(%$storehash)) {
                   6532: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6533:     }
                   6534:     $items=~s/\&$//;
1.802     raeburn  6535:     if (defined($context)) {
                   6536:         $items .= ':'.&escape($context);
                   6537:     }
1.667     albertel 6538:     return &reply("tmpput:$items",$server);
                   6539: }
                   6540: 
                   6541: # ------------------------------------------------------------ tmpget interface
                   6542: sub tmpget {
1.688     albertel 6543:     my ($token,$server)=@_;
                   6544:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6545:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6546:     my %returnhash;
1.1328    raeburn  6547:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6548:         return %returnhash;
                   6549:     }
1.667     albertel 6550:     foreach my $item (split(/\&/,$rep)) {
                   6551: 	my ($key,$value)=split(/=/,$item);
                   6552: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6553:     }
                   6554:     return %returnhash;
                   6555: }
                   6556: 
1.1113    raeburn  6557: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6558: sub tmpdel {
                   6559:     my ($token,$server)=@_;
                   6560:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6561:     return &reply("tmpdel:$token",$server);
                   6562: }
                   6563: 
1.1198    raeburn  6564: # ------------------------------------------------------------ get_timebased_id 
                   6565: 
                   6566: sub get_timebased_id {
                   6567:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6568:         $maxtries) = @_;
                   6569:     my ($newid,$error,$dellock);
                   6570:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6571:         return ('','ok','invalid call to get suffix');
                   6572:     }
                   6573: 
                   6574: # set defaults for any optional args for which values were not supplied
                   6575:     if ($who eq '') {
                   6576:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6577:     }
                   6578:     if (!$locktries) {
                   6579:         $locktries = 3;
                   6580:     }
                   6581:     if (!$maxtries) {
                   6582:         $maxtries = 10;
                   6583:     }
                   6584:     
                   6585:     if (($cdom eq '') || ($cnum eq '')) {
                   6586:         if ($env{'request.course.id'}) {
                   6587:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6588:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6589:         }
                   6590:         if (($cdom eq '') || ($cnum eq '')) {
                   6591:             return ('','ok','call to get suffix not in course context');
                   6592:         }
                   6593:     }
                   6594: 
                   6595: # construct locking item
                   6596:     my $lockhash = {
                   6597:                       $prefix."\0".'locked_'.$keyid => $who,
                   6598:                    };
                   6599:     my $tries = 0;
                   6600: 
                   6601: # attempt to get lock on nohist_$namespace file
                   6602:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6603:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6604:         $tries ++;
                   6605:         sleep 1;
                   6606:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6607:     }
                   6608: 
                   6609: # attempt to get unique identifier, based on current timestamp
                   6610:     if ($gotlock eq 'ok') {
                   6611:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6612:         my $id = time;
                   6613:         $newid = $id;
1.1268    raeburn  6614:         if ($idtype eq 'addcode') {
                   6615:             $newid .= &sixnum_code();
                   6616:         }
1.1198    raeburn  6617:         my $idtries = 0;
                   6618:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6619:             if ($idtype eq 'concat') {
                   6620:                 $newid = $id.$idtries;
1.1268    raeburn  6621:             } elsif ($idtype eq 'addcode') {
                   6622:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6623:             } else {
                   6624:                 $newid ++;
                   6625:             }
                   6626:             $idtries ++;
                   6627:         }
                   6628:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6629:             my %new_item =  (
                   6630:                               $prefix."\0".$newid => $who,
                   6631:                             );
                   6632:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6633:                                                  $cdom,$cnum);
                   6634:             if ($putresult ne 'ok') {
                   6635:                 undef($newid);
                   6636:                 $error = 'error saving new item: '.$putresult;
                   6637:             }
                   6638:         } else {
1.1268    raeburn  6639:              undef($newid);
1.1198    raeburn  6640:              $error = ('error: no unique suffix available for the new item ');
                   6641:         }
                   6642: #  remove lock
                   6643:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6644:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6645:     } else {
                   6646:         $error = "error: could not obtain lockfile\n";
                   6647:         $dellock = 'ok';
1.1276    raeburn  6648:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6649:             $dellock = 'nolock';
                   6650:         }
1.1198    raeburn  6651:     }
                   6652:     return ($newid,$dellock,$error);
                   6653: }
                   6654: 
1.1268    raeburn  6655: sub sixnum_code {
                   6656:     my $code;
                   6657:     for (0..6) {
                   6658:         $code .= int( rand(9) );
                   6659:     }
                   6660:     return $code;
                   6661: }
                   6662: 
1.765     albertel 6663: # -------------------------------------------------- portfolio access checking
                   6664: 
                   6665: sub portfolio_access {
1.1270    raeburn  6666:     my ($requrl,$clientip) = @_;
1.765     albertel 6667:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6668:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6669:     if ($result) {
                   6670:         my %setters;
                   6671:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6672:             my ($startblock,$endblock) =
                   6673:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6674:             if ($startblock && $endblock) {
                   6675:                 return 'B';
                   6676:             }
                   6677:         } else {
                   6678:             my ($startblock,$endblock) =
                   6679:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6680:             if ($startblock && $endblock) {
                   6681:                 return 'B';
                   6682:             }
                   6683:         }
                   6684:     }
1.765     albertel 6685:     if ($result eq 'ok') {
1.766     albertel 6686:        return 'F';
1.765     albertel 6687:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6688:        return 'A';
1.765     albertel 6689:     }
1.766     albertel 6690:     return '';
1.765     albertel 6691: }
                   6692: 
                   6693: sub get_portfolio_access {
1.1270    raeburn  6694:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6695: 
                   6696:     if (!ref($access_hash)) {
                   6697: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6698: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6699: 						   $file_name);
                   6700: 	$access_hash = $access_controls{$file_name};
                   6701:     }
                   6702: 
1.1270    raeburn  6703:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6704:     my $now = time;
                   6705:     if (ref($access_hash) eq 'HASH') {
                   6706:         foreach my $key (keys(%{$access_hash})) {
                   6707:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6708:             if ($start > $now) {
                   6709:                 next;
                   6710:             }
                   6711:             if ($end && $end<$now) {
                   6712:                 next;
                   6713:             }
                   6714:             if ($scope eq 'public') {
                   6715:                 $public = $key;
                   6716:                 last;
                   6717:             } elsif ($scope eq 'guest') {
                   6718:                 $guest = $key;
                   6719:             } elsif ($scope eq 'domains') {
                   6720:                 push(@domains,$key);
                   6721:             } elsif ($scope eq 'users') {
                   6722:                 push(@users,$key);
                   6723:             } elsif ($scope eq 'course') {
                   6724:                 push(@courses,$key);
                   6725:             } elsif ($scope eq 'group') {
                   6726:                 push(@groups,$key);
1.1270    raeburn  6727:             } elsif ($scope eq 'ip') {
                   6728:                 push(@ips,$key);
1.765     albertel 6729:             }
                   6730:         }
                   6731:         if ($public) {
                   6732:             return 'ok';
1.1270    raeburn  6733:         } elsif (@ips > 0) {
                   6734:             my $allowed;
                   6735:             foreach my $ipkey (@ips) {
                   6736:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6737:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6738:                         $allowed = 1;
                   6739:                         last; 
                   6740:                     }
                   6741:                 }
                   6742:             }
                   6743:             if ($allowed) {
                   6744:                 return 'ok';
                   6745:             }
1.765     albertel 6746:         }
                   6747:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6748:             if ($guest) {
                   6749:                 return $guest;
                   6750:             }
                   6751:         } else {
                   6752:             if (@domains > 0) {
                   6753:                 foreach my $domkey (@domains) {
                   6754:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6755:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6756:                             return 'ok';
                   6757:                         }
                   6758:                     }
                   6759:                 }
                   6760:             }
                   6761:             if (@users > 0) {
                   6762:                 foreach my $userkey (@users) {
1.865     raeburn  6763:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6764:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6765:                             if (ref($item) eq 'HASH') {
                   6766:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6767:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6768:                                     return 'ok';
                   6769:                                 }
                   6770:                             }
                   6771:                         }
                   6772:                     } 
1.765     albertel 6773:                 }
                   6774:             }
                   6775:             my %roleshash;
                   6776:             my @courses_and_groups = @courses;
                   6777:             push(@courses_and_groups,@groups); 
                   6778:             if (@courses_and_groups > 0) {
                   6779:                 my (%allgroups,%allroles); 
                   6780:                 my ($start,$end,$role,$sec,$group);
                   6781:                 foreach my $envkey (%env) {
1.1060    raeburn  6782:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6783:                         my $cid = $2.'_'.$3; 
                   6784:                         if ($1 eq 'gr') {
                   6785:                             $group = $4;
                   6786:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6787:                         } else {
                   6788:                             if ($4 eq '') {
                   6789:                                 $sec = 'none';
                   6790:                             } else {
                   6791:                                 $sec = $4;
                   6792:                             }
                   6793:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6794:                         }
1.811     albertel 6795:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6796:                         my $cid = $2.'_'.$3;
                   6797:                         if ($4 eq '') {
                   6798:                             $sec = 'none';
                   6799:                         } else {
                   6800:                             $sec = $4;
                   6801:                         }
                   6802:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6803:                     }
                   6804:                 }
                   6805:                 if (keys(%allroles) == 0) {
                   6806:                     return;
                   6807:                 }
                   6808:                 foreach my $key (@courses_and_groups) {
                   6809:                     my %content = %{$$access_hash{$key}};
                   6810:                     my $cnum = $content{'number'};
                   6811:                     my $cdom = $content{'domain'};
                   6812:                     my $cid = $cdom.'_'.$cnum;
                   6813:                     if (!exists($allroles{$cid})) {
                   6814:                         next;
                   6815:                     }    
                   6816:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6817:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6818:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6819:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6820:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6821:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6822:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6823:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6824:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6825:                                         if (grep/^all$/,@sections) {
                   6826:                                             return 'ok';
                   6827:                                         } else {
                   6828:                                             if (grep/^$sec$/,@sections) {
                   6829:                                                 return 'ok';
                   6830:                                             }
                   6831:                                         }
                   6832:                                     }
                   6833:                                 }
                   6834:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6835:                                     if (grep/^none$/,@groups) {
                   6836:                                         return 'ok';
                   6837:                                     }
                   6838:                                 } else {
                   6839:                                     if (grep/^all$/,@groups) {
                   6840:                                         return 'ok';
                   6841:                                     } 
                   6842:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6843:                                         if (grep/^$group$/,@groups) {
                   6844:                                             return 'ok';
                   6845:                                         }
                   6846:                                     }
                   6847:                                 } 
                   6848:                             }
                   6849:                         }
                   6850:                     }
                   6851:                 }
                   6852:             }
                   6853:             if ($guest) {
                   6854:                 return $guest;
                   6855:             }
                   6856:         }
                   6857:     }
                   6858:     return;
                   6859: }
                   6860: 
                   6861: sub course_group_datechecker {
                   6862:     my ($dates,$now,$status) = @_;
                   6863:     my ($start,$end) = split(/\./,$dates);
                   6864:     if (!$start && !$end) {
                   6865:         return 'ok';
                   6866:     }
                   6867:     if (grep/^active$/,@{$status}) {
                   6868:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6869:             return 'ok';
                   6870:         }
                   6871:     }
                   6872:     if (grep/^previous$/,@{$status}) {
                   6873:         if ($end > $now ) {
                   6874:             return 'ok';
                   6875:         }
                   6876:     }
                   6877:     if (grep/^future$/,@{$status}) {
                   6878:         if ($start > $now) {
                   6879:             return 'ok';
                   6880:         }
                   6881:     }
                   6882:     return; 
                   6883: }
                   6884: 
                   6885: sub parse_portfolio_url {
                   6886:     my ($url) = @_;
                   6887: 
                   6888:     my ($type,$udom,$unum,$group,$file_name);
                   6889:     
1.823     albertel 6890:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6891: 	$type = 1;
                   6892:         $udom = $1;
                   6893:         $unum = $2;
                   6894:         $file_name = $3;
1.823     albertel 6895:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6896: 	$type = 2;
                   6897:         $udom = $1;
                   6898:         $unum = $2;
                   6899:         $group = $3;
                   6900:         $file_name = $3.'/'.$4;
                   6901:     }
                   6902:     if (wantarray) {
                   6903: 	return ($type,$udom,$unum,$file_name,$group);
                   6904:     }
                   6905:     return $type;
                   6906: }
                   6907: 
                   6908: sub is_portfolio_url {
                   6909:     my ($url) = @_;
                   6910:     return scalar(&parse_portfolio_url($url));
                   6911: }
                   6912: 
1.798     raeburn  6913: sub is_portfolio_file {
                   6914:     my ($file) = @_;
1.820     raeburn  6915:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6916:         return 1;
                   6917:     }
                   6918:     return;
                   6919: }
                   6920: 
1.976     raeburn  6921: sub usertools_access {
1.1084    raeburn  6922:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6923:     my ($access,%tools);
                   6924:     if ($context eq '') {
                   6925:         $context = 'tools';
                   6926:     }
                   6927:     if ($context eq 'requestcourses') {
                   6928:         %tools = (
                   6929:                       official   => 1,
                   6930:                       unofficial => 1,
1.1006    raeburn  6931:                       community  => 1,
1.1246    raeburn  6932:                       textbook   => 1,
1.1305    raeburn  6933:                       placement  => 1,
1.985     raeburn  6934:                  );
1.1183    raeburn  6935:     } elsif ($context eq 'requestauthor') {
                   6936:         %tools = (
                   6937:                       requestauthor => 1,
                   6938:                  );
1.985     raeburn  6939:     } else {
                   6940:         %tools = (
                   6941:                       aboutme   => 1,
                   6942:                       blog      => 1,
1.1177    raeburn  6943:                       webdav    => 1,
1.985     raeburn  6944:                       portfolio => 1,
                   6945:                  );
                   6946:     }
1.976     raeburn  6947:     return if (!defined($tools{$tool}));
                   6948: 
1.1242    raeburn  6949:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6950:         $udom = $env{'user.domain'};
                   6951:         $uname = $env{'user.name'};
                   6952:     }
                   6953: 
1.978     raeburn  6954:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6955:         if ($action ne 'reload') {
1.985     raeburn  6956:             if ($context eq 'requestcourses') {
                   6957:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6958:             } elsif ($context eq 'requestauthor') {
                   6959:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6960:             } else {
                   6961:                 return $env{'environment.availabletools.'.$tool};
                   6962:             }
                   6963:         }
1.976     raeburn  6964:     }
                   6965: 
1.1183    raeburn  6966:     my ($toolstatus,$inststatus,$envkey);
                   6967:     if ($context eq 'requestauthor') {
                   6968:         $envkey = $context; 
                   6969:     } else {
                   6970:         $envkey = $context.'.'.$tool;
                   6971:     }
1.976     raeburn  6972: 
1.985     raeburn  6973:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6974:          ($action ne 'reload')) {
1.1183    raeburn  6975:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6976:         $inststatus = $env{'environment.inststatus'};
                   6977:     } else {
1.1084    raeburn  6978:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6979:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6980:             $inststatus = $userenvref->{'inststatus'};
                   6981:         } else {
1.1183    raeburn  6982:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6983:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6984:             $inststatus = $userenv{'inststatus'};
                   6985:         }
1.976     raeburn  6986:     }
                   6987: 
                   6988:     if ($toolstatus ne '') {
                   6989:         if ($toolstatus) {
                   6990:             $access = 1;
                   6991:         } else {
                   6992:             $access = 0;
                   6993:         }
                   6994:         return $access;
                   6995:     }
                   6996: 
1.1084    raeburn  6997:     my ($is_adv,%domdef);
                   6998:     if (ref($is_advref) eq 'HASH') {
                   6999:         $is_adv = $is_advref->{'is_adv'};
                   7000:     } else {
                   7001:         $is_adv = &is_advanced_user($udom,$uname);
                   7002:     }
                   7003:     if (ref($domdefref) eq 'HASH') {
                   7004:         %domdef = %{$domdefref};
                   7005:     } else {
                   7006:         %domdef = &get_domain_defaults($udom);
                   7007:     }
1.976     raeburn  7008:     if (ref($domdef{$tool}) eq 'HASH') {
                   7009:         if ($is_adv) {
                   7010:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7011:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7012:                     $access = 1;
                   7013:                 } else {
                   7014:                     $access = 0;
                   7015:                 }
                   7016:                 return $access;
                   7017:             }
                   7018:         }
                   7019:         if ($inststatus ne '') {
                   7020:             my ($hasaccess,$hasnoaccess);
                   7021:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7022:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7023:                     if ($domdef{$tool}{$affiliation}) {
                   7024:                         $hasaccess = 1;
                   7025:                     } else {
                   7026:                         $hasnoaccess = 1;
                   7027:                     }
                   7028:                 }
                   7029:             }
                   7030:             if ($hasaccess || $hasnoaccess) {
                   7031:                 if ($hasaccess) {
                   7032:                     $access = 1;
                   7033:                 } elsif ($hasnoaccess) {
                   7034:                     $access = 0; 
                   7035:                 }
                   7036:                 return $access;
                   7037:             }
                   7038:         } else {
                   7039:             if ($domdef{$tool}{'default'} ne '') {
                   7040:                 if ($domdef{$tool}{'default'}) {
                   7041:                     $access = 1;
                   7042:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7043:                     $access = 0;
                   7044:                 }
                   7045:                 return $access;
                   7046:             }
                   7047:         }
                   7048:     } else {
1.1177    raeburn  7049:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7050:             $access = 1;
                   7051:         } else {
                   7052:             $access = 0;
                   7053:         }
1.976     raeburn  7054:         return $access;
                   7055:     }
                   7056: }
                   7057: 
1.1050    raeburn  7058: sub is_course_owner {
                   7059:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7060:     if (($udom eq '') || ($uname eq '')) {
                   7061:         $udom = $env{'user.domain'};
                   7062:         $uname = $env{'user.name'};
                   7063:     }
                   7064:     unless (($udom eq '') || ($uname eq '')) {
                   7065:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7066:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7067:                 return 1;
                   7068:             } else {
                   7069:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7070:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7071:                     return 1;
                   7072:                 }
                   7073:             }
                   7074:         }
                   7075:     }
                   7076:     return;
                   7077: }
                   7078: 
1.976     raeburn  7079: sub is_advanced_user {
                   7080:     my ($udom,$uname) = @_;
1.1085    raeburn  7081:     if ($udom ne '' && $uname ne '') {
                   7082:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7083:             if (wantarray) {
                   7084:                 return ($env{'user.adv'},$env{'user.author'});
                   7085:             } else {
                   7086:                 return $env{'user.adv'};
                   7087:             }
1.1085    raeburn  7088:         }
                   7089:     }
1.976     raeburn  7090:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7091:     my %allroles;
1.1128    raeburn  7092:     my ($is_adv,$is_author);
1.976     raeburn  7093:     foreach my $role (keys(%roleshash)) {
                   7094:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7095:         my $area = '/'.$tdomain.'/'.$trest;
                   7096:         if ($sec ne '') {
                   7097:             $area .= '/'.$sec;
                   7098:         }
                   7099:         if (($area ne '') && ($trole ne '')) {
                   7100:             my $spec=$trole.'.'.$area;
                   7101:             if ($trole =~ /^cr\//) {
                   7102:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7103:             } elsif ($trole ne 'gr') {
                   7104:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7105:             }
1.1128    raeburn  7106:             if ($trole eq 'au') {
                   7107:                 $is_author = 1;
                   7108:             }
1.976     raeburn  7109:         }
                   7110:     }
                   7111:     foreach my $role (keys(%allroles)) {
                   7112:         last if ($is_adv);
                   7113:         foreach my $item (split(/:/,$allroles{$role})) {
                   7114:             if ($item ne '') {
                   7115:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7116:                 if ($privilege eq 'adv') {
                   7117:                     $is_adv = 1;
                   7118:                     last;
                   7119:                 }
                   7120:             }
                   7121:         }
                   7122:     }
1.1128    raeburn  7123:     if (wantarray) {
                   7124:         return ($is_adv,$is_author);
                   7125:     }
1.976     raeburn  7126:     return $is_adv;
                   7127: }
1.798     raeburn  7128: 
1.1035    raeburn  7129: sub check_can_request {
1.1036    raeburn  7130:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7131:     my $canreq = 0;
                   7132:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7133:     my @options = ('approval','validate','autolimit');
                   7134:     my $optregex = join('|',@options);
                   7135:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7136:         foreach my $type (@{$types}) {
                   7137:             if (&usertools_access($env{'user.name'},
                   7138:                                   $env{'user.domain'},
                   7139:                                   $type,undef,'requestcourses')) {
                   7140:                 $canreq ++;
1.1036    raeburn  7141:                 if (ref($request_domains) eq 'HASH') {
                   7142:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7143:                 }
1.1035    raeburn  7144:                 if ($dom eq $env{'user.domain'}) {
                   7145:                     $can_request->{$type} = 1;
                   7146:                 }
                   7147:             }
                   7148:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7149:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7150:                 if (@curr > 0) {
1.1036    raeburn  7151:                     foreach my $item (@curr) {
                   7152:                         if (ref($request_domains) eq 'HASH') {
                   7153:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7154:                             if ($otherdom ne '') {
                   7155:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7156:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7157:                                         push(@{$request_domains->{$type}},$otherdom);
                   7158:                                     }
                   7159:                                 } else {
                   7160:                                     push(@{$request_domains->{$type}},$otherdom);
                   7161:                                 }
                   7162:                             }
                   7163:                         }
                   7164:                     }
                   7165:                     unless($dom eq $env{'user.domain'}) {
                   7166:                         $canreq ++;
1.1035    raeburn  7167:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7168:                             $can_request->{$type} = 1;
                   7169:                         }
                   7170:                     }
                   7171:                 }
                   7172:             }
                   7173:         }
                   7174:     }
                   7175:     return $canreq;
                   7176: }
                   7177: 
1.341     www      7178: # ---------------------------------------------- Custom access rule evaluation
                   7179: 
                   7180: sub customaccess {
                   7181:     my ($priv,$uri)=@_;
1.807     albertel 7182:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7183:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7184:     $udom = &LONCAPA::clean_domain($udom);
                   7185:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7186:     my $access=0;
1.800     albertel 7187:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7188: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7189: 	if ($type eq 'user') {
                   7190: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7191: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7192: 		if ($tdom) {
                   7193: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7194: 		}
1.896     albertel 7195: 		if ($tuname) {
                   7196: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7197: 		}
                   7198: 		$access=($effect eq 'allow');
                   7199: 		last;
                   7200: 	    }
                   7201: 	} else {
                   7202: 	    if ($role) {
                   7203: 		if ($role ne $urole) { next; }
                   7204: 	    }
                   7205: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7206: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7207: 		if ($tdom) {
                   7208: 		    if ($tdom ne $udom) { next; }
                   7209: 		}
                   7210: 		if ($tcrs) {
                   7211: 		    if ($tcrs ne $ucrs) { next; }
                   7212: 		}
                   7213: 		if ($tsec) {
                   7214: 		    if ($tsec ne $usec) { next; }
                   7215: 		}
                   7216: 		$access=($effect eq 'allow');
                   7217: 		last;
                   7218: 	    }
                   7219: 	    if ($realm eq '' && $role eq '') {
                   7220: 		$access=($effect eq 'allow');
                   7221: 	    }
1.402     bowersj2 7222: 	}
1.341     www      7223:     }
                   7224:     return $access;
                   7225: }
                   7226: 
1.103     harris41 7227: # ------------------------------------------------- Check for a user privilege
1.12      www      7228: 
                   7229: sub allowed {
1.1281    raeburn  7230:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7231:     my $ver_orguri=$uri;
1.439     www      7232:     $uri=&deversion($uri);
1.152     www      7233:     my $orguri=$uri;
1.52      www      7234:     $uri=&declutter($uri);
1.809     raeburn  7235: 
1.810     raeburn  7236:     if ($priv eq 'evb') {
                   7237: # Evade communication block restrictions for specified role in a course
                   7238:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7239:             return $1;
                   7240:         } else {
                   7241:             return;
                   7242:         }
                   7243:     }
                   7244: 
1.620     albertel 7245:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7246: # Free bre access to adm and meta resources
1.775     albertel 7247:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7248: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7249: 	&& ($priv eq 'bre')) {
1.14      www      7250: 	return 'F';
1.159     www      7251:     }
                   7252: 
1.545     banghart 7253: # Free bre access to user's own portfolio contents
1.714     raeburn  7254:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7255:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7256: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7257:         my %setters;
                   7258:         my ($startblock,$endblock) = 
                   7259:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7260:         if ($startblock && $endblock) {
                   7261:             return 'B';
                   7262:         } else {
                   7263:             return 'F';
                   7264:         }
1.545     banghart 7265:     }
                   7266: 
1.762     raeburn  7267: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7268:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7269:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7270:         if (exists($env{'request.course.id'})) {
                   7271:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7272:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7273:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7274:                 my $courseprivid=$env{'request.course.id'};
                   7275:                 $courseprivid=~s/\_/\//;
                   7276:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7277:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7278:                     return $1; 
1.762     raeburn  7279:                 } else {
                   7280:                     if ($env{'request.course.sec'}) {
                   7281:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7282:                     }
                   7283:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7284:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7285:                         return $2;
                   7286:                     }
1.714     raeburn  7287:                 }
                   7288:             }
                   7289:         }
                   7290:     }
                   7291: 
1.159     www      7292: # Free bre to public access
                   7293: 
                   7294:     if ($priv eq 'bre') {
1.238     www      7295:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7296: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7297:            return 'F'; 
                   7298:         }
1.238     www      7299:         if ($copyright eq 'priv') {
                   7300:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7301: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7302: 		return '';
                   7303:             }
                   7304:         }
                   7305:         if ($copyright eq 'domain') {
                   7306:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7307: 	    unless (($env{'user.domain'} eq $1) ||
                   7308:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7309: 		return '';
                   7310:             }
1.262     matthew  7311:         }
1.620     albertel 7312:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7313:             # Library role, so allow browsing of resources in this domain.
                   7314:             return 'F';
1.238     www      7315:         }
1.341     www      7316:         if ($copyright eq 'custom') {
                   7317: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7318:         }
1.14      www      7319:     }
1.264     matthew  7320:     # Domain coordinator is trying to create a course
1.620     albertel 7321:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7322:         # uri is the requested domain in this case.
                   7323:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7324:         # a role of dc for the domain in question.
1.620     albertel 7325:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7326:     }
1.29      www      7327: 
1.52      www      7328:     my $thisallowed='';
                   7329:     my $statecond=0;
                   7330:     my $courseprivid='';
                   7331: 
1.1039    raeburn  7332:     my $ownaccess;
1.1043    raeburn  7333:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7334:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7335:         if ($uri eq '') {
                   7336:             $ownaccess = 1;
                   7337:         } else {
                   7338:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7339:                 my $udom = $env{'user.domain'};
                   7340:                 my $uname = $env{'user.name'};
                   7341:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7342:                     $ownaccess = 1;
1.1040    raeburn  7343:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7344:                     unless ($uri =~ m{\.\./}) {
                   7345:                         $ownaccess = 1;
                   7346:                     }
                   7347:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7348:                     my $now = time;
                   7349:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7350:                         my $adom = $1;
                   7351:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7352:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7353:                                 my ($start,$end) = split('.',$env{$key});
                   7354:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7355:                                     $ownaccess = 1;
                   7356:                                     last;
                   7357:                                 }
                   7358:                             }
                   7359:                         }
                   7360:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7361:                         my $adom = $1;
                   7362:                         my $aname = $2;
1.1042    raeburn  7363:                         foreach my $role ('ca','aa') { 
                   7364:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7365:                                 my ($start,$end) =
                   7366:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7367:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7368:                                     $ownaccess = 1;
                   7369:                                     last;
                   7370:                                 }
1.1039    raeburn  7371:                             }
                   7372:                         }
                   7373:                     }
                   7374:                 }
                   7375:             }
                   7376:         }
                   7377:     }
                   7378: 
1.52      www      7379: # Course
                   7380: 
1.620     albertel 7381:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7382:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7383:             $thisallowed.=$1;
                   7384:         }
1.52      www      7385:     }
1.29      www      7386: 
1.52      www      7387: # Domain
                   7388: 
1.620     albertel 7389:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7390:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7391:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7392:             $thisallowed.=$1;
                   7393:         }
1.12      www      7394:     }
1.52      www      7395: 
1.1141    raeburn  7396: # User who is not author or co-author might still be able to edit
                   7397: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7398:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7399:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7400:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7401:             $thisallowed.=$1;
                   7402:         }
                   7403:     }
                   7404: 
1.52      www      7405: # Course: uri itself is a course
1.66      www      7406:     my $courseuri=$uri;
                   7407:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7408:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7409: 
1.620     albertel 7410:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7411:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7412:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7413:             $thisallowed.=$1;
                   7414:         }
1.12      www      7415:     }
1.29      www      7416: 
1.665     albertel 7417: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7418: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7419:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7420: 	$thisallowed='';
1.671     raeburn  7421:         my ($match)=&is_on_map($uri);
                   7422:         if ($match) {
                   7423:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7424:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7425:                 my $value = $1;
                   7426:                 if ($noblockcheck) {
                   7427:                     $thisallowed.=$value;
1.1162    raeburn  7428:                 } else {
1.1281    raeburn  7429:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7430:                     if (@blockers > 0) {
                   7431:                         $thisallowed = 'B';
                   7432:                     } else {
                   7433:                         $thisallowed.=$value;
                   7434:                     }
1.1162    raeburn  7435:                 }
1.671     raeburn  7436:             }
                   7437:         } else {
1.705     albertel 7438:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7439:             if ($refuri) {
                   7440:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7441:                     $thisallowed='F';
1.671     raeburn  7442:                 } else {
                   7443:                     $refuri=&declutter($refuri);
                   7444:                     my ($match) = &is_on_map($refuri);
                   7445:                     if ($match) {
1.1281    raeburn  7446:                         if ($noblockcheck) {
                   7447:                             $thisallowed='F';
1.1162    raeburn  7448:                         } else {
1.1281    raeburn  7449:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7450:                             if (@blockers > 0) {
                   7451:                                 $thisallowed = 'B';
                   7452:                             } else {
                   7453:                                 $thisallowed='F';
                   7454:                             }
1.1162    raeburn  7455:                         }
1.671     raeburn  7456:                     }
1.669     raeburn  7457:                 }
1.671     raeburn  7458:             }
                   7459:         }
1.314     www      7460:     }
1.492     albertel 7461: 
1.766     albertel 7462:     if ($priv eq 'bre'
                   7463: 	&& $thisallowed ne 'F' 
                   7464: 	&& $thisallowed ne '2'
                   7465: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7466: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7467:     }
1.1250    raeburn  7468: 
1.52      www      7469: # Full access at system, domain or course-wide level? Exit.
1.29      www      7470:     if ($thisallowed=~/F/) {
                   7471: 	return 'F';
                   7472:     }
                   7473: 
1.52      www      7474: # If this is generating or modifying users, exit with special codes
1.29      www      7475: 
1.643     www      7476:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7477: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7478: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7479: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7480: 	    unless ($auname) { return $thisallowed; }
                   7481: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7482: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7483: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7484: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7485: 	}
1.52      www      7486: 	return $thisallowed;
                   7487:     }
                   7488: #
1.103     harris41 7489: # Gathered so far: system, domain and course wide privileges
1.52      www      7490: #
                   7491: # Course: See if uri or referer is an individual resource that is part of 
                   7492: # the course
                   7493: 
1.620     albertel 7494:     if ($env{'request.course.id'}) {
1.232     www      7495: 
1.620     albertel 7496:        $courseprivid=$env{'request.course.id'};
                   7497:        if ($env{'request.course.sec'}) {
                   7498:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7499:        }
                   7500:        $courseprivid=~s/\_/\//;
                   7501:        my $checkreferer=1;
1.232     www      7502:        my ($match,$cond)=&is_on_map($uri);
                   7503:        if ($match) {
                   7504:            $statecond=$cond;
1.620     albertel 7505:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7506:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7507:                my $value = $1;
                   7508:                if ($priv eq 'bre') {
1.1281    raeburn  7509:                    if ($noblockcheck) {
                   7510:                        $thisallowed.=$value;
1.1162    raeburn  7511:                    } else {
1.1281    raeburn  7512:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7513:                        if (@blockers > 0) {
                   7514:                            $thisallowed = 'B';
                   7515:                        } else {
                   7516:                            $thisallowed.=$value;
                   7517:                        }
1.1162    raeburn  7518:                    }
                   7519:                } else {
                   7520:                    $thisallowed.=$value;
                   7521:                }
1.52      www      7522:                $checkreferer=0;
                   7523:            }
1.29      www      7524:        }
1.83      www      7525:        
1.148     www      7526:        if ($checkreferer) {
1.620     albertel 7527: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7528:             unless ($refuri) {
1.800     albertel 7529:                 foreach my $key (keys(%env)) {
                   7530: 		    if ($key=~/^httpref\..*\*/) {
                   7531: 			my $pattern=$key;
1.156     www      7532:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7533:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7534:                         $pattern=~s/\//\\\//g;
1.152     www      7535:                         if ($orguri=~/$pattern/) {
1.800     albertel 7536: 			    $refuri=$env{$key};
1.148     www      7537:                         }
                   7538:                     }
1.191     harris41 7539:                 }
1.148     www      7540:             }
1.232     www      7541: 
1.148     www      7542:          if ($refuri) { 
1.152     www      7543: 	  $refuri=&declutter($refuri);
1.232     www      7544:           my ($match,$cond)=&is_on_map($refuri);
                   7545:             if ($match) {
                   7546:               my $refstatecond=$cond;
1.620     albertel 7547:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7548:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7549:                   my $value = $1;
                   7550:                   if ($priv eq 'bre') {
1.1281    raeburn  7551:                       if ($noblockcheck) {
                   7552:                           $thisallowed.=$value;
1.1162    raeburn  7553:                       } else {
1.1281    raeburn  7554:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7555:                           if (@blockers > 0) {
                   7556:                               $thisallowed = 'B';
                   7557:                           } else {
                   7558:                               $thisallowed.=$value;
                   7559:                           }
1.1162    raeburn  7560:                       }
                   7561:                   } else {
                   7562:                       $thisallowed.=$value;
                   7563:                   }
1.53      www      7564:                   $uri=$refuri;
                   7565:                   $statecond=$refstatecond;
1.52      www      7566:               }
                   7567:           }
1.148     www      7568:         }
1.29      www      7569:        }
1.52      www      7570:    }
1.29      www      7571: 
1.52      www      7572: #
1.103     harris41 7573: # Gathered now: all privileges that could apply, and condition number
1.52      www      7574: # 
                   7575: #
                   7576: # Full or no access?
                   7577: #
1.29      www      7578: 
1.52      www      7579:     if ($thisallowed=~/F/) {
                   7580: 	return 'F';
                   7581:     }
1.29      www      7582: 
1.52      www      7583:     unless ($thisallowed) {
                   7584:         return '';
                   7585:     }
1.29      www      7586: 
1.52      www      7587: # Restrictions exist, deal with them
                   7588: #
                   7589: #   C:according to course preferences
                   7590: #   R:according to resource settings
                   7591: #   L:unless locked
                   7592: #   X:according to user session state
                   7593: #
                   7594: 
                   7595: # Possibly locked functionality, check all courses
1.54      www      7596: # Locks might take effect only after 10 minutes cache expiration for other
                   7597: # courses, and 2 minutes for current course
1.52      www      7598: 
                   7599:     my $envkey;
                   7600:     if ($thisallowed=~/L/) {
1.1000    raeburn  7601:         foreach $envkey (keys(%env)) {
1.54      www      7602:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7603:                my $courseid=$2;
                   7604:                my $roleid=$1.'.'.$2;
1.92      www      7605:                $courseid=~s/^\///;
1.54      www      7606:                my $expiretime=600;
1.620     albertel 7607:                if ($env{'request.role'} eq $roleid) {
1.54      www      7608: 		  $expiretime=120;
                   7609:                }
                   7610: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7611:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7612:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7613: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7614:                }
1.620     albertel 7615:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7616:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7617: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7618:                        &log($env{'user.domain'},$env{'user.name'},
                   7619:                             $env{'user.home'},
1.57      www      7620:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7621:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7622:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7623: 		       return '';
                   7624:                    }
                   7625:                }
1.620     albertel 7626:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7627:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7628: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7629:                        &log($env{'user.domain'},$env{'user.name'},
                   7630:                             $env{'user.home'},
1.57      www      7631:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7632:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7633:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7634: 		       return '';
                   7635:                    }
                   7636:                }
                   7637: 	   }
1.29      www      7638:        }
1.52      www      7639:     }
                   7640:    
                   7641: #
                   7642: # Rest of the restrictions depend on selected course
                   7643: #
                   7644: 
1.620     albertel 7645:     unless ($env{'request.course.id'}) {
1.766     albertel 7646: 	if ($thisallowed eq 'A') {
                   7647: 	    return 'A';
1.814     raeburn  7648:         } elsif ($thisallowed eq 'B') {
                   7649:             return 'B';
1.766     albertel 7650: 	} else {
                   7651: 	    return '1';
                   7652: 	}
1.52      www      7653:     }
1.29      www      7654: 
1.52      www      7655: #
                   7656: # Now user is definitely in a course
                   7657: #
1.53      www      7658: 
                   7659: 
                   7660: # Course preferences
                   7661: 
                   7662:    if ($thisallowed=~/C/) {
1.620     albertel 7663:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7664:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7665:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7666: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7667: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7668: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7669: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7670: 			$env{'request.course.id'});
                   7671: 	   }
1.237     www      7672:            return '';
                   7673:        }
                   7674: 
1.620     albertel 7675:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7676: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7677: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7678: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7679: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7680: 			$env{'request.course.id'});
                   7681: 	   }
1.54      www      7682:            return '';
                   7683:        }
1.53      www      7684:    }
                   7685: 
                   7686: # Resource preferences
                   7687: 
                   7688:    if ($thisallowed=~/R/) {
1.620     albertel 7689:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7690:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7691: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7692: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7693: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7694: 	   }
                   7695: 	   return '';
1.54      www      7696:        }
1.53      www      7697:    }
1.30      www      7698: 
1.246     www      7699: # Restricted by state or randomout?
1.30      www      7700: 
1.52      www      7701:    if ($thisallowed=~/X/) {
1.620     albertel 7702:       if ($env{'acc.randomout'}) {
1.579     albertel 7703: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7704:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7705:             return ''; 
                   7706:          }
1.247     www      7707:       }
                   7708:       if (&condval($statecond)) {
1.52      www      7709: 	 return '2';
                   7710:       } else {
                   7711:          return '';
                   7712:       }
                   7713:    }
1.30      www      7714: 
1.766     albertel 7715:     if ($thisallowed eq 'A') {
                   7716: 	return 'A';
1.814     raeburn  7717:     } elsif ($thisallowed eq 'B') {
                   7718:         return 'B';
1.766     albertel 7719:     }
1.52      www      7720:    return 'F';
1.232     www      7721: }
1.1162    raeburn  7722: 
1.1192    raeburn  7723: # ------------------------------------------- Check construction space access
                   7724: 
                   7725: sub constructaccess {
                   7726:     my ($url,$setpriv)=@_;
                   7727: 
                   7728: # We do not allow editing of previous versions of files
                   7729:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7730: 
                   7731: # Get username and domain from URL
                   7732:     my ($ownername,$ownerdomain,$ownerhome);
                   7733: 
                   7734:     ($ownerdomain,$ownername) =
1.1325    raeburn  7735:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7736: 
                   7737: # The URL does not really point to any authorspace, forget it
                   7738:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7739: 
                   7740: # Now we need to see if the user has access to the authorspace of
                   7741: # $ownername at $ownerdomain
                   7742: 
                   7743:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7744: # Real author for this?
                   7745:        $ownerhome = $env{'user.home'};
                   7746:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7747:           return ($ownername,$ownerdomain,$ownerhome);
                   7748:        }
                   7749:     } else {
                   7750: # Co-author for this?
                   7751:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7752:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7753:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7754:             return ($ownername,$ownerdomain,$ownerhome);
                   7755:         }
1.1312    raeburn  7756:         if ($env{'request.course.id'}) {
                   7757:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7758:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7759:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7760:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7761:                     return ($ownername,$ownerdomain,$ownerhome);
                   7762:                 }
                   7763:             }
                   7764:         }
1.1192    raeburn  7765:     }
                   7766: 
                   7767: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7768: # we might as well leave
                   7769:    unless ($setpriv) { return ''; }
                   7770: 
                   7771: # Backdoor access?
                   7772:     my $allowed=&allowed('eco',$ownerdomain);
                   7773: # Nope
                   7774:     unless ($allowed) { return ''; }
                   7775: # Looks like we may have access, but could be locked by the owner of the construction space
                   7776:     if ($allowed eq 'U') {
                   7777:         my %blocked=&get('environment',['domcoord.author'],
                   7778:                          $ownerdomain,$ownername);
                   7779: # Is blocked by owner
                   7780:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7781:     }
                   7782:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7783: # Grant temporary access
                   7784:         my $then=$env{'user.login.time'};
1.1209    raeburn  7785:         my $update=$env{'user.update.time'};
1.1192    raeburn  7786:         if (!$update) { $update = $then; }
                   7787:         my $refresh=$env{'user.refresh.time'};
                   7788:         if (!$refresh) { $refresh = $update; }
                   7789:         my $now = time;
                   7790:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7791:                            $now,'ca','constructaccess');
                   7792:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7793:         return($ownername,$ownerdomain,$ownerhome);
                   7794:     }
                   7795: # No business here
                   7796:     return '';
                   7797: }
                   7798: 
1.1282    raeburn  7799: # ----------------------------------------------------------- Content Blocking
                   7800: 
                   7801: {
                   7802: # Caches for faster Course Contents display where content blocking
                   7803: # is in operation (i.e., interval param set) for timed quiz.
                   7804: #
                   7805: # User for whom data are being temporarily cached.
                   7806: my $cacheduser='';
                   7807: # Cached blockers for this user (a hash of blocking items). 
                   7808: my %cachedblockers=();
                   7809: # When the data were last cached.
                   7810: my $cachedlast='';
                   7811: 
                   7812: sub load_all_blockers {
                   7813:     my ($uname,$udom,$blocks)=@_;
                   7814:     if (($uname ne '') && ($udom ne '')) { 
                   7815:         if (($cacheduser eq $uname.':'.$udom) &&
                   7816:             (abs($cachedlast-time)<5)) {
                   7817:             return;
                   7818:         }
                   7819:     }
                   7820:     $cachedlast=time;
                   7821:     $cacheduser=$uname.':'.$udom;
                   7822:     %cachedblockers = &get_commblock_resources($blocks);
                   7823: }
                   7824: 
1.1162    raeburn  7825: sub get_comm_blocks {
                   7826:     my ($cdom,$cnum) = @_;
                   7827:     if ($cdom eq '' || $cnum eq '') {
                   7828:         return unless ($env{'request.course.id'});
                   7829:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7830:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7831:     }
                   7832:     my %commblocks;
                   7833:     my $hashid=$cdom.'_'.$cnum;
                   7834:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7835:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7836:         %commblocks = %{$blocksref};
                   7837:     } else {
                   7838:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7839:         my $cachetime = 600;
                   7840:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7841:     }
                   7842:     return %commblocks;
                   7843: }
                   7844: 
1.1282    raeburn  7845: sub get_commblock_resources {
                   7846:     my ($blocks) = @_;
                   7847:     my %blockers = ();
                   7848:     return %blockers unless ($env{'request.course.id'});
                   7849:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7850:     my %commblocks;
                   7851:     if (ref($blocks) eq 'HASH') {
                   7852:         %commblocks = %{$blocks};
                   7853:     } else {
                   7854:         %commblocks = &get_comm_blocks();
                   7855:     }
1.1282    raeburn  7856:     return %blockers unless (keys(%commblocks) > 0); 
                   7857:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7858:     return %blockers unless (ref($navmap));
1.1162    raeburn  7859:     my $now = time;
                   7860:     foreach my $block (keys(%commblocks)) {
                   7861:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7862:             my ($start,$end) = ($1,$2);
                   7863:             if ($start <= $now && $end >= $now) {
                   7864:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7865:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7866:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7867:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7868:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7869:                             }
                   7870:                         }
                   7871:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7872:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7873:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7874:                             }
                   7875:                         }
                   7876:                     }
                   7877:                 }
                   7878:             }
                   7879:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7880:             my $item = $1;
1.1163    raeburn  7881:             my @to_test;
1.1162    raeburn  7882:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7883:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7884:                     my @interval;
                   7885:                     my $type = 'map';
                   7886:                     if ($item eq 'course') {
                   7887:                         $type = 'course';
                   7888:                         @interval=&EXT("resource.0.interval");
                   7889:                     } else {
                   7890:                         if ($item =~ /___\d+___/) {
                   7891:                             $type = 'resource';
                   7892:                             @interval=&EXT("resource.0.interval",$item);
                   7893:                             if (ref($navmap)) {                        
                   7894:                                 my $res = $navmap->getBySymb($item); 
                   7895:                                 push(@to_test,$res);
                   7896:                             }
1.1162    raeburn  7897:                         } else {
1.1282    raeburn  7898:                             my $mapsymb = &symbread($item,1);
                   7899:                             if ($mapsymb) {
                   7900:                                 if (ref($navmap)) {
                   7901:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7902:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7903:                                     foreach my $res (@to_test) {
                   7904:                                         my $symb = $res->symb();
                   7905:                                         next if ($symb eq $mapsymb);
                   7906:                                         if ($symb ne '') {
                   7907:                                             @interval=&EXT("resource.0.interval",$symb);
                   7908:                                             if ($interval[1] eq 'map') {
                   7909:                                                 last;
1.1162    raeburn  7910:                                             }
                   7911:                                         }
                   7912:                                     }
                   7913:                                 }
                   7914:                             }
                   7915:                         }
1.1282    raeburn  7916:                     }
1.1310    raeburn  7917:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7918:                         my $timelimit = $1; 
1.1282    raeburn  7919:                         my $first_access;
                   7920:                         if ($type eq 'resource') {
                   7921:                             $first_access=&get_first_access($interval[1],$item);
                   7922:                         } elsif ($type eq 'map') {
                   7923:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7924:                         } else {
                   7925:                             $first_access=&get_first_access($interval[1]);
                   7926:                         }
                   7927:                         if ($first_access) {
1.1292    raeburn  7928:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7929:                             if ($timesup > $now) {
                   7930:                                 my $activeblock;
                   7931:                                 foreach my $res (@to_test) {
1.1283    raeburn  7932:                                     if ($res->answerable()) {
1.1282    raeburn  7933:                                         $activeblock = 1;
                   7934:                                         last;
                   7935:                                     }
                   7936:                                 }
                   7937:                                 if ($activeblock) {
                   7938:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7939:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7940:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7941:                                          }
                   7942:                                     }
                   7943:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7944:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7945:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7946:                                         }
1.1162    raeburn  7947:                                     }
                   7948:                                 }
                   7949:                             }
                   7950:                         }
                   7951:                     }
                   7952:                 }
                   7953:             }
                   7954:         }
                   7955:     }
1.1282    raeburn  7956:     return %blockers;
1.1162    raeburn  7957: }
                   7958: 
1.1282    raeburn  7959: sub has_comm_blocking {
                   7960:     my ($priv,$symb,$uri,$blocks) = @_;
                   7961:     my @blockers;
                   7962:     return unless ($env{'request.course.id'});
                   7963:     return unless ($priv eq 'bre');
                   7964:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7965:     return if ($env{'request.state'} eq 'construct');
                   7966:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7967:     return unless (keys(%cachedblockers) > 0);
                   7968:     my (%possibles,@symbs);
                   7969:     if (!$symb) {
                   7970:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7971:     }
1.1282    raeburn  7972:     if ($symb) {
                   7973:         @symbs = ($symb);
                   7974:     } elsif (keys(%possibles)) { 
                   7975:         @symbs = keys(%possibles);
                   7976:     }
                   7977:     my $noblock;
                   7978:     foreach my $symb (@symbs) {
                   7979:         last if ($noblock);
                   7980:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7981:         foreach my $block (keys(%cachedblockers)) {
                   7982:             if ($block =~ /^firstaccess____(.+)$/) {
                   7983:                 my $item = $1;
                   7984:                 if (($item eq $map) || ($item eq $symb)) {
                   7985:                     $noblock = 1;
                   7986:                     last;
                   7987:                 }
                   7988:             }
                   7989:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7990:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7991:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7992:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7993:                             push(@blockers,$block);
                   7994:                         }
                   7995:                     }
                   7996:                 }
1.1162    raeburn  7997:             }
1.1282    raeburn  7998:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7999:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8000:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8001:                         push(@blockers,$block);
                   8002:                     }
                   8003:                 }
1.1162    raeburn  8004:             }
                   8005:         }
                   8006:     }
1.1282    raeburn  8007:     return if ($noblock);
                   8008:     return @blockers;
                   8009: }
1.1162    raeburn  8010: }
                   8011: 
1.1282    raeburn  8012: # -------------------------------- Deversion and split uri into path an filename   
                   8013: 
1.1133    foxr     8014: #
1.1282    raeburn  8015: #   Removes the version from a URI and
1.1133    foxr     8016: #   splits it in to its filename and path to the filename.
                   8017: #   Seems like File::Basename could have done this more clearly.
                   8018: #   Parameters:
                   8019: #      $uri   - input URI
                   8020: #   Returns:
                   8021: #     Two element list consisting of 
                   8022: #     $pathname  - the URI up to and excluding the trailing /
                   8023: #     $filename  - The part of the URI following the last /
                   8024: #  NOTE:
                   8025: #    Another realization of this is simply:
                   8026: #    use File::Basename;
                   8027: #    ...
                   8028: #    $uri = shift;
                   8029: #    $filename = basename($uri);
                   8030: #    $path     = dirname($uri);
                   8031: #    return ($filename, $path);
                   8032: #
                   8033: #     The implementation below is probably faster however.
                   8034: #
1.710     albertel 8035: sub split_uri_for_cond {
                   8036:     my $uri=&deversion(&declutter(shift));
                   8037:     my @uriparts=split(/\//,$uri);
                   8038:     my $filename=pop(@uriparts);
                   8039:     my $pathname=join('/',@uriparts);
                   8040:     return ($pathname,$filename);
                   8041: }
1.232     www      8042: # --------------------------------------------------- Is a resource on the map?
                   8043: 
                   8044: sub is_on_map {
1.710     albertel 8045:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8046:     #Trying to find the conditional for the file
1.620     albertel 8047:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8048: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8049:     if ($match) {
1.289     bowersj2 8050: 	return (1,$1);
                   8051:     } else {
1.434     www      8052: 	return (0,0);
1.289     bowersj2 8053:     }
1.12      www      8054: }
                   8055: 
1.427     www      8056: # --------------------------------------------------------- Get symb from alias
                   8057: 
                   8058: sub get_symb_from_alias {
                   8059:     my $symb=shift;
                   8060:     my ($map,$resid,$url)=&decode_symb($symb);
                   8061: # Already is a symb
                   8062:     if ($url) { return $symb; }
                   8063: # Must be an alias
                   8064:     my $aliassymb='';
                   8065:     my %bighash;
1.620     albertel 8066:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8067:                             &GDBM_READER(),0640)) {
                   8068:         my $rid=$bighash{'mapalias_'.$symb};
                   8069: 	if ($rid) {
                   8070: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8071: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8072: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8073: 	}
                   8074:         untie %bighash;
                   8075:     }
                   8076:     return $aliassymb;
                   8077: }
                   8078: 
1.12      www      8079: # ----------------------------------------------------------------- Define Role
                   8080: 
                   8081: sub definerole {
                   8082:   if (allowed('mcr','/')) {
1.1326    raeburn  8083:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8084:     foreach my $role (split(':',$sysrole)) {
                   8085: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8086:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8087:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8088: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8089:                return "refused:s:$crole&$cqual"; 
                   8090:             }
                   8091:         }
1.191     harris41 8092:     }
1.800     albertel 8093:     foreach my $role (split(':',$domrole)) {
                   8094: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8095:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8096:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8097: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8098:                return "refused:d:$crole&$cqual"; 
                   8099:             }
                   8100:         }
1.191     harris41 8101:     }
1.800     albertel 8102:     foreach my $role (split(':',$courole)) {
                   8103: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8104:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8105:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8106: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8107:                return "refused:c:$crole&$cqual"; 
                   8108:             }
                   8109:         }
1.191     harris41 8110:     }
1.1326    raeburn  8111:     my $uhome;
                   8112:     if (($uname ne '') && ($udom ne '')) {
                   8113:         $uhome = &homeserver($uname,$udom);
                   8114:         return $uhome if ($uhome eq 'no_host');
                   8115:     } else {
                   8116:         $uname = $env{'user.name'};
                   8117:         $udom = $env{'user.domain'};
                   8118:         $uhome = $env{'user.home'};
                   8119:     }
1.620     albertel 8120:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8121:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8122:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8123:     return reply($command,$uhome);
1.12      www      8124:   } else {
                   8125:     return 'refused';
                   8126:   }
1.105     harris41 8127: }
                   8128: 
                   8129: # ---------------- Make a metadata query against the network of library servers
                   8130: 
                   8131: sub metadata_query {
1.1237    raeburn  8132:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8133:     my %rhash;
1.845     albertel 8134:     my %libserv = &all_library();
1.244     matthew  8135:     my @server_list = (defined($server_array) ? @$server_array
                   8136:                                               : keys(%libserv) );
                   8137:     for my $server (@server_list) {
1.1237    raeburn  8138:         my $domains = ''; 
                   8139:         if (ref($domains_hash) eq 'HASH') {
                   8140:             $domains = $domains_hash->{$server}; 
                   8141:         }
1.118     harris41 8142: 	unless ($custom or $customshow) {
1.1237    raeburn  8143: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8144: 	    $rhash{$server}=$reply;
                   8145: 	}
                   8146: 	else {
                   8147: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8148: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8149: 			     $server);
                   8150: 	    $rhash{$server}=$reply;
                   8151: 	}
1.112     harris41 8152:     }
1.118     harris41 8153:     return \%rhash;
1.240     www      8154: }
                   8155: 
                   8156: # ----------------------------------------- Send log queries and wait for reply
                   8157: 
                   8158: sub log_query {
                   8159:     my ($uname,$udom,$query,%filters)=@_;
                   8160:     my $uhome=&homeserver($uname,$udom);
                   8161:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8162:     my $uhost=&hostname($uhome);
1.800     albertel 8163:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8164:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8165:                        $uhome);
1.479     albertel 8166:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8167:     return get_query_reply($queryid);
                   8168: }
                   8169: 
1.818     raeburn  8170: # -------------------------- Update MySQL table for portfolio file
                   8171: 
                   8172: sub update_portfolio_table {
1.821     raeburn  8173:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8174:     if ($group ne '') {
                   8175:         $file_name =~s /^\Q$group\E//;
                   8176:     }
1.818     raeburn  8177:     my $homeserver = &homeserver($uname,$udom);
                   8178:     my $queryid=
1.821     raeburn  8179:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8180:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8181:     my $reply = &get_query_reply($queryid);
                   8182:     return $reply;
                   8183: }
                   8184: 
1.899     raeburn  8185: # -------------------------- Update MySQL allusers table
                   8186: 
                   8187: sub update_allusers_table {
                   8188:     my ($uname,$udom,$names) = @_;
                   8189:     my $homeserver = &homeserver($uname,$udom);
                   8190:     my $queryid=
                   8191:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8192:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8193:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8194:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8195:                'generation='.&escape($names->{'generation'}).'%%'.
                   8196:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8197:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8198:     return;
1.899     raeburn  8199: }
                   8200: 
1.508     raeburn  8201: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8202: 
                   8203: sub fetch_enrollment_query {
1.511     raeburn  8204:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8205:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8206:     my $maxtries = 1;
1.508     raeburn  8207:     if ($context eq 'automated') {
                   8208:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8209:         $sleep = 2;
                   8210:         $loopmax = 100;
1.547     raeburn  8211:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8212:     } else {
                   8213:         $homeserver = &homeserver($cnum,$dom);
                   8214:     }
1.838     albertel 8215:     my $host=&hostname($homeserver);
1.506     raeburn  8216:     my $cmd = '';
1.1000    raeburn  8217:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8218:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8219:     }
                   8220:     $cmd =~ s/%%$//;
                   8221:     $cmd = &escape($cmd);
                   8222:     my $query = 'fetchenrollment';
1.620     albertel 8223:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8224:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8225:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8226:         return 'error: '.$queryid;
                   8227:     }
1.1317    raeburn  8228:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8229:     my $tries = 1;
                   8230:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8231:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8232:         $tries ++;
                   8233:     }
1.526     raeburn  8234:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8235:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8236:     } else {
1.901     albertel 8237:         my @responses = split(/:/,$reply);
1.1322    raeburn  8238:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8239:             foreach my $line (@responses) {
                   8240:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8241:                 $$replyref{$key} = $value;
                   8242:             }
                   8243:         } else {
1.1117    foxr     8244:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8245:             foreach my $line (@responses) {
                   8246:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8247:                 $$replyref{$key} = $value;
                   8248:                 if ($value > 0) {
1.800     albertel 8249:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8250:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8251:                         my $destname = $pathname.'/'.$filename;
                   8252:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8253:                         if ($xml_classlist =~ /^error/) {
                   8254:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8255:                         } else {
1.506     raeburn  8256:                             if ( open(FILE,">$destname") ) {
                   8257:                                 print FILE &unescape($xml_classlist);
                   8258:                                 close(FILE);
1.526     raeburn  8259:                             } else {
                   8260:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8261:                             }
                   8262:                         }
                   8263:                     }
                   8264:                 }
                   8265:             }
                   8266:         }
                   8267:         return 'ok';
                   8268:     }
                   8269:     return 'error';
                   8270: }
                   8271: 
1.242     www      8272: sub get_query_reply {
1.1317    raeburn  8273:     my ($queryid,$sleep,$loopmax) = @_;;
                   8274:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8275:         $sleep = 0.2;
                   8276:     }
                   8277:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8278:         $loopmax = 100;
                   8279:     }
1.1117    foxr     8280:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8281:     my $reply='';
1.1317    raeburn  8282:     for (1..$loopmax) {
                   8283: 	sleep($sleep);
1.240     www      8284:         if (-e $replyfile.'.end') {
1.448     albertel 8285: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 8286: 		$reply = join('',<$fh>);
                   8287: 		close($fh);
1.240     www      8288: 	   } else { return 'error: reply_file_error'; }
1.242     www      8289:            return &unescape($reply);
                   8290: 	}
1.240     www      8291:     }
1.242     www      8292:     return 'timeout:'.$queryid;
1.240     www      8293: }
                   8294: 
                   8295: sub courselog_query {
1.241     www      8296: #
                   8297: # possible filters:
                   8298: # url: url or symb
                   8299: # username
                   8300: # domain
                   8301: # action: view, submit, grade
                   8302: # start: timestamp
                   8303: # end: timestamp
                   8304: #
1.240     www      8305:     my (%filters)=@_;
1.620     albertel 8306:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8307:     if ($filters{'url'}) {
                   8308: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8309:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8310:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8311:     }
1.620     albertel 8312:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8313:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8314:     return &log_query($cname,$cdom,'courselog',%filters);
                   8315: }
                   8316: 
                   8317: sub userlog_query {
1.858     raeburn  8318: #
                   8319: # possible filters:
                   8320: # action: log check role
                   8321: # start: timestamp
                   8322: # end: timestamp
                   8323: #
1.240     www      8324:     my ($uname,$udom,%filters)=@_;
                   8325:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8326: }
                   8327: 
1.506     raeburn  8328: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8329: 
                   8330: sub auto_run {
1.508     raeburn  8331:     my ($cnum,$cdom) = @_;
1.876     raeburn  8332:     my $response = 0;
                   8333:     my $settings;
                   8334:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8335:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8336:         $settings = $domconfig{'autoenroll'};
                   8337:         if ($settings->{'run'} eq '1') {
                   8338:             $response = 1;
                   8339:         }
                   8340:     } else {
1.934     raeburn  8341:         my $homeserver;
                   8342:         if (&is_course($cdom,$cnum)) {
                   8343:             $homeserver = &homeserver($cnum,$cdom);
                   8344:         } else {
                   8345:             $homeserver = &domain($cdom,'primary');
                   8346:         }
                   8347:         if ($homeserver ne 'no_host') {
                   8348:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8349:         }
1.876     raeburn  8350:     }
1.506     raeburn  8351:     return $response;
                   8352: }
1.776     albertel 8353: 
1.506     raeburn  8354: sub auto_get_sections {
1.508     raeburn  8355:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8356:     my $homeserver;
                   8357:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8358:         $homeserver = &homeserver($cnum,$cdom);
                   8359:     }
                   8360:     if (!defined($homeserver)) { 
                   8361:         if ($cdom =~ /^$match_domain$/) {
                   8362:             $homeserver = &domain($cdom,'primary');
                   8363:         }
                   8364:     }
                   8365:     my @secs;
                   8366:     if (defined($homeserver)) {
                   8367:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8368:         unless ($response eq 'refused') {
                   8369:             @secs = split(/:/,$response);
                   8370:         }
1.506     raeburn  8371:     }
                   8372:     return @secs;
                   8373: }
1.776     albertel 8374: 
1.506     raeburn  8375: sub auto_new_course {
1.1099    raeburn  8376:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8377:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8378:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8379:     return $response;
                   8380: }
1.776     albertel 8381: 
1.506     raeburn  8382: sub auto_validate_courseID {
1.508     raeburn  8383:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8384:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8385:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8386:     return $response;
                   8387: }
1.776     albertel 8388: 
1.1007    raeburn  8389: sub auto_validate_instcode {
1.1020    raeburn  8390:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8391:     my ($homeserver,$response);
                   8392:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8393:         $homeserver = &homeserver($cnum,$cdom);
                   8394:     }
                   8395:     if (!defined($homeserver)) {
                   8396:         if ($cdom =~ /^$match_domain$/) {
                   8397:             $homeserver = &domain($cdom,'primary');
                   8398:         }
                   8399:     }
1.1065    raeburn  8400:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8401:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8402:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8403:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8404: }
                   8405: 
1.506     raeburn  8406: sub auto_create_password {
1.873     raeburn  8407:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8408:     my ($homeserver,$response);
1.506     raeburn  8409:     my $create_passwd = 0;
                   8410:     my $authchk = '';
1.873     raeburn  8411:     if ($udom =~ /^$match_domain$/) {
                   8412:         $homeserver = &domain($udom,'primary');
                   8413:     }
                   8414:     if ($homeserver eq '') {
                   8415:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8416:             $homeserver = &homeserver($cnum,$cdom);
                   8417:         }
                   8418:     }
                   8419:     if ($homeserver eq '') {
                   8420:         $authchk = 'nodomain';
1.506     raeburn  8421:     } else {
1.873     raeburn  8422:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8423:         if ($response eq 'refused') {
                   8424:             $authchk = 'refused';
                   8425:         } else {
1.901     albertel 8426:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8427:         }
1.506     raeburn  8428:     }
                   8429:     return ($authparam,$create_passwd,$authchk);
                   8430: }
                   8431: 
1.706     raeburn  8432: sub auto_photo_permission {
                   8433:     my ($cnum,$cdom,$students) = @_;
                   8434:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8435:     my ($outcome,$perm_reqd,$conditions) = 
                   8436: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8437:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8438: 	return (undef,undef);
                   8439:     }
1.706     raeburn  8440:     return ($outcome,$perm_reqd,$conditions);
                   8441: }
                   8442: 
                   8443: sub auto_checkphotos {
                   8444:     my ($uname,$udom,$pid) = @_;
                   8445:     my $homeserver = &homeserver($uname,$udom);
                   8446:     my ($result,$resulttype);
                   8447:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8448: 				   &escape($uname).':'.&escape($pid),
                   8449: 				   $homeserver));
1.709     albertel 8450:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8451: 	return (undef,undef);
                   8452:     }
1.706     raeburn  8453:     if ($outcome) {
                   8454:         ($result,$resulttype) = split(/:/,$outcome);
                   8455:     } 
                   8456:     return ($result,$resulttype);
                   8457: }
                   8458: 
                   8459: sub auto_photochoice {
                   8460:     my ($cnum,$cdom) = @_;
                   8461:     my $homeserver = &homeserver($cnum,$cdom);
                   8462:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8463: 						       &escape($cdom),
                   8464: 						       $homeserver)));
1.709     albertel 8465:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8466: 	return (undef,undef);
                   8467:     }
1.706     raeburn  8468:     return ($update,$comment);
                   8469: }
                   8470: 
                   8471: sub auto_photoupdate {
                   8472:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8473:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8474:     my $host=&hostname($homeserver);
1.706     raeburn  8475:     my $cmd = '';
                   8476:     my $maxtries = 1;
1.800     albertel 8477:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8478:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8479:     }
                   8480:     $cmd =~ s/%%$//;
                   8481:     $cmd = &escape($cmd);
                   8482:     my $query = 'institutionalphotos';
                   8483:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8484:     unless ($queryid=~/^\Q$host\E\_/) {
                   8485:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8486:         return 'error: '.$queryid;
                   8487:     }
                   8488:     my $reply = &get_query_reply($queryid);
                   8489:     my $tries = 1;
                   8490:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8491:         $reply = &get_query_reply($queryid);
                   8492:         $tries ++;
                   8493:     }
                   8494:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8495:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8496:     } else {
                   8497:         my @responses = split(/:/,$reply);
                   8498:         my $outcome = shift(@responses); 
                   8499:         foreach my $item (@responses) {
                   8500:             my ($key,$value) = split(/=/,$item);
                   8501:             $$photo{$key} = $value;
                   8502:         }
                   8503:         return $outcome;
                   8504:     }
                   8505:     return 'error';
                   8506: }
                   8507: 
1.521     raeburn  8508: sub auto_instcode_format {
1.793     albertel 8509:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8510: 	$cat_order) = @_;
1.521     raeburn  8511:     my $courses = '';
1.772     raeburn  8512:     my @homeservers;
1.521     raeburn  8513:     if ($caller eq 'global') {
1.841     albertel 8514: 	my %servers = &get_servers($codedom,'library');
                   8515: 	foreach my $tryserver (keys(%servers)) {
                   8516: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8517: 		push(@homeservers,$tryserver);
                   8518: 	    }
1.584     raeburn  8519:         }
1.1022    raeburn  8520:     } elsif ($caller eq 'requests') {
                   8521:         if ($codedom =~ /^$match_domain$/) {
                   8522:             my $chome = &domain($codedom,'primary');
                   8523:             unless ($chome eq 'no_host') {
                   8524:                 push(@homeservers,$chome);
                   8525:             }
                   8526:         }
1.521     raeburn  8527:     } else {
1.772     raeburn  8528:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8529:     }
1.793     albertel 8530:     foreach my $code (keys(%{$instcodes})) {
                   8531:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8532:     }
                   8533:     chop($courses);
1.772     raeburn  8534:     my $ok_response = 0;
                   8535:     my $response;
                   8536:     while (@homeservers > 0 && $ok_response == 0) {
                   8537:         my $server = shift(@homeservers); 
                   8538:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8539:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8540:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8541: 		split(/:/,$response);
1.772     raeburn  8542:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8543:             push(@{$codetitles},&str2array($codetitles_str));
                   8544:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8545:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8546:             $ok_response = 1;
                   8547:         }
                   8548:     }
                   8549:     if ($ok_response) {
1.521     raeburn  8550:         return 'ok';
1.772     raeburn  8551:     } else {
                   8552:         return $response;
1.521     raeburn  8553:     }
                   8554: }
                   8555: 
1.792     raeburn  8556: sub auto_instcode_defaults {
                   8557:     my ($domain,$returnhash,$code_order) = @_;
                   8558:     my @homeservers;
1.841     albertel 8559: 
                   8560:     my %servers = &get_servers($domain,'library');
                   8561:     foreach my $tryserver (keys(%servers)) {
                   8562: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8563: 	    push(@homeservers,$tryserver);
                   8564: 	}
1.792     raeburn  8565:     }
1.841     albertel 8566: 
1.792     raeburn  8567:     my $response;
1.841     albertel 8568:     foreach my $server (@homeservers) {
1.792     raeburn  8569:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8570:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8571: 	
                   8572: 	foreach my $pair (split(/\&/,$response)) {
                   8573: 	    my ($name,$value)=split(/\=/,$pair);
                   8574: 	    if ($name eq 'code_order') {
                   8575: 		@{$code_order} = split(/\&/,&unescape($value));
                   8576: 	    } else {
                   8577: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8578: 	    }
                   8579: 	}
                   8580: 	return 'ok';
1.792     raeburn  8581:     }
1.841     albertel 8582: 
                   8583:     return $response;
1.1003    raeburn  8584: }
                   8585: 
                   8586: sub auto_possible_instcodes {
1.1007    raeburn  8587:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8588:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8589:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8590:         return;
                   8591:     }
1.1003    raeburn  8592:     my (@homeservers,$uhome);
                   8593:     if (defined(&domain($domain,'primary'))) {
                   8594:         $uhome=&domain($domain,'primary');
                   8595:         push(@homeservers,&domain($domain,'primary'));
                   8596:     } else {
                   8597:         my %servers = &get_servers($domain,'library');
                   8598:         foreach my $tryserver (keys(%servers)) {
                   8599:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8600:                 push(@homeservers,$tryserver);
                   8601:             }
                   8602:         }
                   8603:     }
                   8604:     my $response;
                   8605:     foreach my $server (@homeservers) {
                   8606:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8607:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8608:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8609:             split(':',$response);
                   8610:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8611:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8612:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8613:             my ($name,$value)=split('=',$item);
                   8614:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8615:         }
                   8616:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8617:             my ($name,$value)=split('=',$item);
                   8618:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8619:         }
                   8620:         return 'ok';
                   8621:     }
                   8622:     return $response;
                   8623: }
1.792     raeburn  8624: 
1.1010    raeburn  8625: sub auto_courserequest_checks {
                   8626:     my ($dom) = @_;
1.1020    raeburn  8627:     my ($homeserver,%validations);
                   8628:     if ($dom =~ /^$match_domain$/) {
                   8629:         $homeserver = &domain($dom,'primary');
                   8630:     }
                   8631:     unless ($homeserver eq 'no_host') {
                   8632:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8633:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8634:             my @items = split(/&/,$response);
                   8635:             foreach my $item (@items) {
                   8636:                 my ($key,$value) = split('=',$item);
                   8637:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8638:             }
                   8639:         }
                   8640:     }
1.1010    raeburn  8641:     return %validations; 
                   8642: }
                   8643: 
1.1020    raeburn  8644: sub auto_courserequest_validation {
1.1255    raeburn  8645:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8646:     my ($homeserver,$response);
                   8647:     if ($dom =~ /^$match_domain$/) {
                   8648:         $homeserver = &domain($dom,'primary');
                   8649:     }
1.1255    raeburn  8650:     unless ($homeserver eq 'no_host') {
                   8651:         my $customdata;
                   8652:         if (ref($custominfo) eq 'HASH') {
                   8653:             $customdata = &freeze_escape($custominfo);
                   8654:         }
1.1020    raeburn  8655:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8656:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8657:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8658:                                     $customdata,$homeserver));
1.1020    raeburn  8659:     }
                   8660:     return $response;
                   8661: }
                   8662: 
1.777     albertel 8663: sub auto_validate_class_sec {
1.918     raeburn  8664:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8665:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8666:     my $ownerlist;
                   8667:     if (ref($owners) eq 'ARRAY') {
                   8668:         $ownerlist = join(',',@{$owners});
                   8669:     } else {
                   8670:         $ownerlist = $owners;
                   8671:     }
1.773     raeburn  8672:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8673:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8674:     return $response;
                   8675: }
                   8676: 
1.1248    raeburn  8677: sub auto_crsreq_update {
                   8678:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8679:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8680:     my ($homeserver,%crsreqresponse);
                   8681:     if ($cdom =~ /^$match_domain$/) {
                   8682:         $homeserver = &domain($cdom,'primary');
                   8683:     }
                   8684:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8685:         my $info;
                   8686:         if (ref($inbound) eq 'HASH') {
                   8687:             $info = &freeze_escape($inbound);
                   8688:         }
                   8689:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8690:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8691:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8692:                             &escape($title).':'.&escape($code).':'.
                   8693:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8694:                             $homeserver);
1.1248    raeburn  8695:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8696:             my @items = split(/&/,$response);
                   8697:             foreach my $item (@items) {
                   8698:                 my ($key,$value) = split('=',$item);
                   8699:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8700:             }
                   8701:         }
                   8702:     }
                   8703:     return \%crsreqresponse;
                   8704: }
                   8705: 
1.1305    raeburn  8706: sub auto_export_grades {
1.1309    raeburn  8707:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8708:     my ($homeserver,%exportresponse);
                   8709:     if ($cdom =~ /^$match_domain$/) {
                   8710:         $homeserver = &domain($cdom,'primary');
                   8711:     }
                   8712:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8713:         my $info;
                   8714:         if (ref($inforef) eq 'HASH') {
                   8715:             $info = &freeze_escape($inforef);
                   8716:         }
                   8717:         if (ref($gradesref) eq 'HASH') {
                   8718:             my $grades = &freeze_escape($gradesref);
                   8719:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8720:                                 $info.':'.$grades,$homeserver);
                   8721:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8722:                 my @items = split(/&/,$response);
                   8723:                 foreach my $item (@items) {
                   8724:                     my ($key,$value) = split('=',$item);
                   8725:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8726:                 }
                   8727:             }
                   8728:         }
                   8729:     }
                   8730:     return \%exportresponse;
1.1305    raeburn  8731: }
                   8732: 
1.1287    raeburn  8733: sub check_instcode_cloning {
                   8734:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8735:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8736:         return;
                   8737:     }
                   8738:     my $canclone;
                   8739:     if (@{$code_order} > 0) {
                   8740:         my $instcoderegexp ='^';
                   8741:         my @clonecodes = split(/\&/,$cloner);
                   8742:         foreach my $item (@{$code_order}) {
                   8743:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8744:                 foreach my $pair (@clonecodes) {
                   8745:                     my ($key,$val) = split(/\=/,$pair,2);
                   8746:                     $val = &unescape($val);
                   8747:                     if ($key eq $item) {
                   8748:                         $instcoderegexp .= '('.$val.')';
                   8749:                         last;
                   8750:                     }
                   8751:                 }
                   8752:             } else {
                   8753:                 $instcoderegexp .= $codedefaults->{$item};
                   8754:             }
                   8755:         }
                   8756:         $instcoderegexp .= '$';
                   8757:         my (@from,@to);
                   8758:         eval {
                   8759:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8760:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8761:         };
                   8762:         if ((@from > 0) && (@to > 0)) {
                   8763:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8764:             if (!@diffs) {
                   8765:                 $canclone = 1;
                   8766:             }
                   8767:         }
                   8768:     }
                   8769:     return $canclone;
                   8770: }
                   8771: 
                   8772: sub default_instcode_cloning {
                   8773:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8774:     my (%codedefaults,@code_order,$canclone);
                   8775:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8776:         %codedefaults = %{$codedefaultsref};
                   8777:         @code_order = @{$codeorderref};
                   8778:     } elsif ($clonedom) {
                   8779:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8780:     }
                   8781:     if (($domdefclone) && (@code_order)) {
                   8782:         my @clonecodes = split(/\+/,$domdefclone);
                   8783:         my $instcoderegexp ='^';
                   8784:         foreach my $item (@code_order) {
                   8785:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8786:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8787:             } else {
                   8788:                 $instcoderegexp .= $codedefaults{$item};
                   8789:             }
                   8790:         }
                   8791:         $instcoderegexp .= '$';
                   8792:         my (@from,@to);
                   8793:         eval {
                   8794:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8795:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8796:         };
                   8797:         if ((@from > 0) && (@to > 0)) {
                   8798:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8799:             if (!@diffs) {
                   8800:                 $canclone = 1;
                   8801:             }
                   8802:         }
                   8803:     }
                   8804:     return $canclone;
                   8805: }
                   8806: 
1.679     raeburn  8807: # ------------------------------------------------------- Course Group routines
                   8808: 
                   8809: sub get_coursegroups {
1.809     raeburn  8810:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8811:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8812: }
                   8813: 
1.679     raeburn  8814: sub modify_coursegroup {
                   8815:     my ($cdom,$cnum,$groupsettings) = @_;
                   8816:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8817: }
                   8818: 
1.809     raeburn  8819: sub toggle_coursegroup_status {
                   8820:     my ($cdom,$cnum,$group,$action) = @_;
                   8821:     my ($from_namespace,$to_namespace);
                   8822:     if ($action eq 'delete') {
                   8823:         $from_namespace = 'coursegroups';
                   8824:         $to_namespace = 'deleted_groups';
                   8825:     } else {
                   8826:         $from_namespace = 'deleted_groups';
                   8827:         $to_namespace = 'coursegroups';
                   8828:     }
                   8829:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8830:     if (my $tmp = &error(%curr_group)) {
                   8831:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8832:         return ('read error',$tmp);
                   8833:     } else {
                   8834:         my %savedsettings = %curr_group; 
1.809     raeburn  8835:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8836:         my $deloutcome;
                   8837:         if ($result eq 'ok') {
1.809     raeburn  8838:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8839:         } else {
                   8840:             return ('write error',$result);
                   8841:         }
                   8842:         if ($deloutcome eq 'ok') {
                   8843:             return 'ok';
                   8844:         } else {
                   8845:             return ('delete error',$deloutcome);
                   8846:         }
                   8847:     }
                   8848: }
                   8849: 
1.679     raeburn  8850: sub modify_group_roles {
1.957     raeburn  8851:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8852:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8853:     my $role = 'gr/'.&escape($userprivs);
                   8854:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8855:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8856:     if ($result eq 'ok') {
                   8857:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8858:     }
1.679     raeburn  8859:     return $result;
                   8860: }
                   8861: 
                   8862: sub modify_coursegroup_membership {
                   8863:     my ($cdom,$cnum,$membership) = @_;
                   8864:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8865:     return $result;
                   8866: }
                   8867: 
1.682     raeburn  8868: sub get_active_groups {
                   8869:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8870:     my $now = time;
                   8871:     my %groups = ();
                   8872:     foreach my $key (keys(%env)) {
1.811     albertel 8873:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8874:             my ($start,$end) = split(/\./,$env{$key});
                   8875:             if (($end!=0) && ($end<$now)) { next; }
                   8876:             if (($start!=0) && ($start>$now)) { next; }
                   8877:             if ($1 eq $cdom && $2 eq $cnum) {
                   8878:                 $groups{$3} = $env{$key} ;
                   8879:             }
                   8880:         }
                   8881:     }
                   8882:     return %groups;
                   8883: }
                   8884: 
1.683     raeburn  8885: sub get_group_membership {
                   8886:     my ($cdom,$cnum,$group) = @_;
                   8887:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8888: }
                   8889: 
                   8890: sub get_users_groups {
                   8891:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8892:     my @usersgroups;
1.683     raeburn  8893:     my $cachetime=1800;
                   8894: 
                   8895:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8896:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8897:     if (defined($cached)) {
1.734     albertel 8898:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8899:     } else {  
                   8900:         $grouplist = '';
1.816     raeburn  8901:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8902:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8903:         my $access_end = $env{'course.'.$courseid.
                   8904:                               '.default_enrollment_end_date'};
                   8905:         my $now = time;
                   8906:         foreach my $key (keys(%roleshash)) {
                   8907:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8908:                 my $group = $1;
                   8909:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8910:                     my $start = $2;
                   8911:                     my $end = $1;
                   8912:                     if ($start == -1) { next; } # deleted from group
                   8913:                     if (($start!=0) && ($start>$now)) { next; }
                   8914:                     if (($end!=0) && ($end<$now)) {
                   8915:                         if ($access_end && $access_end < $now) {
                   8916:                             if ($access_end - $end < 86400) {
                   8917:                                 push(@usersgroups,$group);
1.733     raeburn  8918:                             }
                   8919:                         }
1.817     raeburn  8920:                         next;
1.733     raeburn  8921:                     }
1.817     raeburn  8922:                     push(@usersgroups,$group);
1.683     raeburn  8923:                 }
                   8924:             }
                   8925:         }
1.817     raeburn  8926:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8927:         $grouplist = join(':',@usersgroups);
                   8928:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8929:     }
1.733     raeburn  8930:     return @usersgroups;
1.683     raeburn  8931: }
                   8932: 
                   8933: sub devalidate_getgroups_cache {
                   8934:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8935:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8936: 
1.683     raeburn  8937:     my $hashid="$udom:$uname:$courseid";
                   8938:     &devalidate_cache_new('getgroups',$hashid);
                   8939: }
                   8940: 
1.12      www      8941: # ------------------------------------------------------------------ Plain Text
                   8942: 
                   8943: sub plaintext {
1.988     raeburn  8944:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8945:     if ($short =~ m{^cr/}) {
1.758     albertel 8946: 	return (split('/',$short))[-1];
                   8947:     }
1.742     raeburn  8948:     if (!defined($cid)) {
                   8949:         $cid = $env{'request.course.id'};
                   8950:     }
                   8951:     my %rolenames = (
1.1008    raeburn  8952:                       Course    => 'std',
                   8953:                       Community => 'alt1',
1.1305    raeburn  8954:                       Placement => 'std',
1.742     raeburn  8955:                     );
1.1037    raeburn  8956:     if ($cid ne '') {
                   8957:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8958:             unless ($forcedefault) {
                   8959:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8960:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8961:                 return &Apache::lonlocal::mt($roletext);
                   8962:             }
                   8963:         }
                   8964:     }
                   8965:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8966:         (defined($rolenames{$type})) && 
                   8967:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8968:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8969:     } elsif ($cid ne '') {
                   8970:         my $crstype = $env{'course.'.$cid.'.type'};
                   8971:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8972:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8973:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8974:         }
1.742     raeburn  8975:     }
1.1037    raeburn  8976:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8977: }
                   8978: 
                   8979: # ----------------------------------------------------------------- Assign Role
                   8980: 
                   8981: sub assignrole {
1.957     raeburn  8982:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8983:         $context)=@_;
1.21      www      8984:     my $mrole;
                   8985:     if ($role =~ /^cr\//) {
1.393     www      8986:         my $cwosec=$url;
1.811     albertel 8987:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8988: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8989:            my $refused = 1;
                   8990:            if ($context eq 'requestcourses') {
                   8991:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8992:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8993:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8994:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8995:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8996:                            if ($crsenv{'internal.courseowner'} eq
                   8997:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8998:                                $refused = '';
                   8999:                            }
                   9000:                        }
                   9001:                    }
                   9002:                }
                   9003:            }
                   9004:            if ($refused) {
                   9005:                &logthis('Refused custom assignrole: '.
                   9006:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9007:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9008:                return 'refused';
                   9009:            }
1.104     www      9010:         }
1.21      www      9011:         $mrole='cr';
1.678     raeburn  9012:     } elsif ($role =~ /^gr\//) {
                   9013:         my $cwogrp=$url;
1.811     albertel 9014:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9015:         unless (&allowed('mdg',$cwogrp)) {
                   9016:             &logthis('Refused group assignrole: '.
                   9017:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9018:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9019:             return 'refused';
                   9020:         }
                   9021:         $mrole='gr';
1.21      www      9022:     } else {
1.82      www      9023:         my $cwosec=$url;
1.811     albertel 9024:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9025:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9026:             my $refused;
                   9027:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9028:                 if (!(&allowed('c'.$role,$url))) {
                   9029:                     $refused = 1;
                   9030:                 }
                   9031:             } else {
                   9032:                 $refused = 1;
                   9033:             }
1.947     raeburn  9034:             if ($refused) {
1.1045    raeburn  9035:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9036:                 if (!$selfenroll && $context eq 'course') {
                   9037:                     my %crsenv;
                   9038:                     if ($role eq 'cc' || $role eq 'co') {
                   9039:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9040:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9041:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9042:                                 if ($crsenv{'internal.courseowner'} eq 
                   9043:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9044:                                     $refused = '';
                   9045:                                 }
                   9046:                             }
                   9047:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9048:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9049:                                 if ($crsenv{'internal.courseowner'} eq 
                   9050:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9051:                                     $refused = '';
                   9052:                                 }
                   9053:                             }
                   9054:                         }
                   9055:                     }
                   9056:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9057:                     $refused = '';
1.1017    raeburn  9058:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9059:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9060:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9061:                         my $wrongcc;
                   9062:                         if ($cnum =~ /^$match_community$/) {
                   9063:                             $wrongcc = 1 if ($role eq 'cc');
                   9064:                         } else {
                   9065:                             $wrongcc = 1 if ($role eq 'co');
                   9066:                         }
                   9067:                         unless ($wrongcc) {
                   9068:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9069:                             if ($crsenv{'internal.courseowner'} eq 
                   9070:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9071:                                 $refused = '';
                   9072:                             }
1.1017    raeburn  9073:                         }
                   9074:                     }
1.1183    raeburn  9075:                 } elsif ($context eq 'requestauthor') {
                   9076:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9077:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9078:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9079:                             $refused = '';
                   9080:                         } else {
                   9081:                             my %domdefaults = &get_domain_defaults($udom);
                   9082:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9083:                                 my $checkbystatus;
                   9084:                                 if ($env{'user.adv'}) { 
                   9085:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9086:                                     if ($disposition eq 'automatic') {
                   9087:                                         $refused = '';
                   9088:                                     } elsif ($disposition eq '') {
                   9089:                                         $checkbystatus = 1;
                   9090:                                     } 
                   9091:                                 } else {
                   9092:                                     $checkbystatus = 1;
                   9093:                                 }
                   9094:                                 if ($checkbystatus) {
                   9095:                                     if ($env{'environment.inststatus'}) {
                   9096:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9097:                                         foreach my $type (@inststatuses) {
                   9098:                                             if (($type ne '') &&
                   9099:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9100:                                                 $refused = '';
                   9101:                                             }
                   9102:                                         }
                   9103:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9104:                                         $refused = '';
                   9105:                                     }
                   9106:                                 }
                   9107:                             }
                   9108:                         }
                   9109:                     }
1.1017    raeburn  9110:                 }
                   9111:                 if ($refused) {
1.947     raeburn  9112:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9113:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9114: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9115:                     return 'refused';
                   9116:                 }
1.932     raeburn  9117:             }
1.1131    raeburn  9118:         } elsif ($role eq 'au') {
                   9119:             if ($url ne '/'.$udom.'/') {
                   9120:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9121:                          ' to assign author role for '.$uname.':'.$udom.
                   9122:                          ' in domain: '.$url.' refused (wrong domain).');
                   9123:                 return 'refused';
                   9124:             }
1.104     www      9125:         }
1.21      www      9126:         $mrole=$role;
                   9127:     }
1.620     albertel 9128:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9129:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9130:     if ($end) { $command.='_'.$end; }
1.21      www      9131:     if ($start) {
                   9132: 	if ($end) { 
1.81      www      9133:            $command.='_'.$start; 
1.21      www      9134:         } else {
1.81      www      9135:            $command.='_0_'.$start;
1.21      www      9136:         }
                   9137:     }
1.739     raeburn  9138:     my $origstart = $start;
                   9139:     my $origend = $end;
1.957     raeburn  9140:     my $delflag;
1.357     www      9141: # actually delete
                   9142:     if ($deleteflag) {
1.373     www      9143: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9144: # modify command to delete the role
1.620     albertel 9145:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9146:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9147: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9148: # set start and finish to negative values for userrolelog
                   9149:            $start=-1;
                   9150:            $end=-1;
1.957     raeburn  9151:            $delflag = 1;
1.357     www      9152:         }
                   9153:     }
                   9154: # send command
1.349     www      9155:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9156: # log new user role if status is ok
1.349     www      9157:     if ($answer eq 'ok') {
1.663     raeburn  9158: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9159:         if (($role eq 'cc') || ($role eq 'in') ||
                   9160:             ($role eq 'ep') || ($role eq 'ad') ||
                   9161:             ($role eq 'ta') || ($role eq 'st') ||
                   9162:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9163:             ($role eq 'co')) {
1.1200    raeburn  9164: # for course roles, perform group memberships changes triggered by role change.
                   9165:             unless ($role =~ /^gr/) {
                   9166:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9167:                                                  $origstart,$selfenroll,$context);
                   9168:             }
1.1184    raeburn  9169:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9170:                            $selfenroll,$context);
                   9171:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9172:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9173:                  ($role eq 'da')) {
1.1184    raeburn  9174:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9175:                            $context);
                   9176:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9177:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9178:                              $context); 
                   9179:         }
1.1053    raeburn  9180:         if ($role eq 'cc') {
                   9181:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9182:         }
1.349     www      9183:     }
                   9184:     return $answer;
1.169     harris41 9185: }
                   9186: 
1.1053    raeburn  9187: sub autoupdate_coowners {
                   9188:     my ($url,$end,$start,$uname,$udom) = @_;
                   9189:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9190:     if (($cdom ne '') && ($cnum ne '')) {
                   9191:         my $now = time;
                   9192:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9193:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9194:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9195:             my $instcode = $coursehash{'internal.coursecode'};
                   9196:             if ($instcode ne '') {
1.1056    raeburn  9197:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9198:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9199:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9200:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9201:                         if ($result eq 'valid') {
                   9202:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9203:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9204:                                     push(@newcoowners,$coowner);
                   9205:                                 }
                   9206:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9207:                                     push(@newcoowners,$uname.':'.$udom);
                   9208:                                 }
                   9209:                                 @newcoowners = sort(@newcoowners);
                   9210:                             } else {
                   9211:                                 push(@newcoowners,$uname.':'.$udom);
                   9212:                             }
                   9213:                         } else {
                   9214:                             if ($coursehash{'internal.co-owners'}) {
                   9215:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9216:                                     unless ($coowner eq $uname.':'.$udom) {
                   9217:                                         push(@newcoowners,$coowner);
                   9218:                                     }
                   9219:                                 }
                   9220:                                 unless (@newcoowners > 0) {
                   9221:                                     $delcoowners = 1;
                   9222:                                     $coowners = '';
                   9223:                                 }
                   9224:                             }
                   9225:                         }
                   9226:                         if (@newcoowners || $delcoowners) {
                   9227:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9228:                                             $delcoowners,@newcoowners);
                   9229:                         }
                   9230:                     }
                   9231:                 }
                   9232:             }
                   9233:         }
                   9234:     }
                   9235: }
                   9236: 
                   9237: sub store_coowners {
                   9238:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9239:     my $cid = $cdom.'_'.$cnum;
                   9240:     my ($coowners,$delresult,$putresult);
                   9241:     if (@newcoowners) {
                   9242:         $coowners = join(',',@newcoowners);
                   9243:         my %coownershash = (
                   9244:                             'internal.co-owners' => $coowners,
                   9245:                            );
                   9246:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9247:         if ($putresult eq 'ok') {
                   9248:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9249:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9250:             }
                   9251:         }
                   9252:     }
                   9253:     if ($delcoowners) {
                   9254:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9255:         if ($delresult eq 'ok') {
                   9256:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9257:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9258:             }
                   9259:         }
                   9260:     }
                   9261:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9262:         my %crsinfo =
                   9263:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9264:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9265:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9266:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9267:         }
                   9268:     }
                   9269: }
                   9270: 
1.169     harris41 9271: # -------------------------------------------------- Modify user authentication
1.197     www      9272: # Overrides without validation
                   9273: 
1.169     harris41 9274: sub modifyuserauth {
                   9275:     my ($udom,$uname,$umode,$upass)=@_;
                   9276:     my $uhome=&homeserver($uname,$udom);
1.197     www      9277:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9278:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9279:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9280:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9281:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9282: 		     &escape($upass),$uhome);
1.620     albertel 9283:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9284:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9285:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9286:     &log($udom,,$uname,$uhome,
1.620     albertel 9287:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9288:                                      $env{'user.name'}.', '.$umode.
1.197     www      9289:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9290:     unless ($reply eq 'ok') {
1.197     www      9291:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9292: 	return 'error: '.$reply;
                   9293:     }   
1.170     harris41 9294:     return 'ok';
1.80      www      9295: }
                   9296: 
1.81      www      9297: # --------------------------------------------------------------- Modify a user
1.80      www      9298: 
1.81      www      9299: sub modifyuser {
1.206     matthew  9300:     my ($udom,    $uname, $uid,
                   9301:         $umode,   $upass, $first,
                   9302:         $middle,  $last,  $gene,
1.1058    raeburn  9303:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9304:     $udom= &LONCAPA::clean_domain($udom);
                   9305:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9306:     my $showcandelete = 'none';
                   9307:     if (ref($candelete) eq 'ARRAY') {
                   9308:         if (@{$candelete} > 0) {
                   9309:             $showcandelete = join(', ',@{$candelete});
                   9310:         }
                   9311:     }
1.81      www      9312:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9313:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9314: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9315:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9316:                                      ' desiredhome not specified'). 
1.620     albertel 9317:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9318:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9319:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9320:     my $newuser;
                   9321:     if ($uhome eq 'no_host') {
                   9322:         $newuser = 1;
                   9323:     }
1.80      www      9324: # ----------------------------------------------------------------- Create User
1.406     albertel 9325:     if (($uhome eq 'no_host') && 
                   9326: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9327:         my $unhome='';
1.844     albertel 9328:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9329:             $unhome = $desiredhome;
1.620     albertel 9330: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9331: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9332:         } else { # load balancing routine for determining $unhome
1.81      www      9333:             my $loadm=10000000;
1.841     albertel 9334: 	    my %servers = &get_servers($udom,'library');
                   9335: 	    foreach my $tryserver (keys(%servers)) {
                   9336: 		my $answer=reply('load',$tryserver);
                   9337: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9338: 		    $loadm=$answer;
                   9339: 		    $unhome=$tryserver;
                   9340: 		}
1.80      www      9341: 	    }
                   9342:         }
                   9343:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9344: 	    return 'error: unable to find a home server for '.$uname.
                   9345:                    ' in domain '.$udom;
1.80      www      9346:         }
                   9347:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9348:                          &escape($upass),$unhome);
                   9349: 	unless ($reply eq 'ok') {
                   9350:             return 'error: '.$reply;
                   9351:         }   
1.230     stredwic 9352:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9353:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9354: 	    return 'error: unable verify users home machine.';
1.80      www      9355:         }
1.209     matthew  9356:     }   # End of creation of new user
1.80      www      9357: # ---------------------------------------------------------------------- Add ID
                   9358:     if ($uid) {
                   9359:        $uid=~tr/A-Z/a-z/;
                   9360:        my %uidhash=&idrget($udom,$uname);
1.196     www      9361:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9362:          && (!$forceid)) {
1.80      www      9363: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9364: 	      return 'error: user id "'.$uid.'" does not match '.
                   9365:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9366:           }
                   9367:        } else {
1.1300    raeburn  9368: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9369:        }
                   9370:     }
                   9371: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9372:     my @tmp=&get('environment',
1.899     raeburn  9373: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9374:                     'permanentemail','inststatus'],
1.134     albertel 9375: 		   $udom,$uname);
1.1075    raeburn  9376:     my (%names,%oldnames);
1.313     matthew  9377:     if ($tmp[0] =~ m/^error:.*/) { 
                   9378:         %names=(); 
                   9379:     } else {
                   9380:         %names = @tmp;
1.1075    raeburn  9381:         %oldnames = %names;
1.313     matthew  9382:     }
1.388     www      9383: #
1.1058    raeburn  9384: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9385: # of users did not contain them), do not overwrite existing values
                   9386: # unless field is in $candelete array ref.  
                   9387: #
                   9388: 
                   9389:     my @fields = ('firstname','middlename','lastname','generation',
                   9390:                   'permanentemail','id');
                   9391:     my %newvalues;
                   9392:     if (ref($candelete) eq 'ARRAY') {
                   9393:         foreach my $field (@fields) {
                   9394:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9395:                 if ($field eq 'firstname') {
                   9396:                     $names{$field} = $first;
                   9397:                 } elsif ($field eq 'middlename') {
                   9398:                     $names{$field} = $middle;
                   9399:                 } elsif ($field eq 'lastname') {
                   9400:                     $names{$field} = $last;
                   9401:                 } elsif ($field eq 'generation') { 
                   9402:                     $names{$field} = $gene;
                   9403:                 } elsif ($field eq 'permanentemail') {
                   9404:                     $names{$field} = $email;
                   9405:                 } elsif ($field eq 'id') {
                   9406:                     $names{$field}  = $uid;
                   9407:                 }
                   9408:             }
                   9409:         }
                   9410:     }
1.388     www      9411:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9412:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9413:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9414:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9415:     if ($email) {
                   9416:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9417:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9418:     }
1.899     raeburn  9419:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9420:     if (defined($inststatus)) {
                   9421:         $names{'inststatus'} = '';
                   9422:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9423:         if (ref($usertypes) eq 'HASH') {
                   9424:             my @okstatuses; 
                   9425:             foreach my $item (split(/:/,$inststatus)) {
                   9426:                 if (defined($usertypes->{$item})) {
                   9427:                     push(@okstatuses,$item);  
                   9428:                 }
                   9429:             }
                   9430:             if (@okstatuses) {
                   9431:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9432:             }
                   9433:         }
                   9434:     }
1.1075    raeburn  9435:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9436:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9437:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9438:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9439:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9440:     } else {
                   9441:         $logmsg .= ' during self creation';
                   9442:     }
1.1075    raeburn  9443:     my $changed;
                   9444:     if ($newuser) {
                   9445:         $changed = 1;
                   9446:     } else {
                   9447:         foreach my $field (@fields) {
                   9448:             if ($names{$field} ne $oldnames{$field}) {
                   9449:                 $changed = 1;
                   9450:                 last;
                   9451:             }
                   9452:         }
                   9453:     }
                   9454:     unless ($changed) {
                   9455:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9456:         &logthis($logmsg);
                   9457:         return 'ok';
                   9458:     }
                   9459:     my $reply = &put('environment', \%names, $udom,$uname);
                   9460:     if ($reply ne 'ok') { 
                   9461:         return 'error: '.$reply;
                   9462:     }
1.1087    raeburn  9463:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9464:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9465:     }
1.1075    raeburn  9466:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9467:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9468:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9469:     &logthis($logmsg);
1.134     albertel 9470:     return 'ok';
1.80      www      9471: }
                   9472: 
1.81      www      9473: # -------------------------------------------------------------- Modify student
1.80      www      9474: 
1.81      www      9475: sub modifystudent {
                   9476:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9477:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9478:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9479:     if (!$cid) {
1.620     albertel 9480: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9481: 	    return 'not_in_class';
                   9482: 	}
1.80      www      9483:     }
                   9484: # --------------------------------------------------------------- Make the user
1.81      www      9485:     my $reply=&modifyuser
1.209     matthew  9486: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9487:          $desiredhome,$email,$inststatus);
1.80      www      9488:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9489:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9490:     # student's environment
1.297     matthew  9491:     $uid = undef if (!$forceid);
1.455     albertel 9492:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9493:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9494:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9495:     return $reply;
                   9496: }
                   9497: 
                   9498: sub modify_student_enrollment {
1.1216    raeburn  9499:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9500:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9501:     my ($cdom,$cnum,$chome);
                   9502:     if (!$cid) {
1.620     albertel 9503: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9504: 	    return 'not_in_class';
                   9505: 	}
1.620     albertel 9506: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9507: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9508:     } else {
                   9509: 	($cdom,$cnum)=split(/_/,$cid);
                   9510:     }
1.620     albertel 9511:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9512:     if (!$chome) {
1.457     raeburn  9513: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9514:     }
1.455     albertel 9515:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9516:     # Make sure the user exists
1.81      www      9517:     my $uhome=&homeserver($uname,$udom);
                   9518:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9519: 	return 'error: no such user';
                   9520:     }
1.297     matthew  9521:     # Get student data if we were not given enough information
                   9522:     if (!defined($first)  || $first  eq '' || 
                   9523:         !defined($last)   || $last   eq '' || 
                   9524:         !defined($uid)    || $uid    eq '' || 
                   9525:         !defined($middle) || $middle eq '' || 
                   9526:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9527:         # They did not supply us with enough data to enroll the student, so
                   9528:         # we need to pick up more information.
1.297     matthew  9529:         my %tmp = &get('environment',
1.294     matthew  9530:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9531:                        ,$udom,$uname);
                   9532: 
1.800     albertel 9533:         #foreach my $key (keys(%tmp)) {
                   9534:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9535:         #}
1.294     matthew  9536:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9537:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9538:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9539:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9540:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9541:     }
1.556     albertel 9542:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9543:     my $user = "$uname:$udom";
                   9544:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9545:     my $reply=cput('classlist',
1.1148    raeburn  9546: 		   {$user => 
1.1314    raeburn  9547: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9548: 		   $cdom,$cnum);
1.1148    raeburn  9549:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9550:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9551:     } else { 
1.81      www      9552: 	return 'error: '.$reply;
                   9553:     }
1.297     matthew  9554:     # Add student role to user
1.83      www      9555:     my $uurl='/'.$cid;
1.81      www      9556:     $uurl=~s/\_/\//g;
                   9557:     if ($usec) {
                   9558: 	$uurl.='/'.$usec;
                   9559:     }
1.1148    raeburn  9560:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9561:                              $selfenroll,$context);
                   9562:     if ($result ne 'ok') {
                   9563:         if ($old_entry{$user} ne '') {
                   9564:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9565:         } else {
                   9566:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9567:         }
                   9568:     }
                   9569:     return $result; 
1.21      www      9570: }
                   9571: 
1.556     albertel 9572: sub format_name {
                   9573:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9574:     my $name;
                   9575:     if ($first ne 'lastname') {
                   9576: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9577:     } else {
                   9578: 	if ($lastname=~/\S/) {
                   9579: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9580: 	    $name=~s/\s+,/,/;
                   9581: 	} else {
                   9582: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9583: 	}
                   9584:     }
                   9585:     $name=~s/^\s+//;
                   9586:     $name=~s/\s+$//;
                   9587:     $name=~s/\s+/ /g;
                   9588:     return $name;
                   9589: }
                   9590: 
1.84      www      9591: # ------------------------------------------------- Write to course preferences
                   9592: 
                   9593: sub writecoursepref {
                   9594:     my ($courseid,%prefs)=@_;
                   9595:     $courseid=~s/^\///;
                   9596:     $courseid=~s/\_/\//g;
                   9597:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9598:     my $chome=homeserver($cnum,$cdomain);
                   9599:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9600: 	return 'error: no such course';
                   9601:     }
                   9602:     my $cstring='';
1.800     albertel 9603:     foreach my $pref (keys(%prefs)) {
                   9604: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9605:     }
1.84      www      9606:     $cstring=~s/\&$//;
                   9607:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9608: }
                   9609: 
                   9610: # ---------------------------------------------------------- Make/modify course
                   9611: 
                   9612: sub createcourse {
1.741     raeburn  9613:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9614:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9615:     $url=&declutter($url);
                   9616:     my $cid='';
1.1028    raeburn  9617:     if ($context eq 'requestcourses') {
                   9618:         my $can_create = 0;
                   9619:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9620:         if ($udom eq $ownerdom) {
                   9621:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9622:                                   $context)) {
                   9623:                 $can_create = 1;
                   9624:             }
                   9625:         } else {
                   9626:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9627:                                            $category);
                   9628:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9629:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9630:                 if (@curr > 0) {
                   9631:                     my @options = qw(approval validate autolimit);
                   9632:                     my $optregex = join('|',@options);
                   9633:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9634:                         $can_create = 1;
                   9635:                     }
                   9636:                 }
                   9637:             }
                   9638:         }
                   9639:         if ($can_create) {
                   9640:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9641:                 unless (&allowed('ccc',$udom)) {
                   9642:                     return 'refused'; 
                   9643:                 }
1.1017    raeburn  9644:             }
                   9645:         } else {
                   9646:             return 'refused';
                   9647:         }
1.1028    raeburn  9648:     } elsif (!&allowed('ccc',$udom)) {
                   9649:         return 'refused';
1.84      www      9650:     }
1.1011    raeburn  9651: # --------------------------------------------------------------- Get Unique ID
                   9652:     my $uname;
                   9653:     if ($cnum =~ /^$match_courseid$/) {
                   9654:         my $chome=&homeserver($cnum,$udom,'true');
                   9655:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9656:             $uname = $cnum;
                   9657:         } else {
1.1038    raeburn  9658:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9659:         }
                   9660:     } else {
1.1038    raeburn  9661:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9662:     }
                   9663:     return $uname if ($uname =~ /^error/);
                   9664: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9665:     if (!defined($course_server)) {
                   9666:         if (defined(&domain($udom,'primary'))) {
                   9667:             $course_server = &domain($udom,'primary');
                   9668:         } else {
                   9669:             $course_server = $env{'user.home'}; 
                   9670:         }
                   9671:     }
                   9672:     my %host_servers =
                   9673:         &Apache::lonnet::get_servers($udom,'library');
                   9674:     unless ($host_servers{$course_server}) {
                   9675:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9676:     }
1.84      www      9677: # ------------------------------------------------------------- Make the course
                   9678:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9679:                       $course_server);
1.84      www      9680:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9681:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9682:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9683: 	return 'error: no such course';
                   9684:     }
1.271     www      9685: # ----------------------------------------------------------------- Course made
1.516     raeburn  9686: # log existence
1.1029    raeburn  9687:     my $now = time;
1.918     raeburn  9688:     my $newcourse = {
                   9689:                     $udom.'_'.$uname => {
1.921     raeburn  9690:                                      description => $description,
                   9691:                                      inst_code   => $inst_code,
                   9692:                                      owner       => $course_owner,
                   9693:                                      type        => $crstype,
1.1029    raeburn  9694:                                      creator     => $env{'user.name'}.':'.
                   9695:                                                     $env{'user.domain'},
                   9696:                                      created     => $now,
                   9697:                                      context     => $context,
1.918     raeburn  9698:                                                 },
                   9699:                     };
1.921     raeburn  9700:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9701: # set toplevel url
1.271     www      9702:     my $topurl=$url;
                   9703:     unless ($nonstandard) {
                   9704: # ------------------------------------------ For standard courses, make top url
                   9705:         my $mapurl=&clutter($url);
1.278     www      9706:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9707:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9708: <map>
                   9709: <resource id="1" type="start"></resource>
                   9710: <resource id="2" src="$mapurl"></resource>
                   9711: <resource id="3" type="finish"></resource>
                   9712: <link index="1" from="1" to="2"></link>
                   9713: <link index="2" from="2" to="3"></link>
                   9714: </map>
                   9715: ENDINITMAP
                   9716:         $topurl=&declutter(
1.638     albertel 9717:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9718:                           );
                   9719:     }
                   9720: # ----------------------------------------------------------- Write preferences
1.84      www      9721:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9722:                      ('description'              => $description,
                   9723:                       'url'                      => $topurl,
                   9724:                       'internal.creator'         => $env{'user.name'}.':'.
                   9725:                                                     $env{'user.domain'},
                   9726:                       'internal.created'         => $now,
                   9727:                       'internal.creationcontext' => $context)
                   9728:                     );
1.84      www      9729:     return '/'.$udom.'/'.$uname;
                   9730: }
                   9731: 
1.1011    raeburn  9732: # ------------------------------------------------------------------- Create ID
                   9733: sub generate_coursenum {
1.1038    raeburn  9734:     my ($udom,$crstype) = @_;
1.1011    raeburn  9735:     my $domdesc = &domain($udom);
                   9736:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9737:     my $first;
                   9738:     if ($crstype eq 'Community') {
                   9739:         $first = '0';
                   9740:     } else {
                   9741:         $first = int(1+rand(9)); 
                   9742:     } 
                   9743:     my $uname=$first.
1.1011    raeburn  9744:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9745:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9746:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9747: # ----------------------------------------------- Make sure that does not exist
                   9748:     my $uhome=&homeserver($uname,$udom,'true');
                   9749:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9750:         if ($crstype eq 'Community') {
                   9751:             $first = '0';
                   9752:         } else {
                   9753:             $first = int(1+rand(9));
                   9754:         }
                   9755:         $uname=$first.
1.1011    raeburn  9756:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9757:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9758:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9759:         $uhome=&homeserver($uname,$udom,'true');
                   9760:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9761:             return 'error: unable to generate unique course-ID';
                   9762:         }
                   9763:     }
                   9764:     return $uname;
                   9765: }
                   9766: 
1.813     albertel 9767: sub is_course {
1.1167    droeschl 9768:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9769:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9770: 
                   9771:     return unless $cdom and $cnum;
                   9772: 
                   9773:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9774:         '.');
                   9775: 
1.1219    raeburn  9776:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9777:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9778: }
                   9779: 
1.1015    raeburn  9780: sub store_userdata {
                   9781:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9782:     my $result;
1.1016    raeburn  9783:     if ($datakey ne '') {
1.1013    raeburn  9784:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9785:             if ($udom eq '' || $uname eq '') {
                   9786:                 $udom = $env{'user.domain'};
                   9787:                 $uname = $env{'user.name'};
                   9788:             }
                   9789:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9790:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9791:                 $result = 'error: no_host';
                   9792:             } else {
                   9793:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9794:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9795: 
                   9796:                 my $namevalue='';
                   9797:                 foreach my $key (keys(%{$storehash})) {
                   9798:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9799:                 }
                   9800:                 $namevalue=~s/\&$//;
1.1224    raeburn  9801:                 unless ($namespace eq 'courserequests') {
                   9802:                     $datakey = &escape($datakey);
                   9803:                 }
1.1105    raeburn  9804:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9805:                                   $namevalue,$uhome);
1.1013    raeburn  9806:             }
                   9807:         } else {
                   9808:             $result = 'error: data to store was not a hash reference'; 
                   9809:         }
                   9810:     } else {
                   9811:         $result= 'error: invalid requestkey'; 
                   9812:     }
                   9813:     return $result;
                   9814: }
                   9815: 
1.21      www      9816: # ---------------------------------------------------------- Assign Custom Role
                   9817: 
                   9818: sub assigncustomrole {
1.957     raeburn  9819:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9820:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9821:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9822: }
                   9823: 
                   9824: # ----------------------------------------------------------------- Revoke Role
                   9825: 
                   9826: sub revokerole {
1.957     raeburn  9827:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9828:     my $now=time;
1.965     raeburn  9829:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9830: }
                   9831: 
                   9832: # ---------------------------------------------------------- Revoke Custom Role
                   9833: 
                   9834: sub revokecustomrole {
1.957     raeburn  9835:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9836:     my $now=time;
1.357     www      9837:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9838:            $deleteflag,$selfenroll,$context);
1.17      www      9839: }
                   9840: 
1.533     banghart 9841: # ------------------------------------------------------------ Disk usage
1.535     albertel 9842: sub diskusage {
1.955     raeburn  9843:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9844:     $directorypath =~ s/\/$//;
                   9845:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9846:                        .&escape($getpropath).':'.&escape($uname).':'
                   9847:                        .&escape($udom),homeserver($uname,$udom));
                   9848:     if ($listing eq 'unknown_cmd') {
                   9849:         if ($getpropath) {
                   9850:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9851:         }
                   9852:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9853:     }
1.514     albertel 9854:     return $listing;
1.512     banghart 9855: }
                   9856: 
1.566     banghart 9857: sub is_locked {
1.1096    raeburn  9858:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9859:     my @check;
                   9860:     my $is_locked;
1.1093    raeburn  9861:     push (@check,$file_name);
1.613     albertel 9862:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9863: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9864:     my ($tmp)=keys(%locked);
                   9865:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9866:     
1.566     banghart 9867:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9868:         $is_locked = 'false';
                   9869:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9870:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9871:                $is_locked = 'true';
1.1096    raeburn  9872:                if (ref($which) eq 'ARRAY') {
                   9873:                    push(@{$which},$entry);
                   9874:                } else {
                   9875:                    last;
                   9876:                }
1.745     raeburn  9877:            }
                   9878:        }
1.566     banghart 9879:     } else {
                   9880:         $is_locked = 'false';
                   9881:     }
1.1093    raeburn  9882:     return $is_locked;
1.566     banghart 9883: }
                   9884: 
1.759     albertel 9885: sub declutter_portfile {
                   9886:     my ($file) = @_;
1.833     albertel 9887:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9888:     return $file;
                   9889: }
                   9890: 
1.559     banghart 9891: # ------------------------------------------------------------- Mark as Read Only
                   9892: 
                   9893: sub mark_as_readonly {
                   9894:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9895:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9896:     my ($tmp)=keys(%current_permissions);
                   9897:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9898:     foreach my $file (@{$files}) {
1.759     albertel 9899: 	$file = &declutter_portfile($file);
1.561     banghart 9900:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9901:     }
1.613     albertel 9902:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9903:     return;
                   9904: }
                   9905: 
1.572     banghart 9906: # ------------------------------------------------------------Save Selected Files
                   9907: 
                   9908: sub save_selected_files {
                   9909:     my ($user, $path, @files) = @_;
                   9910:     my $filename = $user."savedfiles";
1.573     banghart 9911:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9912:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9913:     foreach my $file (@files) {
1.620     albertel 9914:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9915:     }
                   9916:     foreach my $file (@other_files) {
1.574     banghart 9917:         print (OUT $file."\n");
1.572     banghart 9918:     }
1.574     banghart 9919:     close (OUT);
1.572     banghart 9920:     return 'ok';
                   9921: }
                   9922: 
1.574     banghart 9923: sub clear_selected_files {
                   9924:     my ($user) = @_;
                   9925:     my $filename = $user."savedfiles";
1.1117    foxr     9926:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9927:     print (OUT undef);
                   9928:     close (OUT);
                   9929:     return ("ok");    
                   9930: }
                   9931: 
1.572     banghart 9932: sub files_in_path {
                   9933:     my ($user, $path) = @_;
                   9934:     my $filename = $user."savedfiles";
                   9935:     my %return_files;
1.1117    foxr     9936:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9937:     while (my $line_in = <IN>) {
1.574     banghart 9938:         chomp ($line_in);
                   9939:         my @paths_and_file = split (m!/!, $line_in);
                   9940:         my $file_part = pop (@paths_and_file);
                   9941:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9942:         $path_part.='/';
                   9943:         my $path_and_file = $path_part.$file_part;
                   9944:         if ($path_part eq $path) {
                   9945:             $return_files{$file_part}= 'selected';
                   9946:         }
                   9947:     }
1.574     banghart 9948:     close (IN);
                   9949:     return (\%return_files);
1.572     banghart 9950: }
                   9951: 
                   9952: # called in portfolio select mode, to show files selected NOT in current directory
                   9953: sub files_not_in_path {
                   9954:     my ($user, $path) = @_;
                   9955:     my $filename = $user."savedfiles";
                   9956:     my @return_files;
                   9957:     my $path_part;
1.1117    foxr     9958:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9959:     while (my $line = <IN>) {
1.572     banghart 9960:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9961:         my @paths_and_file = split(m|/|, $line);
                   9962:         my $file_part = pop(@paths_and_file);
                   9963:         chomp($file_part);
                   9964:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9965:         $path_part .= '/';
                   9966:         my $path_and_file = $path_part.$file_part;
                   9967:         if ($path_part ne $path) {
1.800     albertel 9968:             push(@return_files, ($path_and_file));
1.572     banghart 9969:         }
                   9970:     }
1.800     albertel 9971:     close(OUT);
1.574     banghart 9972:     return (@return_files);
1.572     banghart 9973: }
                   9974: 
1.1273    raeburn  9975: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9976:  
                   9977: sub portfiles_versioning {
                   9978:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9979:     my $portfolio_root = '/userfiles/portfolio';
                   9980:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9981:     foreach my $file (@{$portfiles}) {
                   9982:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9983:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9984:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9985:         my $getpropath = 1;
                   9986:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9987:                                              $stu_name,$getpropath);
                   9988:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9989:         my $new_answer = 
                   9990:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9991:         if ($new_answer ne 'problem getting file') {
                   9992:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9993:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9994:                               [$symb,$env{'request.course.id'},'graded']);
                   9995:         }
                   9996:     }
                   9997: }
                   9998: 
                   9999: sub get_next_version {
                   10000:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10001:     my $version;
                   10002:     if (ref($dir_list) eq 'ARRAY') {
                   10003:         foreach my $row (@{$dir_list}) {
                   10004:             my ($file) = split(/\&/,$row,2);
                   10005:             my ($file_name,$file_version,$file_ext) =
                   10006:                 &file_name_version_ext($file);
                   10007:             if (($file_name eq $answer_name) &&
                   10008:                 ($file_ext eq $answer_ext)) {
                   10009:                      # gets here if filename and extension match,
                   10010:                      # regardless of version
                   10011:                 if ($file_version ne '') {
                   10012:                     # a versioned file is found  so save it for later
                   10013:                     if ($file_version > $version) {
                   10014:                         $version = $file_version;
                   10015:                     }
                   10016:                 }
                   10017:             }
                   10018:         }
                   10019:     }
                   10020:     $version ++;
                   10021:     return($version);
                   10022: }
                   10023: 
                   10024: sub version_selected_portfile {
                   10025:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10026:     my ($answer_name,$answer_ver,$answer_ext) =
                   10027:         &file_name_version_ext($file_name);
                   10028:     my $new_answer;
                   10029:     $env{'form.copy'} =
                   10030:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10031:     if($env{'form.copy'} eq '-1') {
                   10032:         $new_answer = 'problem getting file';
                   10033:     } else {
                   10034:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10035:         my $copy_result = 
                   10036:             &finishuserfileupload($stu_name,$domain,'copy',
                   10037:                                   '/portfolio'.$directory.$new_answer);
                   10038:     }
                   10039:     undef($env{'form.copy'});
                   10040:     return ($new_answer);
                   10041: }
                   10042: 
                   10043: sub file_name_version_ext {
                   10044:     my ($file)=@_;
                   10045:     my @file_parts = split(/\./, $file);
                   10046:     my ($name,$version,$ext);
                   10047:     if (@file_parts > 1) {
                   10048:         $ext=pop(@file_parts);
                   10049:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10050:             $version=pop(@file_parts);
                   10051:         }
                   10052:         $name=join('.',@file_parts);
                   10053:     } else {
                   10054:         $name=join('.',@file_parts);
                   10055:     }
                   10056:     return($name,$version,$ext);
                   10057: }
                   10058: 
1.745     raeburn  10059: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10060: 
1.745     raeburn  10061: sub get_portfile_permissions {
                   10062:     my ($domain,$user) = @_;
1.613     albertel 10063:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10064:     my ($tmp)=keys(%current_permissions);
                   10065:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10066:     return \%current_permissions;
                   10067: }
                   10068: 
                   10069: #---------------------------------------------Get portfolio file access controls
                   10070: 
1.749     raeburn  10071: sub get_access_controls {
1.745     raeburn  10072:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10073:     my %access;
                   10074:     my $real_file = $file;
                   10075:     $file =~ s/\.meta$//;
1.745     raeburn  10076:     if (defined($file)) {
1.749     raeburn  10077:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10078:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10079:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10080:             }
                   10081:         }
1.745     raeburn  10082:     } else {
1.749     raeburn  10083:         foreach my $key (keys(%{$current_permissions})) {
                   10084:             if ($key =~ /\0accesscontrol$/) {
                   10085:                 if (defined($group)) {
                   10086:                     if ($key !~ m-^\Q$group\E/-) {
                   10087:                         next;
                   10088:                     }
                   10089:                 }
                   10090:                 my ($fullpath) = split(/\0/,$key);
                   10091:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10092:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10093:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10094:                     }
                   10095:                 }
                   10096:             }
                   10097:         }
                   10098:     }
                   10099:     return %access;
                   10100: }
                   10101: 
                   10102: sub modify_access_controls {
                   10103:     my ($file_name,$changes,$domain,$user)=@_;
                   10104:     my ($outcome,$deloutcome);
                   10105:     my %store_permissions;
                   10106:     my %new_values;
                   10107:     my %new_control;
                   10108:     my %translation;
                   10109:     my @deletions = ();
                   10110:     my $now = time;
                   10111:     if (exists($$changes{'activate'})) {
                   10112:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10113:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10114:             my $numnew = scalar(@newitems);
                   10115:             for (my $i=0; $i<$numnew; $i++) {
                   10116:                 my $newkey = $newitems[$i];
                   10117:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10118:                 if ($newkey =~ /^\d+:/) { 
                   10119:                     $newkey =~ s/^(\d+)/$newid/;
                   10120:                     $translation{$1} = $newid;
                   10121:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10122:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10123:                     $translation{$1} = $newid;
                   10124:                 }
1.749     raeburn  10125:                 $new_values{$file_name."\0".$newkey} = 
                   10126:                                           $$changes{'activate'}{$newitems[$i]};
                   10127:                 $new_control{$newkey} = $now;
                   10128:             }
                   10129:         }
                   10130:     }
                   10131:     my %todelete;
                   10132:     my %changed_items;
                   10133:     foreach my $action ('delete','update') {
                   10134:         if (exists($$changes{$action})) {
                   10135:             if (ref($$changes{$action}) eq 'HASH') {
                   10136:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10137:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10138:                     if ($action eq 'delete') { 
                   10139:                         $todelete{$itemnum} = 1;
                   10140:                     } else {
                   10141:                         $changed_items{$itemnum} = $key;
                   10142:                     }
                   10143:                 }
1.745     raeburn  10144:             }
                   10145:         }
1.749     raeburn  10146:     }
                   10147:     # get lock on access controls for file.
                   10148:     my $lockhash = {
                   10149:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10150:                                                        ':'.$env{'user.domain'},
                   10151:                    }; 
                   10152:     my $tries = 0;
                   10153:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10154:    
1.1288    damieng  10155:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10156:         $tries ++;
1.1289    damieng  10157:         sleep(0.1);
1.749     raeburn  10158:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10159:     }
                   10160:     if ($gotlock eq 'ok') {
                   10161:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10162:         my ($tmp)=keys(%curr_permissions);
                   10163:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10164:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10165:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10166:             if (ref($curr_controls) eq 'HASH') {
                   10167:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10168:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10169:                     if (defined($todelete{$itemnum})) {
                   10170:                         push(@deletions,$file_name."\0".$control_item);
                   10171:                     } else {
                   10172:                         if (defined($changed_items{$itemnum})) {
                   10173:                             $new_control{$changed_items{$itemnum}} = $now;
                   10174:                             push(@deletions,$file_name."\0".$control_item);
                   10175:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10176:                         } else {
                   10177:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10178:                         }
                   10179:                     }
1.745     raeburn  10180:                 }
                   10181:             }
                   10182:         }
1.970     raeburn  10183:         my ($group);
                   10184:         if (&is_course($domain,$user)) {
                   10185:             ($group,my $file) = split(/\//,$file_name,2);
                   10186:         }
1.749     raeburn  10187:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10188:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10189:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10190:         #  remove lock
                   10191:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10192:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10193:         my $sqlresult =
1.970     raeburn  10194:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10195:                                     $group);
1.749     raeburn  10196:     } else {
                   10197:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10198:     }
1.749     raeburn  10199:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10200: }
                   10201: 
1.827     raeburn  10202: sub make_public_indefinitely {
1.1271    raeburn  10203:     my (@requrl) = @_;
                   10204:     return &automated_portfile_access('public',\@requrl);
                   10205: }
                   10206: 
                   10207: sub automated_portfile_access {
                   10208:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10209:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10210:         return 'invalid';
                   10211:     }
1.1271    raeburn  10212:     my %urls;
                   10213:     if (ref($addsref) eq 'ARRAY') {
                   10214:         foreach my $requrl (@{$addsref}) {
                   10215:             if (&is_portfolio_url($requrl)) {
                   10216:                 unless (exists($urls{$requrl})) {
                   10217:                     $urls{$requrl} = 'add';
                   10218:                 }
                   10219:             }
                   10220:         }
                   10221:     }
                   10222:     if (ref($delsref) eq 'ARRAY') {
                   10223:         foreach my $requrl (@{$delsref}) { 
                   10224:             if (&is_portfolio_url($requrl)) {
                   10225:                 unless (exists($urls{$requrl})) {
                   10226:                     $urls{$requrl} = 'delete'; 
                   10227:                 }
                   10228:             }
                   10229:         }
                   10230:     }
                   10231:     unless (keys(%urls)) {
                   10232:         return 'invalid';
                   10233:     }
                   10234:     my $ip;
                   10235:     if ($accesstype eq 'ip') {
                   10236:         if (ref($info) eq 'HASH') {
                   10237:             if ($info->{'ip'} ne '') {
                   10238:                 $ip = $info->{'ip'};
                   10239:             }
                   10240:         }
                   10241:         if ($ip eq '') {
                   10242:             return 'invalid';
                   10243:         }
                   10244:     }
                   10245:     my $errors;
1.827     raeburn  10246:     my $now = time;
1.1271    raeburn  10247:     my %current_perms;
                   10248:     foreach my $requrl (sort(keys(%urls))) {
                   10249:         my $action;
                   10250:         if ($urls{$requrl} eq 'add') {
                   10251:             $action = 'activate';
                   10252:         } else {
                   10253:             $action = 'none';
                   10254:         }
                   10255:         my $aclnum = 0;
1.827     raeburn  10256:         my (undef,$udom,$unum,$file_name,$group) =
                   10257:             &parse_portfolio_url($requrl);
1.1271    raeburn  10258:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10259:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10260:         }
                   10261:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10262:                                                    $group,$file_name);
                   10263:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10264:             my ($num,$scope,$end,$start) = 
                   10265:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10266:             if ($scope eq $accesstype) {
                   10267:                 if (($start <= $now) && ($end == 0)) {
                   10268:                     if ($accesstype eq 'ip') {
                   10269:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10270:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10271:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10272:                                     if ($urls{$requrl} eq 'add') {
                   10273:                                         $action = 'none';
                   10274:                                         last;
                   10275:                                     } else {
                   10276:                                         $action = 'delete';
                   10277:                                         $aclnum = $num;
                   10278:                                         last;
                   10279:                                     }
                   10280:                                 }
                   10281:                             }
                   10282:                         }
                   10283:                     } elsif ($accesstype eq 'public') {
                   10284:                         if ($urls{$requrl} eq 'add') {
                   10285:                             $action = 'none';
                   10286:                             last;
                   10287:                         } else {
                   10288:                             $action = 'delete';
                   10289:                             $aclnum = $num;
                   10290:                             last;
                   10291:                         }
                   10292:                     }
                   10293:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10294:                     $action = 'update';
                   10295:                     $aclnum = $num;
1.1271    raeburn  10296:                     last;
1.827     raeburn  10297:                 }
                   10298:             }
                   10299:         }
                   10300:         if ($action eq 'none') {
1.1271    raeburn  10301:             next;
1.827     raeburn  10302:         } else {
                   10303:             my %changes;
                   10304:             my $newend = 0;
                   10305:             my $newstart = $now;
1.1271    raeburn  10306:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10307:             $changes{$action}{$newkey} = {
1.1271    raeburn  10308:                 type => $accesstype,
1.827     raeburn  10309:                 time => {
                   10310:                     start => $newstart,
                   10311:                     end   => $newend,
                   10312:                 },
                   10313:             };
1.1271    raeburn  10314:             if ($accesstype eq 'ip') {
                   10315:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10316:             }
1.827     raeburn  10317:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10318:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10319:             unless ($outcome eq 'ok') {
                   10320:                 $errors .= $outcome.' ';
                   10321:             }
1.827     raeburn  10322:         }
1.1271    raeburn  10323:     }
                   10324:     if ($errors) {
                   10325:         $errors =~ s/\s$//;
                   10326:         return $errors;
1.827     raeburn  10327:     } else {
1.1271    raeburn  10328:         return 'ok';
1.827     raeburn  10329:     }
                   10330: }
                   10331: 
1.745     raeburn  10332: #------------------------------------------------------Get Marked as Read Only
                   10333: 
                   10334: sub get_marked_as_readonly {
                   10335:     my ($domain,$user,$what,$group) = @_;
                   10336:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10337:     my @readonly_files;
1.629     banghart 10338:     my $cmp1=$what;
                   10339:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10340:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10341:         if (defined($group)) {
                   10342:             if ($file_name !~ m-^\Q$group\E/-) {
                   10343:                 next;
                   10344:             }
                   10345:         }
1.561     banghart 10346:         if (ref($value) eq "ARRAY"){
                   10347:             foreach my $stored_what (@{$value}) {
1.629     banghart 10348:                 my $cmp2=$stored_what;
1.759     albertel 10349:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10350:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10351:                 }
1.629     banghart 10352:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10353:                     push(@readonly_files, $file_name);
1.745     raeburn  10354:                     last;
1.563     banghart 10355:                 } elsif (!defined($what)) {
                   10356:                     push(@readonly_files, $file_name);
1.745     raeburn  10357:                     last;
1.561     banghart 10358:                 }
                   10359:             }
1.745     raeburn  10360:         }
1.561     banghart 10361:     }
                   10362:     return @readonly_files;
                   10363: }
1.577     banghart 10364: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10365: 
1.577     banghart 10366: sub get_marked_as_readonly_hash {
1.745     raeburn  10367:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10368:     my %readonly_files;
1.745     raeburn  10369:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10370:         if (defined($group)) {
                   10371:             if ($file_name !~ m-^\Q$group\E/-) {
                   10372:                 next;
                   10373:             }
                   10374:         }
1.577     banghart 10375:         if (ref($value) eq "ARRAY"){
                   10376:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10377:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10378:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10379:                         if ($lock_descriptor eq 'graded') {
                   10380:                             $readonly_files{$file_name} = 'graded';
                   10381:                         } elsif ($lock_descriptor eq 'handback') {
                   10382:                             $readonly_files{$file_name} = 'handback';
                   10383:                         } else {
                   10384:                             if (!exists($readonly_files{$file_name})) {
                   10385:                                 $readonly_files{$file_name} = 'locked';
                   10386:                             }
                   10387:                         }
1.745     raeburn  10388:                     }
1.750     banghart 10389:                 } 
1.577     banghart 10390:             }
                   10391:         } 
                   10392:     }
                   10393:     return %readonly_files;
                   10394: }
1.559     banghart 10395: # ------------------------------------------------------------ Unmark as Read Only
                   10396: 
                   10397: sub unmark_as_readonly {
1.629     banghart 10398:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10399:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10400:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10401:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10402:     my $symb_crs = $what;
                   10403:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10404:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10405:     my ($tmp)=keys(%current_permissions);
                   10406:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10407:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10408:     foreach my $file (@readonly_files) {
1.759     albertel 10409: 	my $clean_file = &declutter_portfile($file);
                   10410: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10411: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10412:         my @new_locks;
                   10413:         my @del_keys;
                   10414:         if (ref($current_locks) eq "ARRAY"){
                   10415:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10416:                 my $compare=$locker;
1.749     raeburn  10417:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10418:                     $compare=join('',@{$locker});
1.746     raeburn  10419:                     if ($compare ne $symb_crs) {
                   10420:                         push(@new_locks, $locker);
                   10421:                     }
1.563     banghart 10422:                 }
                   10423:             }
1.650     albertel 10424:             if (scalar(@new_locks) > 0) {
1.563     banghart 10425:                 $current_permissions{$file} = \@new_locks;
                   10426:             } else {
                   10427:                 push(@del_keys, $file);
1.613     albertel 10428:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10429:                 delete($current_permissions{$file});
1.563     banghart 10430:             }
                   10431:         }
1.561     banghart 10432:     }
1.613     albertel 10433:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10434:     return;
                   10435: }
1.512     banghart 10436: 
1.17      www      10437: # ------------------------------------------------------------ Directory lister
                   10438: 
                   10439: sub dirlist {
1.955     raeburn  10440:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10441:     $uri=~s/^\///;
                   10442:     $uri=~s/\/$//;
1.253     stredwic 10443:     my ($udom, $uname);
1.955     raeburn  10444:     if ($getuserdir) {
1.253     stredwic 10445:         $udom = $userdomain;
                   10446:         $uname = $username;
1.955     raeburn  10447:     } else {
                   10448:         (undef,$udom,$uname)=split(/\//,$uri);
                   10449:         if(defined($userdomain)) {
                   10450:             $udom = $userdomain;
                   10451:         }
                   10452:         if(defined($username)) {
                   10453:             $uname = $username;
                   10454:         }
1.253     stredwic 10455:     }
1.955     raeburn  10456:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10457: 
1.955     raeburn  10458:     $dirRoot = $perlvar{'lonDocRoot'};
                   10459:     if (defined($getpropath)) {
                   10460:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10461:         $dirRoot =~ s/\/$//;
1.955     raeburn  10462:     } elsif (defined($getuserdir)) {
                   10463:         my $subdir=$uname.'__';
                   10464:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10465:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10466:                    ."/$udom/$subdir/$uname";
                   10467:     } elsif (defined($alternateRoot)) {
                   10468:         $dirRoot = $alternateRoot;
1.751     banghart 10469:     }
1.253     stredwic 10470: 
                   10471:     if($udom) {
                   10472:         if($uname) {
1.1135    raeburn  10473:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10474:             if ($uhome eq 'no_host') {
                   10475:                 return ([],'no_host');
                   10476:             }
1.955     raeburn  10477:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10478:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10479:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10480:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10481:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10482:             } else {
                   10483:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10484:             }
1.605     matthew  10485:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10486:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10487:                 @listing_results = split(/:/,$listing);
                   10488:             } else {
                   10489:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10490:             }
1.1135    raeburn  10491:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10492:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10493:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10494:                 return ([],$listing);
                   10495:             } else {
                   10496:                 return (\@listing_results);
1.1135    raeburn  10497:             }
1.955     raeburn  10498:         } elsif(!$alternateRoot) {
1.1136    raeburn  10499:             my (%allusers,%listerror);
1.841     albertel 10500: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10501:  	    foreach my $tryserver (keys(%servers)) {
                   10502:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10503:                                   &escape($udom),$tryserver);
                   10504:                 if ($listing eq 'unknown_cmd') {
                   10505: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10506: 				      $udom, $tryserver);
                   10507:                 } else {
                   10508:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10509:                 }
1.841     albertel 10510: 		if ($listing eq 'unknown_cmd') {
                   10511: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10512: 				      $udom, $tryserver);
                   10513: 		    @listing_results = split(/:/,$listing);
                   10514: 		} else {
                   10515: 		    @listing_results =
                   10516: 			map { &unescape($_); } split(/:/,$listing);
                   10517: 		}
1.1136    raeburn  10518:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10519:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10520:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10521:                     $listerror{$tryserver} = $listing;
                   10522:                 } else {
1.841     albertel 10523: 		    foreach my $line (@listing_results) {
                   10524: 			my ($entry) = split(/&/,$line,2);
                   10525: 			$allusers{$entry} = 1;
                   10526: 		    }
                   10527: 		}
1.253     stredwic 10528:             }
1.1136    raeburn  10529:             my @alluserslist=();
1.800     albertel 10530:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10531:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10532:             }
1.1318    droeschl 10533: 
                   10534:             if (!%listerror) {
                   10535:                 # no errors
                   10536:                 return (\@alluserslist);
                   10537:             } elsif (scalar(keys(%servers)) == 1) {
                   10538:                 # one library server, one error 
                   10539:                 my ($key) = keys(%listerror);
                   10540:                 return (\@alluserslist, $listerror{$key});
                   10541:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10542:                 # con_lost indicates that we might miss data from at least one
                   10543:                 # library server
                   10544:                 return (\@alluserslist, 'con_lost');
                   10545:             } else {
                   10546:                 # multiple library servers and no con_lost -> data should be
                   10547:                 # complete. 
                   10548:                 return (\@alluserslist);
                   10549:             }
                   10550: 
1.253     stredwic 10551:         } else {
1.1136    raeburn  10552:             return ([],'missing username');
1.253     stredwic 10553:         }
1.955     raeburn  10554:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10555:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10556:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10557:         return (\@all_domains);
1.955     raeburn  10558:     } else {
1.1136    raeburn  10559:         return ([],'missing domain');
1.275     stredwic 10560:     }
                   10561: }
                   10562: 
                   10563: # --------------------------------------------- GetFileTimestamp
                   10564: # This function utilizes dirlist and returns the date stamp for
                   10565: # when it was last modified.  It will also return an error of -1
                   10566: # if an error occurs
                   10567: 
                   10568: sub GetFileTimestamp {
1.955     raeburn  10569:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10570:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10571:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10572:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10573:                                     undef,$getuserdir);
                   10574:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10575:         return -1;
                   10576:     }
                   10577:     if (ref($fileref) eq 'ARRAY') {
                   10578:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10579:         # @stats contains first the filename, then the stat output
                   10580:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10581:     } else {
                   10582:         return -1;
1.253     stredwic 10583:     }
1.26      www      10584: }
                   10585: 
1.712     albertel 10586: sub stat_file {
                   10587:     my ($uri) = @_;
1.787     albertel 10588:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10589: 
1.955     raeburn  10590:     my ($udom,$uname,$file);
1.712     albertel 10591:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10592: 	($udom,$uname,$file) =
1.811     albertel 10593: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10594: 	$file = 'userfiles/'.$file;
                   10595:     }
                   10596:     if ($uri =~ m-^/res/-) {
                   10597: 	($udom,$uname) = 
1.807     albertel 10598: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10599: 	$file = $uri;
                   10600:     }
                   10601: 
                   10602:     if (!$udom || !$uname || !$file) {
                   10603: 	# unable to handle the uri
                   10604: 	return ();
                   10605:     }
1.956     raeburn  10606:     my $getpropath;
                   10607:     if ($file =~ /^userfiles\//) {
                   10608:         $getpropath = 1;
                   10609:     }
1.1136    raeburn  10610:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10611:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10612:         return ();
                   10613:     } else {
                   10614:         if (ref($listref) eq 'ARRAY') {
                   10615:             my @stats = split('&',$listref->[0]);
                   10616: 	    shift(@stats); #filename is first
                   10617: 	    return @stats;
                   10618:         }
1.712     albertel 10619:     }
                   10620:     return ();
                   10621: }
                   10622: 
1.1313    raeburn  10623: # --------------------------------------------------------- recursedirs
                   10624: # Recursive function to traverse either a specific user's Authoring Space
                   10625: # or corresponding Published Resource Space, and populate the hash ref:
                   10626: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10627: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10628: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10629: # files in Authoring Space.
                   10630: #
                   10631: # Inputs:
                   10632: #
                   10633: # $is_home - true if current server is home server for user's space
                   10634: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10635: # $docroot - Document root (i.e., /home/httpd/html
                   10636: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10637: # $relpath - Current path (relative to top level).
                   10638: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10639: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10640: #
                   10641: # Returns: nothing
                   10642: #
                   10643: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10644: #
                   10645: # Currently used by interface/londocs.pm to create linked select boxes for
                   10646: # directory and filename to import a Course "Author" resource into a course, and
                   10647: # also to create linked select boxes for Authoring Space and Directory to choose
                   10648: # save location for creation of a new "standard" problem from the Course Editor.
                   10649: #
                   10650: 
                   10651: sub recursedirs {
                   10652:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10653:     return unless (ref($dirhashref) eq 'HASH');
                   10654:     my $currpath = $docroot.$toppath;
                   10655:     if ($relpath) {
                   10656:         $currpath .= "/$relpath";
                   10657:     }
                   10658:     my $savefile;
                   10659:     if (ref($filehashref)) {
                   10660:         $savefile = 1;
                   10661:     }
                   10662:     if ($is_home) {
                   10663:         if (opendir(my $dirh,$currpath)) {
                   10664:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10665:                 next if ($item eq '');
                   10666:                 if (-d "$currpath/$item") {
                   10667:                     my $newpath;
                   10668:                     if ($relpath) {
                   10669:                         $newpath = "$relpath/$item";
                   10670:                     } else {
                   10671:                         $newpath = $item;
                   10672:                     }
                   10673:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10674:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10675:                 } elsif ($savefile) {
                   10676:                     if ($context eq 'priv') {
                   10677:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10678:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10679:                         }
                   10680:                     } else {
                   10681:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10682:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10683:                         }
                   10684:                     }
                   10685:                 }
                   10686:             }
                   10687:             closedir($dirh);
                   10688:         }
                   10689:     } else {
                   10690:         my ($dirlistref,$listerror) =
                   10691:             &dirlist($toppath.$relpath);
                   10692:         my @dir_lines;
                   10693:         my $dirptr=16384;
                   10694:         if (ref($dirlistref) eq 'ARRAY') {
                   10695:             foreach my $dir_line (sort
                   10696:                               {
                   10697:                                   my ($afile)=split('&',$a,2);
                   10698:                                   my ($bfile)=split('&',$b,2);
                   10699:                                   return (lc($afile) cmp lc($bfile));
                   10700:                               } (@{$dirlistref})) {
                   10701:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10702:                     split(/\&/,$dir_line,16);
                   10703:                 $item =~ s/\s+$//;
                   10704:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10705:                 if ($dirptr&$testdir) {
                   10706:                     my $newpath;
                   10707:                     if ($relpath) {
                   10708:                         $newpath = "$relpath/$item";
                   10709:                     } else {
                   10710:                         $relpath = '/';
                   10711:                         $newpath = $item;
                   10712:                     }
                   10713:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10714:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10715:                 } elsif ($savefile) {
                   10716:                     if ($context eq 'priv') {
                   10717:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10718:                             $filehashref->{$relpath}{$item} = 1;
                   10719:                         }
                   10720:                     } else {
                   10721:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10722:                             $filehashref->{$relpath}{$item} = 1;
                   10723:                         }
                   10724:                     }
                   10725:                 }
                   10726:             }
                   10727:         }
                   10728:     }
                   10729:     return;
                   10730: }
                   10731: 
1.26      www      10732: # -------------------------------------------------------- Value of a Condition
                   10733: 
1.713     albertel 10734: # gets the value of a specific preevaluated condition
                   10735: #    stored in the string  $env{user.state.<cid>}
                   10736: # or looks up a condition reference in the bighash and if if hasn't
                   10737: # already been evaluated recurses into docondval to get the value of
                   10738: # the condition, then memoizing it to 
                   10739: #   $env{user.state.<cid>.<condition>}
1.40      www      10740: sub directcondval {
                   10741:     my $number=shift;
1.620     albertel 10742:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10743: 	&Apache::lonuserstate::evalstate();
                   10744:     }
1.713     albertel 10745:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10746: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10747:     } elsif ($number =~ /^_/) {
                   10748: 	my $sub_condition;
                   10749: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10750: 		&GDBM_READER(),0640)) {
                   10751: 	    $sub_condition=$bighash{'conditions'.$number};
                   10752: 	    untie(%bighash);
                   10753: 	}
                   10754: 	my $value = &docondval($sub_condition);
1.949     raeburn  10755: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10756: 	return $value;
                   10757:     }
1.620     albertel 10758:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10759:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10760:     } else {
                   10761:        return 2;
                   10762:     }
                   10763: }
                   10764: 
1.713     albertel 10765: # get the collection of conditions for this resource
1.26      www      10766: sub condval {
                   10767:     my $condidx=shift;
1.54      www      10768:     my $allpathcond='';
1.713     albertel 10769:     foreach my $cond (split(/\|/,$condidx)) {
                   10770: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10771: 	    $allpathcond.=
                   10772: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10773: 	}
1.191     harris41 10774:     }
1.54      www      10775:     $allpathcond=~s/\|$//;
1.713     albertel 10776:     return &docondval($allpathcond);
                   10777: }
                   10778: 
                   10779: #evaluates an expression of conditions
                   10780: sub docondval {
                   10781:     my ($allpathcond) = @_;
                   10782:     my $result=0;
                   10783:     if ($env{'request.course.id'}
                   10784: 	&& defined($allpathcond)) {
                   10785: 	my $operand='|';
                   10786: 	my @stack;
                   10787: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10788: 	    if ($chunk eq '(') {
                   10789: 		push @stack,($operand,$result);
                   10790: 	    } elsif ($chunk eq ')') {
                   10791: 		my $before=pop @stack;
                   10792: 		if (pop @stack eq '&') {
                   10793: 		    $result=$result>$before?$before:$result;
                   10794: 		} else {
                   10795: 		    $result=$result>$before?$result:$before;
                   10796: 		}
                   10797: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10798: 		$operand=$chunk;
                   10799: 	    } else {
                   10800: 		my $new=directcondval($chunk);
                   10801: 		if ($operand eq '&') {
                   10802: 		    $result=$result>$new?$new:$result;
                   10803: 		} else {
                   10804: 		    $result=$result>$new?$result:$new;
                   10805: 		}
                   10806: 	    }
                   10807: 	}
1.26      www      10808:     }
                   10809:     return $result;
1.421     albertel 10810: }
                   10811: 
                   10812: # ---------------------------------------------------- Devalidate courseresdata
                   10813: 
                   10814: sub devalidatecourseresdata {
                   10815:     my ($coursenum,$coursedomain)=@_;
                   10816:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10817:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10818: }
                   10819: 
1.763     www      10820: 
1.200     www      10821: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10822: #
                   10823: #  Parameters:
                   10824: #      $coursenum    - Number of the course.
                   10825: #      $coursedomain - Domain at which the course was created.
                   10826: #  Returns:
                   10827: #     A hash of the course parameters along (I think) with timestamps
                   10828: #     and version info.
1.877     foxr     10829: 
1.624     albertel 10830: sub get_courseresdata {
                   10831:     my ($coursenum,$coursedomain)=@_;
1.200     www      10832:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10833:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10834:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10835:     my %dumpreply;
1.417     albertel 10836:     unless (defined($cached)) {
1.624     albertel 10837: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10838: 	$result=\%dumpreply;
1.251     albertel 10839: 	my ($tmp) = keys(%dumpreply);
                   10840: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10841: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10842: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10843: 	    return $tmp;
1.416     albertel 10844: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10845: 	    $result=undef;
1.599     albertel 10846: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10847: 	}
                   10848:     }
1.624     albertel 10849:     return $result;
                   10850: }
                   10851: 
1.633     albertel 10852: sub devalidateuserresdata {
                   10853:     my ($uname,$udom)=@_;
                   10854:     my $hashid="$udom:$uname";
                   10855:     &devalidate_cache_new('userres',$hashid);
                   10856: }
                   10857: 
1.624     albertel 10858: sub get_userresdata {
                   10859:     my ($uname,$udom)=@_;
                   10860:     #most student don\'t have any data set, check if there is some data
                   10861:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10862: 
                   10863:     my $hashid="$udom:$uname";
                   10864:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10865:     if (!defined($cached)) {
                   10866: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10867: 	$result=\%resourcedata;
                   10868: 	&do_cache_new('userres',$hashid,$result,600);
                   10869:     }
                   10870:     my ($tmp)=keys(%$result);
                   10871:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10872: 	return $result;
                   10873:     }
                   10874:     #error 2 occurs when the .db doesn't exist
                   10875:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10876:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10877: 	    &logthis("<font color=\"blue\">WARNING:".
                   10878: 		     " Trying to get resource data for ".
                   10879: 		     $uname." at ".$udom.": ".
                   10880: 		     $tmp."</font>");
                   10881:         }
1.624     albertel 10882:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10883: 	#&EXT_cache_set($udom,$uname);
                   10884: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10885: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10886:     }
                   10887:     return $tmp;
                   10888: }
1.879     foxr     10889: #----------------------------------------------- resdata - return resource data
                   10890: #  Purpose:
                   10891: #    Return resource data for either users or for a course.
                   10892: #  Parameters:
                   10893: #     $name      - Course/user name.
                   10894: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10895: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10896: #     $mapp      - decluttered URL of enclosing map  
                   10897: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10898: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10899: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10900: #     $courseid  - CourseID (first part of param identifier).
                   10901: #     $modifier  - Middle part of param identifier.
                   10902: #     $what      - Last part of param identifier.
1.879     foxr     10903: #     @which     - Array of names of resources desired.
                   10904: #  Returns:
                   10905: #     The value of the first reasource in @which that is found in the
                   10906: #     resource hash.
                   10907: #  Exceptional Conditions:
                   10908: #     If the $type passed in is not valid (not the string 'course' or 
                   10909: #     'user', an undefined  reference is returned.
                   10910: #     If none of the resources are found, an undef is returned
1.624     albertel 10911: sub resdata {
1.1301    raeburn  10912:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10913:         $modifier,$what,@which)=@_;
1.624     albertel 10914:     my $result;
                   10915:     if ($type eq 'course') {
                   10916: 	$result=&get_courseresdata($name,$domain);
                   10917:     } elsif ($type eq 'user') {
                   10918: 	$result=&get_userresdata($name,$domain);
                   10919:     }
                   10920:     if (!ref($result)) { return $result; }    
1.251     albertel 10921:     foreach my $item (@which) {
1.1301    raeburn  10922:         if ($item->[1] eq 'course') {
                   10923:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10924:                 unless ($$recursed) {
1.1302    raeburn  10925:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10926:                     $$recursed = 1;
                   10927:                 }
                   10928:                 foreach my $item (@${recurseup}) {
                   10929:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10930:                     last if (defined($result->{$norecursechk}));
                   10931:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10932:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10933:                 }
                   10934:             }
                   10935:         }
                   10936:         if (defined($result->{$item->[0]})) {
1.927     albertel 10937: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10938: 	}
1.250     albertel 10939:     }
1.291     albertel 10940:     return undef;
1.200     www      10941: }
                   10942: 
1.1298    raeburn  10943: sub get_domain_ltitools {
                   10944:     my ($cdom) = @_;
                   10945:     my %ltitools;
                   10946:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10947:     if (defined($cached)) {
                   10948:         if (ref($result) eq 'HASH') {
                   10949:             %ltitools = %{$result};
                   10950:         }
                   10951:     } else {
                   10952:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10953:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10954:             %ltitools = %{$domconfig{'ltitools'}};
                   10955:         }
                   10956:         my $cachetime = 24*60*60;
                   10957:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10958:     }
                   10959:     return %ltitools;
                   10960: }
                   10961: 
1.1236    raeburn  10962: sub get_numsuppfiles {
                   10963:     my ($cnum,$cdom,$ignorecache)=@_;
                   10964:     my $hashid=$cnum.':'.$cdom;
                   10965:     my ($suppcount,$cached);
                   10966:     unless ($ignorecache) {
                   10967:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10968:     }
                   10969:     unless (defined($cached)) {
                   10970:         my $chome=&homeserver($cnum,$cdom);
                   10971:         unless ($chome eq 'no_host') {
                   10972:             ($suppcount,my $errors) = (0,0);
                   10973:             my $suppmap = 'supplemental.sequence';
                   10974:             ($suppcount,$errors) = 
                   10975:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10976:         }
                   10977:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10978:     }
                   10979:     return $suppcount;
                   10980: }
                   10981: 
1.379     matthew  10982: #
                   10983: # EXT resource caching routines
                   10984: #
                   10985: 
1.1302    raeburn  10986: {
                   10987: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10988: #
                   10989: # The course for which we cache
                   10990: my $cachedmapkey='';
                   10991: # The cached recursive maps for this course
                   10992: my %cachedmaps=();
                   10993: # When this was last done
                   10994: my $cachedmaptime='';
                   10995: 
1.379     matthew  10996: sub clear_EXT_cache_status {
1.383     albertel 10997:     &delenv('cache.EXT.');
1.379     matthew  10998: }
                   10999: 
                   11000: sub EXT_cache_status {
                   11001:     my ($target_domain,$target_user) = @_;
1.383     albertel 11002:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11003:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11004:         # We know already the user has no data
                   11005:         return 1;
                   11006:     } else {
                   11007:         return 0;
                   11008:     }
                   11009: }
                   11010: 
                   11011: sub EXT_cache_set {
                   11012:     my ($target_domain,$target_user) = @_;
1.383     albertel 11013:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11014:     #&appenv({$cachename => time});
1.379     matthew  11015: }
                   11016: 
1.28      www      11017: # --------------------------------------------------------- Value of a Variable
1.58      www      11018: sub EXT {
1.715     albertel 11019: 
1.1228    raeburn  11020:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11021:     unless ($varname) { return ''; }
1.218     albertel 11022:     #get real user name/domain, courseid and symb
                   11023:     my $courseid;
1.359     albertel 11024:     my $publicuser;
1.427     www      11025:     if ($symbparm) {
                   11026: 	$symbparm=&get_symb_from_alias($symbparm);
                   11027:     }
1.218     albertel 11028:     if (!($uname && $udom)) {
1.790     albertel 11029:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11030:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11031:     } else {
1.620     albertel 11032: 	$courseid=$env{'request.course.id'};
1.218     albertel 11033:     }
1.48      www      11034:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11035:     my $rest;
1.320     albertel 11036:     if (defined($therest[0])) {
1.48      www      11037:        $rest=join('.',@therest);
                   11038:     } else {
                   11039:        $rest='';
                   11040:     }
1.320     albertel 11041: 
1.57      www      11042:     my $qualifierrest=$qualifier;
                   11043:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11044:     my $spacequalifierrest=$space;
                   11045:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11046:     if ($realm eq 'user') {
1.48      www      11047: # --------------------------------------------------------------- user.resource
                   11048: 	if ($space eq 'resource') {
1.651     albertel 11049: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11050: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11051: 		 &&
1.744     albertel 11052: 		 ($symbparm eq &symbread()) ) {	
                   11053: 		# if we are in the middle of processing the resource the
                   11054: 		# get the value we are planning on committing
                   11055:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11056:                     return $Apache::lonhomework::results{$qualifierrest};
                   11057:                 } else {
                   11058:                     return $Apache::lonhomework::history{$qualifierrest};
                   11059:                 }
1.335     albertel 11060: 	    } else {
1.359     albertel 11061: 		my %restored;
1.620     albertel 11062: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11063: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11064: 		} else {
                   11065: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11066: 		}
1.335     albertel 11067: 		return $restored{$qualifierrest};
                   11068: 	    }
1.48      www      11069: # ----------------------------------------------------------------- user.access
                   11070:         } elsif ($space eq 'access') {
1.218     albertel 11071: 	    # FIXME - not supporting calls for a specific user
1.48      www      11072:             return &allowed($qualifier,$rest);
                   11073: # ------------------------------------------ user.preferences, user.environment
                   11074:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11075: 	    if (($uname eq $env{'user.name'}) &&
                   11076: 		($udom eq $env{'user.domain'})) {
                   11077: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11078: 	    } else {
1.359     albertel 11079: 		my %returnhash;
                   11080: 		if (!$publicuser) {
                   11081: 		    %returnhash=&userenvironment($udom,$uname,
                   11082: 						 $qualifierrest);
                   11083: 		}
1.218     albertel 11084: 		return $returnhash{$qualifierrest};
                   11085: 	    }
1.48      www      11086: # ----------------------------------------------------------------- user.course
                   11087:         } elsif ($space eq 'course') {
1.218     albertel 11088: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11089:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11090: # ------------------------------------------------------------------- user.role
                   11091:         } elsif ($space eq 'role') {
1.218     albertel 11092: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11093:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11094:             if ($qualifier eq 'value') {
                   11095: 		return $role;
                   11096:             } elsif ($qualifier eq 'extent') {
                   11097:                 return $where;
                   11098:             }
                   11099: # ----------------------------------------------------------------- user.domain
                   11100:         } elsif ($space eq 'domain') {
1.218     albertel 11101:             return $udom;
1.48      www      11102: # ------------------------------------------------------------------- user.name
                   11103:         } elsif ($space eq 'name') {
1.218     albertel 11104:             return $uname;
1.48      www      11105: # ---------------------------------------------------- Any other user namespace
1.29      www      11106:         } else {
1.359     albertel 11107: 	    my %reply;
                   11108: 	    if (!$publicuser) {
                   11109: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11110: 	    }
                   11111: 	    return $reply{$qualifierrest};
1.48      www      11112:         }
1.236     www      11113:     } elsif ($realm eq 'query') {
                   11114: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11115:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11116: 						[$spacequalifierrest]);
1.620     albertel 11117: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11118:    } elsif ($realm eq 'request') {
1.48      www      11119: # ------------------------------------------------------------- request.browser
                   11120:         if ($space eq 'browser') {
1.1145    bisitz   11121:             return $env{'browser.'.$qualifier};
1.57      www      11122: # ------------------------------------------------------------ request.filename
                   11123:         } else {
1.620     albertel 11124:             return $env{'request.'.$spacequalifierrest};
1.29      www      11125:         }
1.28      www      11126:     } elsif ($realm eq 'course') {
1.48      www      11127: # ---------------------------------------------------------- course.description
1.620     albertel 11128:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11129:     } elsif ($realm eq 'resource') {
1.165     www      11130: 
1.620     albertel 11131: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11132: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11133: 	}
1.693     albertel 11134: 
1.1232    raeburn  11135:         if ($qualifier eq '') {
                   11136: 	    if ($space eq 'title') {
                   11137: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11138: 	        return &gettitle($symbparm);
                   11139: 	    }
1.693     albertel 11140: 	
1.1232    raeburn  11141: 	    if ($space eq 'map') {
                   11142: 	        my ($map) = &decode_symb($symbparm);
                   11143: 	        return &symbread($map);
                   11144: 	    }
                   11145:             if ($space eq 'maptitle') {
                   11146:                 my ($map) = &decode_symb($symbparm);
                   11147:                 return &gettitle($map);
                   11148:             }
                   11149: 	    if ($space eq 'filename') {
                   11150: 	        if ($symbparm) {
                   11151: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11152: 	        }
                   11153: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11154: 	    }
1.1232    raeburn  11155: 
1.1233    raeburn  11156:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11157:                 if ($space eq 'visibleparts') {
                   11158:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11159:                     my $item;
                   11160:                     if (ref($navmap)) {
                   11161:                         my $res = $navmap->getBySymb($symbparm);
                   11162:                         my $parts = $res->parts();
                   11163:                         if (ref($parts) eq 'ARRAY') {
                   11164:                             $item = join(',',@{$parts});
                   11165:                         }
                   11166:                         undef($navmap);
1.1232    raeburn  11167:                     }
1.1233    raeburn  11168:                     return $item;
1.1232    raeburn  11169:                 }
                   11170:             }
                   11171:         }
1.693     albertel 11172: 
1.1301    raeburn  11173: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11174: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11175:         if (($courseid eq '') && ($cid)) {
                   11176:             $courseid = $cid;
                   11177:         }
                   11178: 	if (($symbparm && $courseid) && 
                   11179: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11180: 
1.218     albertel 11181: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11182: 
1.60      www      11183: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11184: 	    my $symbp=$symbparm;
1.1301    raeburn  11185: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11186: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11187:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11188: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11189: 	    if (($env{'user.name'} eq $uname) &&
                   11190: 		($env{'user.domain'} eq $udom)) {
                   11191: 		$section=$env{'request.course.sec'};
1.733     raeburn  11192:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11193:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11194: 	    } else {
1.539     albertel 11195: 		if (! defined($usection)) {
1.551     albertel 11196: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11197: 		} else {
                   11198: 		    $section = $usection;
                   11199: 		}
1.733     raeburn  11200:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11201: 	    }
                   11202: 
                   11203: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11204: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11205:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11206: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11207: 
1.593     albertel 11208: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11209: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11210:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11211: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11212: 
1.60      www      11213: # ----------------------------------------------------------- first, check user
1.624     albertel 11214: 
1.1301    raeburn  11215: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11216:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11217: 				       ([$courselevelr,'resource'],
                   11218: 					[$courselevelm,'map'     ],
1.1301    raeburn  11219:                                         [$courseleveli,'map'     ],
1.927     albertel 11220: 					[$courselevel, 'course'  ]));
1.931     albertel 11221: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11222: 
1.594     albertel 11223: # ------------------------------------------------ second, check some of course
1.684     raeburn  11224:             my $coursereply;
1.691     raeburn  11225:             if (@groups > 0) {
                   11226:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11227:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11228:                                        $mapp,\$recursed,\@recurseup);
                   11229:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11230:             }
1.96      www      11231: 
1.684     raeburn  11232: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11233: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11234: 				  'course',$mapp,\$recursed,\@recurseup,
                   11235:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11236: 				  ([$seclevelr,   'resource'],
                   11237: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11238:                                    [$secleveli,   'map'     ],
1.927     albertel 11239: 				   [$seclevel,    'course'  ],
                   11240: 				   [$courselevelr,'resource']));
                   11241: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11242: 
1.60      www      11243: # ------------------------------------------------------ third, check map parms
1.218     albertel 11244: 	    my %parmhash=();
                   11245: 	    my $thisparm='';
                   11246: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11247: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11248: 		    &GDBM_READER(),0640)) {
1.218     albertel 11249: 		$thisparm=$parmhash{$symbparm};
                   11250: 		untie(%parmhash);
                   11251: 	    }
1.927     albertel 11252: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11253: 	}
1.594     albertel 11254: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11255:  
                   11256:         my $what = $spacequalifierrest;
                   11257: 	$what=~s/\./\_/;
1.282     albertel 11258: 	my $filename;
                   11259: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11260: 	if ($symbparm) {
1.409     www      11261: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11262: 	} else {
1.620     albertel 11263: 	    $filename=$env{'request.filename'};
1.282     albertel 11264: 	}
1.1301    raeburn  11265: 	my $metadata=&metadata($filename,$what);
1.927     albertel 11266: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  11267: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 11268: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11269: 
1.1301    raeburn  11270: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11271: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11272: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11273: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11274: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11275: 				     'course',$mapp,\$recursed,\@recurseup,
                   11276:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11277: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11278:                                       [$courseleveli,'map'   ],
1.927     albertel 11279: 				      [$courselevel, 'course']));
                   11280: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11281: 	}
1.145     www      11282: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11283: 	unless ($space eq '0') {
1.336     albertel 11284: 	    my @parts=split(/_/,$space);
                   11285: 	    my $id=pop(@parts);
                   11286: 	    my $part=join('_',@parts);
                   11287: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11288: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11289: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11290: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11291: 	}
1.395     albertel 11292: 	if ($recurse) { return undef; }
                   11293: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11294: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11295: # ---------------------------------------------------- Any other user namespace
                   11296:     } elsif ($realm eq 'environment') {
                   11297: # ----------------------------------------------------------------- environment
1.620     albertel 11298: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11299: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11300: 	} else {
1.770     albertel 11301: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11302: 		return '';
                   11303: 	    }
1.219     albertel 11304: 	    my %returnhash=&userenvironment($udom,$uname,
                   11305: 					    $spacequalifierrest);
                   11306: 	    return $returnhash{$spacequalifierrest};
                   11307: 	}
1.28      www      11308:     } elsif ($realm eq 'system') {
1.48      www      11309: # ----------------------------------------------------------------- system.time
                   11310: 	if ($space eq 'time') {
                   11311: 	    return time;
                   11312:         }
1.696     albertel 11313:     } elsif ($realm eq 'server') {
                   11314: # ----------------------------------------------------------------- system.time
                   11315: 	if ($space eq 'name') {
                   11316: 	    return $ENV{'SERVER_NAME'};
                   11317:         }
1.28      www      11318:     }
1.48      www      11319:     return '';
1.61      www      11320: }
                   11321: 
1.927     albertel 11322: sub get_reply {
                   11323:     my ($reply_value) = @_;
1.940     raeburn  11324:     if (ref($reply_value) eq 'ARRAY') {
                   11325:         if (wantarray) {
                   11326: 	    return @$reply_value;
                   11327:         }
                   11328:         return $reply_value->[0];
                   11329:     } else {
                   11330:         return $reply_value;
1.927     albertel 11331:     }
                   11332: }
                   11333: 
1.691     raeburn  11334: sub check_group_parms {
1.1301    raeburn  11335:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11336:         $recursed,$recurseupref) = @_;
                   11337:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11338:                   [$what,'course']);
                   11339:     my $coursereply;
1.691     raeburn  11340:     foreach my $group (@{$groups}) {
1.1301    raeburn  11341:         my @groupitems = ();
1.691     raeburn  11342:         foreach my $level (@levels) {
1.927     albertel 11343:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11344:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11345:         }
1.1301    raeburn  11346:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11347:                                    $env{'course.'.$courseid.'.domain'},
                   11348:                                    'course',$mapp,$recursed,$recurseupref,
                   11349:                                    $courseid,'.['.$group.'].',$what,
                   11350:                                    @groupitems);
                   11351:         last if (defined($coursereply));
1.691     raeburn  11352:     }
                   11353:     return $coursereply;
                   11354: }
                   11355: 
1.1301    raeburn  11356: sub get_map_hierarchy {
1.1302    raeburn  11357:     my ($mapname,$courseid) = @_;
                   11358:     my @recurseup = ();
1.1301    raeburn  11359:     if ($mapname) {
1.1302    raeburn  11360:         if (($cachedmapkey eq $courseid) &&
                   11361:             (abs($cachedmaptime-time)<5)) {
                   11362:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11363:                 return @{$cachedmaps{$mapname}};
                   11364:             }
                   11365:         }
1.1301    raeburn  11366:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11367:         if (ref($navmap)) {
                   11368:             @recurseup = $navmap->recurseup_maps($mapname);
                   11369:             undef($navmap);
1.1302    raeburn  11370:             $cachedmaps{$mapname} = \@recurseup;
                   11371:             $cachedmaptime=time;
                   11372:             $cachedmapkey=$courseid;
1.1301    raeburn  11373:         }
                   11374:     }
                   11375:     return @recurseup;
                   11376: }
                   11377: 
1.1302    raeburn  11378: }
                   11379: 
1.691     raeburn  11380: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11381:     my ($courseid,@groups) = @_;
                   11382:     @groups = sort(@groups);
1.691     raeburn  11383:     return @groups;
                   11384: }
                   11385: 
1.395     albertel 11386: sub packages_tab_default {
                   11387:     my ($uri,$varname)=@_;
                   11388:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11389: 
                   11390:     my (@extension,@specifics,$do_default);
                   11391:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11392: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11393: 	if ($pack_type eq 'default') {
                   11394: 	    $do_default=1;
                   11395: 	} elsif ($pack_type eq 'extension') {
                   11396: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11397: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11398: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11399: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11400: 	}
                   11401:     }
                   11402:     # first look for a package that matches the requested part id
                   11403:     foreach my $package (@specifics) {
                   11404: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11405: 	next if ($pack_part ne $part);
                   11406: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11407: 	    return $packagetab{"$pack_type&$name&default"};
                   11408: 	}
                   11409:     }
                   11410:     # look for any possible matching non extension_ package
                   11411:     foreach my $package (@specifics) {
                   11412: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11413: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11414: 	    return $packagetab{"$pack_type&$name&default"};
                   11415: 	}
1.585     albertel 11416: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11417: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11418: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11419: 	}
                   11420:     }
1.738     albertel 11421:     # look for any posible extension_ match
                   11422:     foreach my $package (@extension) {
                   11423: 	my ($package,$pack_type)=@{$package};
                   11424: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11425: 	    return $packagetab{"$pack_type&$name&default"};
                   11426: 	}
                   11427: 	if (defined($packagetab{$package."&$name&default"})) {
                   11428: 	    return $packagetab{$package."&$name&default"};
                   11429: 	}
                   11430:     }
                   11431:     # look for a global default setting
                   11432:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11433: 	return $packagetab{"default&$name&default"};
                   11434:     }
1.395     albertel 11435:     return undef;
                   11436: }
                   11437: 
1.334     albertel 11438: sub add_prefix_and_part {
                   11439:     my ($prefix,$part)=@_;
                   11440:     my $keyroot;
                   11441:     if (defined($prefix) && $prefix !~ /^__/) {
                   11442: 	# prefix that has a part already
                   11443: 	$keyroot=$prefix;
                   11444:     } elsif (defined($prefix)) {
                   11445: 	# prefix that is missing a part
                   11446: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11447:     } else {
                   11448: 	# no prefix at all
                   11449: 	if (defined($part)) { $keyroot='_'.$part; }
                   11450:     }
                   11451:     return $keyroot;
                   11452: }
                   11453: 
1.71      www      11454: # ---------------------------------------------------------------- Get metadata
                   11455: 
1.599     albertel 11456: my %metaentry;
1.1070    www      11457: my %importedpartids;
1.71      www      11458: sub metadata {
1.176     www      11459:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11460:     $uri=&declutter($uri);
1.288     albertel 11461:     # if it is a non metadata possible uri return quickly
1.529     albertel 11462:     if (($uri eq '') || 
                   11463: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11464: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11465:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11466: 	return undef;
                   11467:     }
1.1261    raeburn  11468:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11469: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11470: 	return undef;
1.288     albertel 11471:     }
1.73      www      11472:     my $filename=$uri;
                   11473:     $uri=~s/\.meta$//;
1.172     www      11474: #
                   11475: # Is the metadata already cached?
1.177     www      11476: # Look at timestamp of caching
1.172     www      11477: # Everything is cached by the main uri, libraries are never directly cached
                   11478: #
1.428     albertel 11479:     if (!defined($liburi)) {
1.599     albertel 11480: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11481: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11482:     }
                   11483:     {
1.1069    www      11484: # Imported parts would go here
1.1070    www      11485:         my %importedids=();
                   11486:         my @origfileimportpartids=();
1.1069    www      11487:         my $importedparts=0;
1.172     www      11488: #
                   11489: # Is this a recursive call for a library?
                   11490: #
1.599     albertel 11491: #	if (! exists($metacache{$uri})) {
                   11492: #	    $metacache{$uri}={};
                   11493: #	}
1.924     albertel 11494: 	my $cachetime = 60*60;
1.171     www      11495:         if ($liburi) {
                   11496: 	    $liburi=&declutter($liburi);
                   11497:             $filename=$liburi;
1.401     bowersj2 11498:         } else {
1.599     albertel 11499: 	    &devalidate_cache_new('meta',$uri);
                   11500: 	    undef(%metaentry);
1.401     bowersj2 11501: 	}
1.140     www      11502:         my %metathesekeys=();
1.73      www      11503:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11504: 	my $metastring;
1.1140    www      11505: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11506: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11507: 	    $metastring = 
1.929     albertel 11508: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11509: 					  ('grade_target' => 'meta'));
                   11510: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11511: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11512:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11513: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11514: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11515: 	    $metastring=&getfile($file);
1.489     albertel 11516: 	}
1.208     albertel 11517:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11518:         my $token;
1.140     www      11519:         undef %metathesekeys;
1.71      www      11520:         while ($token=$parser->get_token) {
1.339     albertel 11521: 	    if ($token->[0] eq 'S') {
                   11522: 		if (defined($token->[2]->{'package'})) {
1.172     www      11523: #
                   11524: # This is a package - get package info
                   11525: #
1.339     albertel 11526: 		    my $package=$token->[2]->{'package'};
                   11527: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11528: 		    if (defined($token->[2]->{'id'})) { 
                   11529: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11530: 		    }
1.599     albertel 11531: 		    if ($metaentry{':packages'}) {
                   11532: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11533: 		    } else {
1.599     albertel 11534: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11535: 		    }
1.736     albertel 11536: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11537: 			my $part=$keyroot;
                   11538: 			$part=~s/^\_//;
1.736     albertel 11539: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11540: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11541: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11542: 			    # ignore package.tab specified default values
                   11543:                             # here &package_tab_default() will fetch those
                   11544: 			    if ($subp eq 'default') { next; }
1.736     albertel 11545: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11546: 			    my $unikey;
                   11547: 			    if ($pack =~ /_0$/) {
                   11548: 				$unikey='parameter_0_'.$name;
                   11549: 				$part=0;
                   11550: 			    } else {
                   11551: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11552: 			    }
1.339     albertel 11553: 			    if ($subp eq 'display') {
                   11554: 				$value.=' [Part: '.$part.']';
                   11555: 			    }
1.599     albertel 11556: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11557: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11558: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11559: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11560: 			    }
1.599     albertel 11561: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11562: 				$metaentry{':'.$unikey}=
                   11563: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11564: 			    }
1.339     albertel 11565: 			}
                   11566: 		    }
                   11567: 		} else {
1.172     www      11568: #
                   11569: # This is not a package - some other kind of start tag
1.339     albertel 11570: #
                   11571: 		    my $entry=$token->[1];
1.1068    www      11572: 		    my $unikey='';
1.175     www      11573: 
1.339     albertel 11574: 		    if ($entry eq 'import') {
1.175     www      11575: #
                   11576: # Importing a library here
1.339     albertel 11577: #
1.1067    www      11578:                         my $location=$parser->get_text('/import');
                   11579:                         my $dir=$filename;
                   11580:                         $dir=~s|[^/]*$||;
                   11581:                         $location=&filelocation($dir,$location);
1.1069    www      11582:                        
1.1068    www      11583:                         my $importmode=$token->[2]->{'importmode'};
                   11584:                         if ($importmode eq 'problem') {
1.1069    www      11585: # Import as problem/response
1.1068    www      11586:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11587:                         } elsif ($importmode eq 'part') {
                   11588: # Import as part(s)
1.1069    www      11589:                            $importedparts=1;
                   11590: # We need to get the original file and the imported file to get the part order correct
                   11591: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11592: # Load and inspect original file
1.1070    www      11593:                            if ($#origfileimportpartids<0) {
                   11594:                               undef(%importedpartids);
                   11595:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11596:                               my $origfile=&getfile($origfilelocation);
                   11597:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11598:                            }
                   11599: 
1.1069    www      11600: # Load and inspect imported file
                   11601:                            my $impfile=&getfile($location);
                   11602:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11603:                            if ($#impfilepartids>=0) {
                   11604: # This problem had parts
1.1070    www      11605:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11606:                            } else {
                   11607: # Importing by turning a single problem into a problem part
                   11608: # It gets the import-tags ID as part-ID
                   11609:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11610:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11611:                            }
1.1068    www      11612:                         } else {
                   11613: # Normal import
                   11614:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11615:                            if (defined($token->[2]->{'id'})) {
                   11616:                               $unikey.='_'.$token->[2]->{'id'};
                   11617:                            }
1.1067    www      11618:                         }
                   11619: 
1.339     albertel 11620: 			if ($depthcount<20) {
1.736     albertel 11621: 			    my $metadata = 
                   11622: 				&metadata($uri,'keys', $location,$unikey,
                   11623: 					  $depthcount+1);
                   11624: 			    foreach my $meta (split(',',$metadata)) {
                   11625: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11626: 				$metathesekeys{$meta}=1;
1.339     albertel 11627: 			    }
1.1068    www      11628: 			
                   11629:                         }
1.1067    www      11630: 		    } else {
                   11631: #
                   11632: # Not importing, some other kind of non-package, non-library start tag
                   11633: # 
                   11634:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11635:                         if (defined($token->[2]->{'id'})) {
                   11636:                             $unikey.='_'.$token->[2]->{'id'};
                   11637:                         }
1.339     albertel 11638: 			if (defined($token->[2]->{'name'})) { 
                   11639: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11640: 			}
                   11641: 			$metathesekeys{$unikey}=1;
1.736     albertel 11642: 			foreach my $param (@{$token->[3]}) {
                   11643: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11644: 				$token->[2]->{$param};
1.339     albertel 11645: 			}
                   11646: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11647: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11648: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11649: 		 # only ws inside the tag, and not in default, so use default
                   11650: 		 # as value
1.599     albertel 11651: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11652: 			} elsif ( $internaltext =~ /\S/ ) {
                   11653: 		  # something interesting inside the tag
                   11654: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11655: 			} else {
1.908     albertel 11656: 		  # no interesting values, don't set a default
1.339     albertel 11657: 			}
1.172     www      11658: # end of not-a-package not-a-library import
1.339     albertel 11659: 		    }
1.172     www      11660: # end of not-a-package start tag
1.339     albertel 11661: 		}
1.172     www      11662: # the next is the end of "start tag"
1.339     albertel 11663: 	    }
                   11664: 	}
1.483     albertel 11665: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11666: 	$extension = lc($extension);
                   11667: 	if ($extension eq 'htm') { $extension='html'; }
                   11668: 
1.737     albertel 11669: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11670: 	    #no specific packages #how's our extension
                   11671: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11672: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11673: 					 \%metathesekeys);
                   11674: 	}
1.883     albertel 11675: 
                   11676: 	if (!exists($metaentry{':packages'})
                   11677: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11678: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11679: 		#no specific packages well let's get default then
                   11680: 		if ($key!~/^default&/) { next; }
1.488     albertel 11681: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11682: 					     \%metathesekeys);
                   11683: 	    }
                   11684: 	}
1.338     www      11685: # are there custom rights to evaluate
1.599     albertel 11686: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11687: 
1.338     www      11688:     #
                   11689:     # Importing a rights file here
1.339     albertel 11690:     #
                   11691: 	    unless ($depthcount) {
1.599     albertel 11692: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11693: 		my $dir=$filename;
                   11694: 		$dir=~s|[^/]*$||;
                   11695: 		$location=&filelocation($dir,$location);
1.736     albertel 11696: 		my $rights_metadata =
                   11697: 		    &metadata($uri,'keys',$location,'_rights',
                   11698: 			      $depthcount+1);
                   11699: 		foreach my $rights (split(',',$rights_metadata)) {
                   11700: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11701: 		    $metathesekeys{$rights}=1;
1.339     albertel 11702: 		}
                   11703: 	    }
                   11704: 	}
1.737     albertel 11705: 	# uniqifiy package listing
                   11706: 	my %seen;
                   11707: 	my @uniq_packages =
                   11708: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11709: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11710: 
1.1070    www      11711:         if ($importedparts) {
                   11712: # We had imported parts and need to rebuild partorder
                   11713:            $metaentry{':partorder'}='';
                   11714:            $metathesekeys{'partorder'}=1;
                   11715:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11716:                if ($origfileimportpartids[$index] eq 'part') {
                   11717: # original part, part of the problem
                   11718:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11719:                } else {
                   11720: # we have imported parts at this position
                   11721:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11722:                }
                   11723:            }
                   11724:            $metaentry{':partorder'}=~s/^\,//;
                   11725:         }
                   11726: 
1.737     albertel 11727: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11728: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11729: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11730: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11731: # this is the end of "was not already recently cached
1.71      www      11732:     }
1.599     albertel 11733:     return $metaentry{':'.$what};
1.261     albertel 11734: }
                   11735: 
1.488     albertel 11736: sub metadata_create_package_def {
1.483     albertel 11737:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11738:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11739:     if ($subp eq 'default') { next; }
                   11740:     
1.599     albertel 11741:     if (defined($metaentry{':packages'})) {
                   11742: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11743:     } else {
1.599     albertel 11744: 	$metaentry{':packages'}=$package;
1.483     albertel 11745:     }
                   11746:     my $value=$packagetab{$key};
                   11747:     my $unikey;
                   11748:     $unikey='parameter_0_'.$name;
1.599     albertel 11749:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11750:     $$metathesekeys{$unikey}=1;
1.599     albertel 11751:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11752: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11753:     }
1.599     albertel 11754:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11755: 	$metaentry{':'.$unikey}=
                   11756: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11757:     }
                   11758: }
                   11759: 
1.261     albertel 11760: sub metadata_generate_part0 {
                   11761:     my ($metadata,$metacache,$uri) = @_;
                   11762:     my %allnames;
1.737     albertel 11763:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11764: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11765: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11766: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11767: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11768: 	    $allnames{$name}=$part;
                   11769: 	  }
                   11770: 	}
                   11771:     }
                   11772:     foreach my $name (keys(%allnames)) {
                   11773:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11774:       my $key=":parameter_0_$name";
1.261     albertel 11775:       $$metacache{"$key.part"}='0';
                   11776:       $$metacache{"$key.name"}=$name;
1.428     albertel 11777:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11778: 					   $allnames{$name}.'_'.$name.
                   11779: 					   '.type'};
1.428     albertel 11780:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11781: 			     '.display'};
1.644     www      11782:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11783:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11784:       $$metacache{"$key.display"}=$olddis;
                   11785:     }
1.71      www      11786: }
                   11787: 
1.764     albertel 11788: # ------------------------------------------------------ Devalidate title cache
                   11789: 
                   11790: sub devalidate_title_cache {
                   11791:     my ($url)=@_;
                   11792:     if (!$env{'request.course.id'}) { return; }
                   11793:     my $symb=&symbread($url);
                   11794:     if (!$symb) { return; }
                   11795:     my $key=$env{'request.course.id'}."\0".$symb;
                   11796:     &devalidate_cache_new('title',$key);
                   11797: }
                   11798: 
1.1014    droeschl 11799: # ------------------------------------------------- Get the title of a course
                   11800: 
                   11801: sub current_course_title {
                   11802:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11803: }
1.301     www      11804: # ------------------------------------------------- Get the title of a resource
                   11805: 
                   11806: sub gettitle {
                   11807:     my $urlsymb=shift;
                   11808:     my $symb=&symbread($urlsymb);
1.534     albertel 11809:     if ($symb) {
1.620     albertel 11810: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11811: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11812: 	if (defined($cached)) { 
                   11813: 	    return $result;
                   11814: 	}
1.534     albertel 11815: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11816: 	my $title='';
1.907     albertel 11817: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11818: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11819: 	} else {
                   11820: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11821: 		    &GDBM_READER(),0640)) {
                   11822: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11823: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11824: 		untie(%bighash);
                   11825: 	    }
1.534     albertel 11826: 	}
                   11827: 	$title=~s/\&colon\;/\:/gs;
                   11828: 	if ($title) {
1.1159    www      11829: # Remember both $symb and $title for dynamic metadata
                   11830:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11831:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11832: # Cache this title and then return it
1.599     albertel 11833: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11834: 	}
                   11835: 	$urlsymb=$url;
                   11836:     }
                   11837:     my $title=&metadata($urlsymb,'title');
                   11838:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11839:     return $title;
1.301     www      11840: }
1.613     albertel 11841: 
1.614     albertel 11842: sub get_slot {
                   11843:     my ($which,$cnum,$cdom)=@_;
                   11844:     if (!$cnum || !$cdom) {
1.790     albertel 11845: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11846: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11847: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11848:     }
1.703     albertel 11849:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11850:     my %slotinfo;
                   11851:     if (exists($remembered{$key})) {
                   11852: 	$slotinfo{$which} = $remembered{$key};
                   11853:     } else {
                   11854: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11855: 	&Apache::lonhomework::showhash(%slotinfo);
                   11856: 	my ($tmp)=keys(%slotinfo);
                   11857: 	if ($tmp=~/^error:/) { return (); }
                   11858: 	$remembered{$key} = $slotinfo{$which};
                   11859:     }
1.616     albertel 11860:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11861: 	return %{$slotinfo{$which}};
                   11862:     }
                   11863:     return $slotinfo{$which};
1.614     albertel 11864: }
1.1150    raeburn  11865: 
                   11866: sub get_reservable_slots {
                   11867:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11868:     my $now = time;
                   11869:     my $reservable_info;
                   11870:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11871:     if (exists($remembered{$key})) {
                   11872:         $reservable_info = $remembered{$key};
                   11873:     } else {
                   11874:         my %resv;
                   11875:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11876:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11877:         $reservable_info = \%resv;
                   11878:         $remembered{$key} = $reservable_info;
                   11879:     }
                   11880:     return $reservable_info;
                   11881: }
                   11882: 
                   11883: sub get_course_slots {
                   11884:     my ($cnum,$cdom) = @_;
                   11885:     my $hashid=$cnum.':'.$cdom;
                   11886:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11887:     if (defined($cached)) {
                   11888:         if (ref($result) eq 'HASH') {
                   11889:             return %{$result};
                   11890:         }
                   11891:     } else {
                   11892:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11893:         my ($tmp) = keys(%slots);
                   11894:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11895:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11896:             return %slots;
                   11897:         }
                   11898:     }
                   11899:     return;
                   11900: }
                   11901: 
                   11902: sub devalidate_slots_cache {
                   11903:     my ($cnum,$cdom)=@_;
                   11904:     my $hashid=$cnum.':'.$cdom;
                   11905:     &devalidate_cache_new('allslots',$hashid);
                   11906: }
                   11907: 
1.1181    raeburn  11908: sub get_coursechange {
                   11909:     my ($cdom,$cnum) = @_;
                   11910:     if ($cdom eq '' || $cnum eq '') {
                   11911:         return unless ($env{'request.course.id'});
                   11912:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11913:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11914:     }
                   11915:     my $hashid=$cdom.'_'.$cnum;
                   11916:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11917:     if ((defined($cached)) && ($change ne '')) {
                   11918:         return $change;
                   11919:     } else {
                   11920:         my %crshash;
                   11921:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11922:         if ($crshash{'internal.contentchange'} eq '') {
                   11923:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11924:             if ($change eq '') {
                   11925:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11926:                 $change = $crshash{'internal.created'};
                   11927:             }
                   11928:         } else {
                   11929:             $change = $crshash{'internal.contentchange'};
                   11930:         }
                   11931:         my $cachetime = 600;
                   11932:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11933:     }
                   11934:     return $change;
                   11935: }
                   11936: 
                   11937: sub devalidate_coursechange_cache {
                   11938:     my ($cnum,$cdom)=@_;
                   11939:     my $hashid=$cnum.':'.$cdom;
                   11940:     &devalidate_cache_new('crschange',$hashid);
                   11941: }
                   11942: 
1.31      www      11943: # ------------------------------------------------- Update symbolic store links
                   11944: 
                   11945: sub symblist {
                   11946:     my ($mapname,%newhash)=@_;
1.438     www      11947:     $mapname=&deversion(&declutter($mapname));
1.31      www      11948:     my %hash;
1.620     albertel 11949:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11950:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11951:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11952: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11953: 		next if ($url eq 'last_known'
                   11954: 			 && $env{'form.no_update_last_known'});
                   11955: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11956: 						    $newhash{$url}->[1],
                   11957: 						    $newhash{$url}->[0]);
1.191     harris41 11958:             }
1.31      www      11959:             if (untie(%hash)) {
                   11960: 		return 'ok';
                   11961:             }
                   11962:         }
                   11963:     }
                   11964:     return 'error';
1.212     www      11965: }
                   11966: 
                   11967: # --------------------------------------------------------------- Verify a symb
                   11968: 
                   11969: sub symbverify {
1.1190    raeburn  11970:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11971:     my $thisfn=$thisurl;
1.439     www      11972:     $thisfn=&declutter($thisfn);
1.215     www      11973: # direct jump to resource in page or to a sequence - will construct own symbs
                   11974:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11975: # check URL part
1.409     www      11976:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11977: 
1.431     www      11978:     unless ($url eq $thisfn) { return 0; }
1.213     www      11979: 
1.216     www      11980:     $symb=&symbclean($symb);
1.510     www      11981:     $thisurl=&deversion($thisurl);
1.439     www      11982:     $thisfn=&deversion($thisfn);
1.213     www      11983: 
                   11984:     my %bighash;
                   11985:     my $okay=0;
1.431     www      11986: 
1.620     albertel 11987:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11988:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11989:         my $noclutter;
1.1032    raeburn  11990:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11991:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11992:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11993:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11994:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11995:                 $noclutter = 1;
                   11996:             }
                   11997:         }
                   11998:         my $ids;
                   11999:         if ($noclutter) {
                   12000:             $ids=$bighash{'ids_'.$thisurl};
                   12001:         } else {
                   12002:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12003:         }
1.1102    raeburn  12004:         unless ($ids) {
                   12005:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12006:             $ids=$bighash{$idkey};
1.216     www      12007:         }
                   12008:         if ($ids) {
                   12009: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12010:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12011:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12012:             }
1.800     albertel 12013: 	    foreach my $id (split(/\,/,$ids)) {
                   12014: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12015:                if (
                   12016:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12017:    eq $symb) {
                   12018:                    if (ref($encstate)) {
                   12019:                        $$encstate = $bighash{'encrypted_'.$id};
                   12020:                    }
1.620     albertel 12021: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12022: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12023:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12024: 		       $okay=1;
1.1202    raeburn  12025:                        last;
1.582     albertel 12026: 		   }
                   12027: 	       }
1.216     www      12028: 	   }
                   12029:         }
1.213     www      12030: 	untie(%bighash);
                   12031:     }
                   12032:     return $okay;
1.31      www      12033: }
                   12034: 
1.210     www      12035: # --------------------------------------------------------------- Clean-up symb
                   12036: 
                   12037: sub symbclean {
                   12038:     my $symb=shift;
1.568     albertel 12039:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12040: # remove version from map
                   12041:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12042: 
1.210     www      12043: # remove version from URL
                   12044:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12045: 
1.507     www      12046: # remove wrapper
                   12047: 
1.510     www      12048:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12049:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12050:     return $symb;
1.409     www      12051: }
                   12052: 
                   12053: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12054: 
                   12055: sub encode_symb {
                   12056:     my ($map,$resid,$url)=@_;
                   12057:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12058: }
1.409     www      12059: 
                   12060: sub decode_symb {
1.568     albertel 12061:     my $symb=shift;
                   12062:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12063:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12064:     return (&fixversion($map),$resid,&fixversion($url));
                   12065: }
                   12066: 
                   12067: sub fixversion {
                   12068:     my $fn=shift;
1.609     banghart 12069:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12070:     my %bighash;
                   12071:     my $uri=&clutter($fn);
1.620     albertel 12072:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12073: # is this cached?
1.599     albertel 12074:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12075:     if (defined($cached)) { return $result; }
                   12076: # unfortunately not cached, or expired
1.620     albertel 12077:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12078: 	    &GDBM_READER(),0640)) {
                   12079:  	if ($bighash{'version_'.$uri}) {
                   12080:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12081:  	    unless (($version eq 'mostrecent') || 
                   12082: 		    ($version==&getversion($uri))) {
1.440     www      12083:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12084:  	    }
                   12085:  	}
                   12086:  	untie %bighash;
1.413     www      12087:     }
1.599     albertel 12088:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12089: }
                   12090: 
                   12091: sub deversion {
                   12092:     my $url=shift;
                   12093:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12094:     return $url;
1.210     www      12095: }
                   12096: 
1.31      www      12097: # ------------------------------------------------------ Return symb list entry
                   12098: 
                   12099: sub symbread {
1.1282    raeburn  12100:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12101:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12102:     if (defined($env{$cache_str})) {
                   12103:         if ($ignorecachednull) {
                   12104:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12105:         } else {
                   12106:             return $env{$cache_str};
                   12107:         }
                   12108:     }
1.242     www      12109: # no filename provided? try from environment
1.1265    raeburn  12110:     unless ($thisfn) {
1.620     albertel 12111:         if ($env{'request.symb'}) {
                   12112: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12113: 	}
1.620     albertel 12114: 	$thisfn=$env{'request.filename'};
1.44      www      12115:     }
1.569     albertel 12116:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12117: # is that filename actually a symb? Verify, clean, and return
                   12118:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12119: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12120: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12121: 	}
1.242     www      12122:     }
1.44      www      12123:     $thisfn=declutter($thisfn);
1.31      www      12124:     my %hash;
1.37      www      12125:     my %bighash;
                   12126:     my $syval='';
1.620     albertel 12127:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12128:         my $targetfn = $thisfn;
1.609     banghart 12129:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12130:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12131:         }
1.687     albertel 12132: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12133: 	    $targetfn=$1;
                   12134: 	}
1.620     albertel 12135:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12136:                       &GDBM_READER(),0640)) {
1.481     raeburn  12137: 	    $syval=$hash{$targetfn};
1.37      www      12138:             untie(%hash);
                   12139:         }
                   12140: # ---------------------------------------------------------- There was an entry
                   12141:         if ($syval) {
1.601     albertel 12142: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12143: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12144: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12145: 		    #return $env{$cache_str}='';
1.601     albertel 12146: 		#}    
                   12147: 		#$syval.=$1;
                   12148: 	    #}
1.37      www      12149:         } else {
                   12150: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12151:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12152:                             &GDBM_READER(),0640)) {
1.37      www      12153: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12154:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12155:               unless ($ids) { 
                   12156:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12157:               }
                   12158:               unless ($ids) {
                   12159: # alias?
                   12160: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12161:               }
1.37      www      12162:               if ($ids) {
                   12163: # ------------------------------------------------------------------- Has ID(s)
                   12164:                  my @possibilities=split(/\,/,$ids);
1.39      www      12165:                  if ($#possibilities==0) {
                   12166: # ----------------------------------------------- There is only one possibility
1.37      www      12167: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12168: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12169: 						    $resid,$thisfn);
1.1282    raeburn  12170:                      if (ref($possibles) eq 'HASH') {
                   12171:                          $possibles->{$syval} = 1;    
                   12172:                      }
                   12173:                      if ($checkforblock) {
                   12174:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12175:                          if (@blockers) {
                   12176:                              $syval = '';
                   12177:                              return;
                   12178:                          }
                   12179:                      }
                   12180:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12181: # ------------------------------------------ There is more than one possibility
                   12182:                      my $realpossible=0;
1.800     albertel 12183:                      foreach my $id (@possibilities) {
                   12184: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12185:                          my $canaccess;
                   12186:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12187:                              $canaccess = 1;
                   12188:                          } else { 
                   12189:                              $canaccess = &allowed('bre',$file);
                   12190:                          }
                   12191:                          if ($canaccess) {
                   12192:          		     my ($mapid,$resid)=split(/\./,$id);
                   12193:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12194:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12195: 						             $resid,$thisfn);
                   12196:                                  if (ref($possibles) eq 'HASH') {
                   12197:                                      $possibles->{$syval} = 1;
                   12198:                                  }
                   12199:                                  if ($checkforblock) {
                   12200:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12201:                                      unless (@blockers > 0) {
                   12202:                                          $syval = $poss_syval;
                   12203:                                          $realpossible++;
                   12204:                                      }
                   12205:                                  } else {
                   12206:                                      $syval = $poss_syval;
                   12207:                                      $realpossible++;
                   12208:                                  }
                   12209:                              }
1.39      www      12210: 			 }
1.191     harris41 12211:                      }
1.39      www      12212: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12213:                  } else {
                   12214:                      $syval='';
1.37      www      12215:                  }
                   12216: 	      }
1.1282    raeburn  12217:               untie(%bighash);
1.481     raeburn  12218:            }
1.31      www      12219:         }
1.62      www      12220:         if ($syval) {
1.620     albertel 12221: 	    return $env{$cache_str}=$syval;
1.62      www      12222:         }
1.31      www      12223:     }
1.949     raeburn  12224:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12225:     return $env{$cache_str}='';
1.31      www      12226: }
                   12227: 
                   12228: # ---------------------------------------------------------- Return random seed
                   12229: 
1.32      www      12230: sub numval {
                   12231:     my $txt=shift;
                   12232:     $txt=~tr/A-J/0-9/;
                   12233:     $txt=~tr/a-j/0-9/;
                   12234:     $txt=~tr/K-T/0-9/;
                   12235:     $txt=~tr/k-t/0-9/;
                   12236:     $txt=~tr/U-Z/0-5/;
                   12237:     $txt=~tr/u-z/0-5/;
                   12238:     $txt=~s/\D//g;
1.564     albertel 12239:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12240:     return int($txt);
1.368     albertel 12241: }
                   12242: 
1.484     albertel 12243: sub numval2 {
                   12244:     my $txt=shift;
                   12245:     $txt=~tr/A-J/0-9/;
                   12246:     $txt=~tr/a-j/0-9/;
                   12247:     $txt=~tr/K-T/0-9/;
                   12248:     $txt=~tr/k-t/0-9/;
                   12249:     $txt=~tr/U-Z/0-5/;
                   12250:     $txt=~tr/u-z/0-5/;
                   12251:     $txt=~s/\D//g;
                   12252:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12253:     my $total;
                   12254:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12255:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12256:     return int($total);
                   12257: }
                   12258: 
1.575     albertel 12259: sub numval3 {
                   12260:     use integer;
                   12261:     my $txt=shift;
                   12262:     $txt=~tr/A-J/0-9/;
                   12263:     $txt=~tr/a-j/0-9/;
                   12264:     $txt=~tr/K-T/0-9/;
                   12265:     $txt=~tr/k-t/0-9/;
                   12266:     $txt=~tr/U-Z/0-5/;
                   12267:     $txt=~tr/u-z/0-5/;
                   12268:     $txt=~s/\D//g;
                   12269:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12270:     my $total;
                   12271:     foreach my $val (@txts) { $total+=$val; }
                   12272:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12273:     return $total;
                   12274: }
                   12275: 
1.675     albertel 12276: sub digest {
                   12277:     my ($data)=@_;
                   12278:     my $digest=&Digest::MD5::md5($data);
                   12279:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12280:     my ($e,$f);
                   12281:     {
                   12282:         use integer;
                   12283:         $e=($a+$b);
                   12284:         $f=($c+$d);
                   12285:         if ($_64bit) {
                   12286:             $e=(($e<<32)>>32);
                   12287:             $f=(($f<<32)>>32);
                   12288:         }
                   12289:     }
                   12290:     if (wantarray) {
                   12291: 	return ($e,$f);
                   12292:     } else {
                   12293: 	my $g;
                   12294: 	{
                   12295: 	    use integer;
                   12296: 	    $g=($e+$f);
                   12297: 	    if ($_64bit) {
                   12298: 		$g=(($g<<32)>>32);
                   12299: 	    }
                   12300: 	}
                   12301: 	return $g;
                   12302:     }
                   12303: }
                   12304: 
1.368     albertel 12305: sub latest_rnd_algorithm_id {
1.675     albertel 12306:     return '64bit5';
1.366     albertel 12307: }
1.32      www      12308: 
1.503     albertel 12309: sub get_rand_alg {
                   12310:     my ($courseid)=@_;
1.790     albertel 12311:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12312:     if ($courseid) {
1.620     albertel 12313: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12314:     }
                   12315:     return &latest_rnd_algorithm_id();
                   12316: }
                   12317: 
1.562     albertel 12318: sub validCODE {
                   12319:     my ($CODE)=@_;
                   12320:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12321:     return 0;
                   12322: }
                   12323: 
1.491     albertel 12324: sub getCODE {
1.620     albertel 12325:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12326:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12327: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12328: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12329: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12330:     }
                   12331:     return undef;
                   12332: }
1.1133    foxr     12333: #
                   12334: #  Determines the random seed for a specific context:
                   12335: #
                   12336: # parameters:
                   12337: #   symb      - in course context the symb for the seed.
                   12338: #   course_id - The course id of the form domain_coursenum.
                   12339: #   domain    - Domain for the user.
                   12340: #   course    - Course for the user.
                   12341: #   cenv      - environment of the course.
                   12342: #
                   12343: # NOTE:
                   12344: #   All parameters are picked out of the environment if missing
                   12345: #   or not defined.
                   12346: #   If a symb cannot be determined the current time is used instead.
                   12347: #
                   12348: #  For a given well defined symb, courside, domain, username,
                   12349: #  and course environment, the seed is reproducible.
                   12350: #
1.31      www      12351: sub rndseed {
1.1133    foxr     12352:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12353:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12354:     if (!defined($symb)) {
1.366     albertel 12355: 	unless ($symb=$wsymb) { return time; }
                   12356:     }
1.1146    foxr     12357:     if (!defined $courseid) { 
                   12358: 	$courseid=$wcourseid; 
                   12359:     }
                   12360:     if (!defined $domain) { $domain=$wdomain; }
                   12361:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12362: 
                   12363:     my $which;
                   12364:     if (defined($cenv->{'rndseed'})) {
                   12365: 	$which = $cenv->{'rndseed'};
                   12366:     } else {
                   12367: 	$which =&get_rand_alg($courseid);
                   12368:     }
1.491     albertel 12369:     if (defined(&getCODE())) {
1.1133    foxr     12370: 
1.675     albertel 12371: 	if ($which eq '64bit5') {
                   12372: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12373: 	} elsif ($which eq '64bit4') {
1.575     albertel 12374: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12375: 	} else {
                   12376: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12377: 	}
1.675     albertel 12378:     } elsif ($which eq '64bit5') {
                   12379: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12380:     } elsif ($which eq '64bit4') {
                   12381: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12382:     } elsif ($which eq '64bit3') {
                   12383: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12384:     } elsif ($which eq '64bit2') {
                   12385: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12386:     } elsif ($which eq '64bit') {
                   12387: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12388:     }
                   12389:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12390: }
                   12391: 
                   12392: sub rndseed_32bit {
                   12393:     my ($symb,$courseid,$domain,$username)=@_;
                   12394:     {
                   12395: 	use integer;
                   12396: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12397: 	my $symbseed=numval($symb) << 22;
                   12398: 	my $namechck=unpack("%32C*",$username) << 17;
                   12399: 	my $nameseed=numval($username) << 12;
                   12400: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12401: 	my $courseseed=unpack("%32C*",$courseid);
                   12402: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12403: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12404: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12405: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12406: 	return $num;
                   12407:     }
                   12408: }
                   12409: 
                   12410: sub rndseed_64bit {
                   12411:     my ($symb,$courseid,$domain,$username)=@_;
                   12412:     {
                   12413: 	use integer;
                   12414: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12415: 	my $symbseed=numval($symb) << 10;
                   12416: 	my $namechck=unpack("%32S*",$username);
                   12417: 	
                   12418: 	my $nameseed=numval($username) << 21;
                   12419: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12420: 	my $courseseed=unpack("%32S*",$courseid);
                   12421: 	
                   12422: 	my $num1=$symbchck+$symbseed+$namechck;
                   12423: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12424: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12425: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12426: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12427: 	return "$num1,$num2";
1.155     albertel 12428:     }
1.366     albertel 12429: }
                   12430: 
1.443     albertel 12431: sub rndseed_64bit2 {
                   12432:     my ($symb,$courseid,$domain,$username)=@_;
                   12433:     {
                   12434: 	use integer;
                   12435: 	# strings need to be an even # of cahracters long, it it is odd the
                   12436:         # last characters gets thrown away
                   12437: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12438: 	my $symbseed=numval($symb) << 10;
                   12439: 	my $namechck=unpack("%32S*",$username.' ');
                   12440: 	
                   12441: 	my $nameseed=numval($username) << 21;
1.501     albertel 12442: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12443: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12444: 	
                   12445: 	my $num1=$symbchck+$symbseed+$namechck;
                   12446: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12447: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12448: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12449: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12450: 	return "$num1,$num2";
                   12451:     }
                   12452: }
                   12453: 
                   12454: sub rndseed_64bit3 {
                   12455:     my ($symb,$courseid,$domain,$username)=@_;
                   12456:     {
                   12457: 	use integer;
                   12458: 	# strings need to be an even # of cahracters long, it it is odd the
                   12459:         # last characters gets thrown away
                   12460: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12461: 	my $symbseed=numval2($symb) << 10;
                   12462: 	my $namechck=unpack("%32S*",$username.' ');
                   12463: 	
                   12464: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12465: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12466: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12467: 	
                   12468: 	my $num1=$symbchck+$symbseed+$namechck;
                   12469: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12470: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12471: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12472: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12473: 	
1.503     albertel 12474: 	return "$num1:$num2";
1.443     albertel 12475:     }
                   12476: }
                   12477: 
1.575     albertel 12478: sub rndseed_64bit4 {
                   12479:     my ($symb,$courseid,$domain,$username)=@_;
                   12480:     {
                   12481: 	use integer;
                   12482: 	# strings need to be an even # of cahracters long, it it is odd the
                   12483:         # last characters gets thrown away
                   12484: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12485: 	my $symbseed=numval3($symb) << 10;
                   12486: 	my $namechck=unpack("%32S*",$username.' ');
                   12487: 	
                   12488: 	my $nameseed=numval3($username) << 21;
                   12489: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12490: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12491: 	
                   12492: 	my $num1=$symbchck+$symbseed+$namechck;
                   12493: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12494: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12495: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12496: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12497: 	
1.575     albertel 12498: 	return "$num1:$num2";
                   12499:     }
                   12500: }
                   12501: 
1.675     albertel 12502: sub rndseed_64bit5 {
                   12503:     my ($symb,$courseid,$domain,$username)=@_;
                   12504:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12505:     return "$num1:$num2";
                   12506: }
                   12507: 
1.366     albertel 12508: sub rndseed_CODE_64bit {
                   12509:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12510:     {
1.366     albertel 12511: 	use integer;
1.443     albertel 12512: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12513: 	my $symbseed=numval2($symb);
1.491     albertel 12514: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12515: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12516: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12517: 	my $num1=$symbseed+$CODEchck;
                   12518: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12519: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12520: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12521: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12522: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12523: 	return "$num1:$num2";
1.366     albertel 12524:     }
                   12525: }
                   12526: 
1.575     albertel 12527: sub rndseed_CODE_64bit4 {
                   12528:     my ($symb,$courseid,$domain,$username)=@_;
                   12529:     {
                   12530: 	use integer;
                   12531: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12532: 	my $symbseed=numval3($symb);
                   12533: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12534: 	my $CODEseed=numval3(&getCODE());
                   12535: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12536: 	my $num1=$symbseed+$CODEchck;
                   12537: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12538: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12539: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12540: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12541: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12542: 	return "$num1:$num2";
                   12543:     }
                   12544: }
                   12545: 
1.675     albertel 12546: sub rndseed_CODE_64bit5 {
                   12547:     my ($symb,$courseid,$domain,$username)=@_;
                   12548:     my $code = &getCODE();
                   12549:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12550:     return "$num1:$num2";
                   12551: }
                   12552: 
1.366     albertel 12553: sub setup_random_from_rndseed {
                   12554:     my ($rndseed)=@_;
1.503     albertel 12555:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12556:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12557:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12558:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12559:         } else {
                   12560:             &Math::Random::random_set_seed($num1,$num2);
                   12561:         }
1.366     albertel 12562:     } else {
                   12563: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12564:     }
1.36      albertel 12565: }
                   12566: 
1.474     albertel 12567: sub latest_receipt_algorithm_id {
1.835     albertel 12568:     return 'receipt3';
1.474     albertel 12569: }
                   12570: 
1.480     www      12571: sub recunique {
                   12572:     my $fucourseid=shift;
                   12573:     my $unique;
1.835     albertel 12574:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12575: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12576: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12577:     } else {
                   12578: 	$unique=$perlvar{'lonReceipt'};
                   12579:     }
                   12580:     return unpack("%32C*",$unique);
                   12581: }
                   12582: 
                   12583: sub recprefix {
                   12584:     my $fucourseid=shift;
                   12585:     my $prefix;
1.835     albertel 12586:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12587: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12588: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12589:     } else {
                   12590: 	$prefix=$perlvar{'lonHostID'};
                   12591:     }
                   12592:     return unpack("%32C*",$prefix);
                   12593: }
                   12594: 
1.76      www      12595: sub ireceipt {
1.474     albertel 12596:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12597: 
                   12598:     my $return =&recprefix($fucourseid).'-';
                   12599: 
                   12600:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12601: 	$env{'request.state'} eq 'construct') {
                   12602: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12603: 	return $return;
                   12604:     }
                   12605: 
1.76      www      12606:     my $cuname=unpack("%32C*",$funame);
                   12607:     my $cudom=unpack("%32C*",$fudom);
                   12608:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12609:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12610:     my $cunique=&recunique($fucourseid);
1.474     albertel 12611:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12612:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12613: 
1.790     albertel 12614: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12615: 			       
                   12616: 	$return.= ($cunique%$cuname+
                   12617: 		   $cunique%$cudom+
                   12618: 		   $cusymb%$cuname+
                   12619: 		   $cusymb%$cudom+
                   12620: 		   $cucourseid%$cuname+
                   12621: 		   $cucourseid%$cudom+
                   12622: 		   $cpart%$cuname+
                   12623: 		   $cpart%$cudom);
                   12624:     } else {
                   12625: 	$return.= ($cunique%$cuname+
                   12626: 		   $cunique%$cudom+
                   12627: 		   $cusymb%$cuname+
                   12628: 		   $cusymb%$cudom+
                   12629: 		   $cucourseid%$cuname+
                   12630: 		   $cucourseid%$cudom);
                   12631:     }
                   12632:     return $return;
1.76      www      12633: }
                   12634: 
                   12635: sub receipt {
1.474     albertel 12636:     my ($part)=@_;
1.790     albertel 12637:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12638:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12639: }
1.260     ng       12640: 
1.790     albertel 12641: sub whichuser {
                   12642:     my ($passedsymb)=@_;
                   12643:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12644:     if (defined($env{'form.grade_symb'})) {
                   12645: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12646: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12647: 	if (!$allowed &&
                   12648: 	    exists($env{'request.course.sec'}) &&
                   12649: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12650: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12651: 			      '/'.$env{'request.course.sec'});
                   12652: 	}
                   12653: 	if ($allowed) {
                   12654: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12655: 	    $courseid=$tmp_courseid;
                   12656: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12657: 	    ($name)=&get_env_multiple('form.grade_username');
                   12658: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12659: 	}
                   12660:     }
                   12661:     if (!$passedsymb) {
                   12662: 	$symb=&symbread();
                   12663:     } else {
                   12664: 	$symb=$passedsymb;
                   12665:     }
                   12666:     $courseid=$env{'request.course.id'};
                   12667:     $domain=$env{'user.domain'};
                   12668:     $name=$env{'user.name'};
                   12669:     if ($name eq 'public' && $domain eq 'public') {
                   12670: 	if (!defined($env{'form.username'})) {
                   12671: 	    $env{'form.username'}.=time.rand(10000000);
                   12672: 	}
                   12673: 	$name.=$env{'form.username'};
                   12674:     }
                   12675:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12676: 
                   12677: }
                   12678: 
1.36      albertel 12679: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12680: # returns either the contents of the file or 
                   12681: # -1 if the file doesn't exist
1.481     raeburn  12682: #
                   12683: # if the target is a file that was uploaded via DOCS, 
                   12684: # a check will be made to see if a current copy exists on the local server,
                   12685: # if it does this will be served, otherwise a copy will be retrieved from
                   12686: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12687: # the local server.   
1.472     albertel 12688: 
1.36      albertel 12689: sub getfile {
1.538     albertel 12690:     my ($file) = @_;
1.609     banghart 12691:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12692:     &repcopy($file);
                   12693:     return &readfile($file);
                   12694: }
                   12695: 
                   12696: sub repcopy_userfile {
                   12697:     my ($file)=@_;
1.1142    raeburn  12698:     my $londocroot = $perlvar{'lonDocRoot'};
                   12699:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12700:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12701:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12702: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12703:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12704:     if (-e "$file") {
1.828     www      12705: # we already have a local copy, check it out
1.538     albertel 12706: 	my @fileinfo = stat($file);
1.828     www      12707: 	my $rtncode;
                   12708: 	my $info;
1.538     albertel 12709: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12710: 	if ($lwpresp ne 'ok') {
1.828     www      12711: # there is no such file anymore, even though we had a local copy
1.482     albertel 12712: 	    if ($rtncode eq '404') {
1.538     albertel 12713: 		unlink($file);
1.482     albertel 12714: 	    }
                   12715: 	    return -1;
                   12716: 	}
                   12717: 	if ($info < $fileinfo[9]) {
1.828     www      12718: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12719: 	    return 'ok';
1.828     www      12720: 	} else {
                   12721: # the file is outdated, get rid of it
                   12722: 	    unlink($file);
1.482     albertel 12723: 	}
1.828     www      12724:     }
                   12725: # one way or the other, at this point, we don't have the file
                   12726: # construct the correct path for the file
                   12727:     my @parts = ($cdom,$cnum); 
                   12728:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12729: 	push @parts, split(/\//,$1);
                   12730:     }
                   12731:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12732:     foreach my $part (@parts) {
                   12733: 	$path .= '/'.$part;
                   12734: 	if (!-e $path) {
                   12735: 	    mkdir($path,0770);
1.482     albertel 12736: 	}
                   12737:     }
1.828     www      12738: # now the path exists for sure
                   12739: # get a user agent
                   12740:     my $ua=new LWP::UserAgent;
                   12741:     my $transferfile=$file.'.in.transfer';
                   12742: # FIXME: this should flock
                   12743:     if (-e $transferfile) { return 'ok'; }
                   12744:     my $request;
                   12745:     $uri=~s/^\///;
1.980     raeburn  12746:     my $homeserver = &homeserver($cnum,$cdom);
                   12747:     my $protocol = $protocol{$homeserver};
                   12748:     $protocol = 'http' if ($protocol ne 'https');
                   12749:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12750:     my $response=$ua->request($request,$transferfile);
                   12751: # did it work?
                   12752:     if ($response->is_error()) {
                   12753: 	unlink($transferfile);
                   12754: 	&logthis("Userfile repcopy failed for $uri");
                   12755: 	return -1;
                   12756:     }
                   12757: # worked, rename the transfer file
                   12758:     rename($transferfile,$file);
1.607     raeburn  12759:     return 'ok';
1.481     raeburn  12760: }
                   12761: 
1.517     albertel 12762: sub tokenwrapper {
                   12763:     my $uri=shift;
1.980     raeburn  12764:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12765:     $uri=~s|^/||;
1.620     albertel 12766:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12767:     my $token=$1;
1.552     albertel 12768:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12769:     if ($udom && $uname && $file) {
                   12770: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12771:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12772:         my $homeserver = &homeserver($uname,$udom);
                   12773:         my $protocol = $protocol{$homeserver};
                   12774:         $protocol = 'http' if ($protocol ne 'https');
                   12775:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12776:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12777:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12778:     } else {
                   12779:         return '/adm/notfound.html';
                   12780:     }
                   12781: }
                   12782: 
1.828     www      12783: # call with reqtype HEAD: get last modification time
                   12784: # call with reqtype GET: get the file contents
                   12785: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12786: #
1.481     raeburn  12787: sub getuploaded {
                   12788:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12789:     $uri=~s/^\///;
1.980     raeburn  12790:     my $homeserver = &homeserver($cnum,$cdom);
                   12791:     my $protocol = $protocol{$homeserver};
                   12792:     $protocol = 'http' if ($protocol ne 'https');
                   12793:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12794:     my $ua=new LWP::UserAgent;
                   12795:     my $request=new HTTP::Request($reqtype,$uri);
                   12796:     my $response=$ua->request($request);
                   12797:     $$rtncode = $response->code;
1.482     albertel 12798:     if (! $response->is_success()) {
                   12799: 	return 'failed';
                   12800:     }      
                   12801:     if ($reqtype eq 'HEAD') {
1.486     www      12802: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12803:     } elsif ($reqtype eq 'GET') {
                   12804: 	$$info = $response->content;
1.472     albertel 12805:     }
1.482     albertel 12806:     return 'ok';
1.36      albertel 12807: }
                   12808: 
1.481     raeburn  12809: sub readfile {
                   12810:     my $file = shift;
                   12811:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12812:     my $fh;
                   12813:     open($fh,"<$file");
                   12814:     my $a='';
1.800     albertel 12815:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12816:     return $a;
                   12817: }
                   12818: 
1.36      albertel 12819: sub filelocation {
1.590     banghart 12820:     my ($dir,$file) = @_;
                   12821:     my $location;
                   12822:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12823: 
                   12824:     if ($file =~ m-^/adm/-) {
                   12825: 	$file=~s-^/adm/wrapper/-/-;
                   12826: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12827:     }
1.882     albertel 12828: 
1.1139    www      12829:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12830:         $location = $file;
1.609     banghart 12831:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12832:         my ($udom,$uname,$filename)=
1.811     albertel 12833:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12834:         my $home=&homeserver($uname,$udom);
                   12835:         my $is_me=0;
                   12836:         my @ids=&current_machine_ids();
                   12837:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12838:         if ($is_me) {
1.1117    foxr     12839:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12840:         } else {
                   12841:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12842:   	      $udom.'/'.$uname.'/'.$filename;
                   12843:         }
1.882     albertel 12844:     } elsif ($file =~ m-^/adm/-) {
                   12845: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12846:     } else {
                   12847:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12848:         $file=~s:^/(res|priv)/:/:;
                   12849:         my $space=$1;
1.590     banghart 12850:         if ( !( $file =~ m:^/:) ) {
                   12851:             $location = $dir. '/'.$file;
                   12852:         } else {
1.1142    raeburn  12853:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12854:         }
1.59      albertel 12855:     }
1.590     banghart 12856:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12857:     while ($location=~m{/\.\./}) {
                   12858: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12859: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12860: 	} else {
                   12861: 	    $location=~ s{/\.\./}{/}g;
                   12862: 	}
                   12863:     } #remove dir/..
1.590     banghart 12864:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12865:     return $location;
1.46      www      12866: }
1.36      albertel 12867: 
1.46      www      12868: sub hreflocation {
                   12869:     my ($dir,$file)=@_;
1.980     raeburn  12870:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12871: 	$file=filelocation($dir,$file);
1.700     albertel 12872:     } elsif ($file=~m-^/adm/-) {
                   12873: 	$file=~s-^/adm/wrapper/-/-;
                   12874: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12875:     }
                   12876:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12877: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12878:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12879: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12880: 	        {/uploaded/$1/$2/}x;
1.46      www      12881:     }
1.913     albertel 12882:     if ($file=~ m{^/userfiles/}) {
                   12883: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12884:     }
1.462     albertel 12885:     return $file;
1.465     albertel 12886: }
                   12887: 
1.1139    www      12888: 
                   12889: 
                   12890: 
                   12891: 
1.465     albertel 12892: sub current_machine_domains {
1.853     albertel 12893:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12894: }
                   12895: 
                   12896: sub machine_domains {
                   12897:     my ($hostname) = @_;
1.465     albertel 12898:     my @domains;
1.838     albertel 12899:     my %hostname = &all_hostnames();
1.465     albertel 12900:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12901: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12902: 	if ($hostname eq $name) {
1.844     albertel 12903: 	    push(@domains,&host_domain($id));
1.465     albertel 12904: 	}
                   12905:     }
                   12906:     return @domains;
                   12907: }
                   12908: 
                   12909: sub current_machine_ids {
1.853     albertel 12910:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12911: }
                   12912: 
                   12913: sub machine_ids {
                   12914:     my ($hostname) = @_;
                   12915:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12916:     my @ids;
1.888     albertel 12917:     my %name_to_host = &all_names();
1.889     albertel 12918:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12919: 	return @{ $name_to_host{$hostname} };
                   12920:     }
                   12921:     return;
1.31      www      12922: }
                   12923: 
1.824     raeburn  12924: sub additional_machine_domains {
                   12925:     my @domains;
                   12926:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12927:     while( my $line = <$fh>) {
                   12928:         $line =~ s/\s//g;
                   12929:         push(@domains,$line);
                   12930:     }
                   12931:     return @domains;
                   12932: }
                   12933: 
                   12934: sub default_login_domain {
                   12935:     my $domain = $perlvar{'lonDefDomain'};
                   12936:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12937:     foreach my $posdom (&current_machine_domains(),
                   12938:                         &additional_machine_domains()) {
                   12939:         if (lc($posdom) eq lc($testdomain)) {
                   12940:             $domain=$posdom;
                   12941:             last;
                   12942:         }
                   12943:     }
                   12944:     return $domain;
                   12945: }
                   12946: 
1.31      www      12947: # ------------------------------------------------------------- Declutters URLs
                   12948: 
                   12949: sub declutter {
                   12950:     my $thisfn=shift;
1.569     albertel 12951:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12952:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12953:         $thisfn=~s{^/home/httpd/html}{};
                   12954:     }
1.31      www      12955:     $thisfn=~s/^\///;
1.697     albertel 12956:     $thisfn=~s|^adm/wrapper/||;
                   12957:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12958:     $thisfn=~s/^res\///;
1.1172    bisitz   12959:     $thisfn=~s/^priv\///;
1.1032    raeburn  12960:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12961:         $thisfn=~s/\?.+$//;
                   12962:     }
1.268     www      12963:     return $thisfn;
                   12964: }
                   12965: 
                   12966: # ------------------------------------------------------------- Clutter up URLs
                   12967: 
                   12968: sub clutter {
                   12969:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12970:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12971: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12972:        $thisfn='/res'.$thisfn; 
                   12973:     }
1.1031    raeburn  12974:     if ($thisfn !~m|^/adm|) {
                   12975: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12976: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12977: 	} else {
                   12978: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12979: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12980: 	    if ($embstyle eq 'ssi'
                   12981: 		|| ($embstyle eq 'hdn')
                   12982: 		|| ($embstyle eq 'rat')
                   12983: 		|| ($embstyle eq 'prv')
                   12984: 		|| ($embstyle eq 'ign')) {
                   12985: 		#do nothing with these
                   12986: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12987: 		|| ($embstyle eq 'emb')
                   12988: 		|| ($embstyle eq 'wrp')) {
                   12989: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12990: 	    } elsif ($embstyle eq 'unk'
                   12991: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12992: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12993: 	    } else {
1.718     www      12994: #		&logthis("Got a blank emb style");
1.695     albertel 12995: 	    }
1.694     albertel 12996: 	}
1.1298    raeburn  12997:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12998:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12999:     }
1.31      www      13000:     return $thisfn;
1.12      www      13001: }
                   13002: 
1.787     albertel 13003: sub clutter_with_no_wrapper {
                   13004:     my $uri = &clutter(shift);
                   13005:     if ($uri =~ m-^/adm/-) {
                   13006: 	$uri =~ s-^/adm/wrapper/-/-;
                   13007: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13008:     }
                   13009:     return $uri;
                   13010: }
                   13011: 
1.557     albertel 13012: sub freeze_escape {
                   13013:     my ($value)=@_;
                   13014:     if (ref($value)) {
                   13015: 	$value=&nfreeze($value);
                   13016: 	return '__FROZEN__'.&escape($value);
                   13017:     }
                   13018:     return &escape($value);
                   13019: }
                   13020: 
1.11      www      13021: 
1.557     albertel 13022: sub thaw_unescape {
                   13023:     my ($value)=@_;
                   13024:     if ($value =~ /^__FROZEN__/) {
                   13025: 	substr($value,0,10,undef);
                   13026: 	$value=&unescape($value);
                   13027: 	return &thaw($value);
                   13028:     }
                   13029:     return &unescape($value);
                   13030: }
                   13031: 
1.436     albertel 13032: sub correct_line_ends {
                   13033:     my ($result)=@_;
                   13034:     $$result =~s/\r\n/\n/mg;
                   13035:     $$result =~s/\r/\n/mg;
1.415     albertel 13036: }
1.1       albertel 13037: # ================================================================ Main Program
                   13038: 
1.184     www      13039: sub goodbye {
1.204     albertel 13040:    &logthis("Starting Shut down");
1.443     albertel 13041: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13042:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13043: #converted
1.599     albertel 13044: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13045:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13046: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13047: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13048: #1.1 only
1.870     albertel 13049: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13050: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13051: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13052: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13053:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13054:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13055:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13056:    &flushcourselogs();
                   13057:    &logthis("Shutting down");
                   13058: }
                   13059: 
1.852     albertel 13060: sub get_dns {
1.1210    raeburn  13061:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13062:     if (!$ignore_cache) {
                   13063: 	my ($content,$cached)=
                   13064: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13065: 	if ($cached) {
1.1210    raeburn  13066: 	    &$func($content,$hashref);
1.869     albertel 13067: 	    return;
                   13068: 	}
                   13069:     }
                   13070: 
                   13071:     my %alldns;
1.852     albertel 13072:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13073:     foreach my $dns (<$config>) {
                   13074: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13075:         my $line = $1;
                   13076:         my ($host,$protocol) = split(/:/,$line);
                   13077:         if ($protocol ne 'https') {
                   13078:             $protocol = 'http';
                   13079:         }
                   13080: 	$alldns{$host} = $protocol;
1.869     albertel 13081:     }
                   13082:     while (%alldns) {
1.1263    raeburn  13083: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13084: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13085:         $ua->timeout(30);
1.979     raeburn  13086: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13087: 	my $response=$ua->request($request);
1.979     raeburn  13088:         delete($alldns{$dns});
1.852     albertel 13089: 	next if ($response->is_error());
                   13090: 	my @content = split("\n",$response->content);
1.1210    raeburn  13091: 	unless ($nocache) {
1.1219    raeburn  13092: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13093: 	}
                   13094: 	&$func(\@content,$hashref);
1.869     albertel 13095: 	return;
1.852     albertel 13096:     }
                   13097:     close($config);
1.871     albertel 13098:     my $which = (split('/',$url))[3];
                   13099:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13100:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13101:     my @content = <$config>;
1.1210    raeburn  13102:     &$func(\@content,$hashref);
                   13103:     return;
                   13104: }
                   13105: 
                   13106: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13107: sub parse_dns_checksums_tab {
1.1210    raeburn  13108:     my ($lines,$hashref) = @_;
1.1264    raeburn  13109:     my $lonhost = $perlvar{'lonHostID'};
                   13110:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13111:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13112:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13113:     my $webconfdir = '/etc/httpd/conf';
                   13114:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13115:         $webconfdir = '/etc/apache2';
                   13116:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13117:         if ($1 >= 10) {
                   13118:             $webconfdir = '/etc/apache2';
                   13119:         }
                   13120:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13121:         if ($1 >= 10.0) {
                   13122:             $webconfdir = '/etc/apache2';
                   13123:         }
                   13124:     }
1.1210    raeburn  13125:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13126:     my (%chksum,%revnum);
                   13127:     if (ref($lines) eq 'ARRAY') {
                   13128:         chomp(@{$lines});
1.1238    raeburn  13129:         my $version = shift(@{$lines});
                   13130:         if ($version eq $release) {  
1.1210    raeburn  13131:             foreach my $line (@{$lines}) {
1.1238    raeburn  13132:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13133:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13134:                     if ($webconfdir eq '/etc/apache2') {
                   13135:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13136:                     }
                   13137:                 }
1.1238    raeburn  13138:                 $chksum{$file} = $shasum;
                   13139:                 $revnum{$file} = $version;
1.1210    raeburn  13140:             }
                   13141:             if (ref($hashref) eq 'HASH') {
                   13142:                 %{$hashref} = (
                   13143:                                 sums     => \%chksum,
                   13144:                                 versions => \%revnum,
                   13145:                               );
                   13146:             }
                   13147:         }
                   13148:     }
1.869     albertel 13149:     return;
1.852     albertel 13150: }
1.1210    raeburn  13151: 
                   13152: sub fetch_dns_checksums {
1.1238    raeburn  13153:     my %checksums;
                   13154:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13155:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13156:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13157:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13158:              \%checksums);
1.1210    raeburn  13159:     return \%checksums;
                   13160: }
                   13161: 
1.327     albertel 13162: # ------------------------------------------------------------ Read domain file
                   13163: {
1.852     albertel 13164:     my $loaded;
1.846     albertel 13165:     my %domain;
                   13166: 
1.852     albertel 13167:     sub parse_domain_tab {
                   13168: 	my ($lines) = @_;
                   13169: 	foreach my $line (@$lines) {
                   13170: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13171: 
1.846     albertel 13172: 	    chomp($line);
1.852     albertel 13173: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13174: 	    my %this_domain;
                   13175: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13176: 			       'lang_def', 'city', 'longi', 'lati',
                   13177: 			       'primary') {
                   13178: 		$this_domain{$field} = shift(@elements);
                   13179: 	    }
                   13180: 	    $domain{$name} = \%this_domain;
1.852     albertel 13181: 	}
                   13182:     }
1.864     albertel 13183: 
                   13184:     sub reset_domain_info {
                   13185: 	undef($loaded);
                   13186: 	undef(%domain);
                   13187:     }
                   13188: 
1.852     albertel 13189:     sub load_domain_tab {
1.1293    raeburn  13190: 	my ($ignore_cache,$nocache) = @_;
                   13191: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13192: 	my $fh;
                   13193: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   13194: 	    my @lines = <$fh>;
                   13195: 	    &parse_domain_tab(\@lines);
1.448     albertel 13196: 	}
1.852     albertel 13197: 	close($fh);
                   13198: 	$loaded = 1;
1.327     albertel 13199:     }
1.846     albertel 13200: 
                   13201:     sub domain {
1.852     albertel 13202: 	&load_domain_tab() if (!$loaded);
                   13203: 
1.846     albertel 13204: 	my ($name,$what) = @_;
                   13205: 	return if ( !exists($domain{$name}) );
                   13206: 
                   13207: 	if (!$what) {
                   13208: 	    return $domain{$name}{'description'};
                   13209: 	}
                   13210: 	return $domain{$name}{$what};
                   13211:     }
1.974     raeburn  13212: 
                   13213:     sub domain_info {
                   13214:         &load_domain_tab() if (!$loaded);
                   13215:         return %domain;
                   13216:     }
                   13217: 
1.327     albertel 13218: }
                   13219: 
                   13220: 
1.1       albertel 13221: # ------------------------------------------------------------- Read hosts file
                   13222: {
1.838     albertel 13223:     my %hostname;
1.844     albertel 13224:     my %hostdom;
1.845     albertel 13225:     my %libserv;
1.852     albertel 13226:     my $loaded;
1.888     albertel 13227:     my %name_to_host;
1.1074    raeburn  13228:     my %internetdom;
1.1107    raeburn  13229:     my %LC_dns_serv;
1.852     albertel 13230: 
                   13231:     sub parse_hosts_tab {
                   13232: 	my ($file) = @_;
                   13233: 	foreach my $configline (@$file) {
                   13234: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13235:             chomp($configline);
                   13236: 	    if ($configline =~ /^\^/) {
                   13237:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13238:                     $LC_dns_serv{$1} = 1;
                   13239:                 }
                   13240:                 next;
                   13241:             }
1.1074    raeburn  13242: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13243: 	    $name=~s/\s//g;
                   13244: 	    if ($id && $domain && $role && $name) {
                   13245: 		$hostname{$id}=$name;
1.888     albertel 13246: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 13247: 		$hostdom{$id}=$domain;
                   13248: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13249:                 if (defined($protocol)) {
                   13250:                     if ($protocol eq 'https') {
                   13251:                         $protocol{$id} = $protocol;
                   13252:                     } else {
                   13253:                         $protocol{$id} = 'http'; 
                   13254:                     }
1.968     raeburn  13255:                 } else {
1.969     raeburn  13256:                     $protocol{$id} = 'http';
1.968     raeburn  13257:                 }
1.1074    raeburn  13258:                 if (defined($intdom)) {
                   13259:                     $internetdom{$id} = $intdom;
                   13260:                 }
1.852     albertel 13261: 	    }
                   13262: 	}
                   13263:     }
1.864     albertel 13264:     
                   13265:     sub reset_hosts_info {
1.897     albertel 13266: 	&purge_remembered();
1.864     albertel 13267: 	&reset_domain_info();
                   13268: 	&reset_hosts_ip_info();
1.1339    raeburn  13269:         undef(%internetdom);
1.892     albertel 13270: 	undef(%name_to_host);
1.864     albertel 13271: 	undef(%hostname);
                   13272: 	undef(%hostdom);
                   13273: 	undef(%libserv);
                   13274: 	undef($loaded);
                   13275:     }
1.1       albertel 13276: 
1.852     albertel 13277:     sub load_hosts_tab {
1.1293    raeburn  13278: 	my ($ignore_cache,$nocache) = @_;
                   13279: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 13280: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13281: 	my @config = <$config>;
                   13282: 	&parse_hosts_tab(\@config);
                   13283: 	close($config);
                   13284: 	$loaded=1;
1.1       albertel 13285:     }
1.852     albertel 13286: 
1.838     albertel 13287:     sub hostname {
1.852     albertel 13288: 	&load_hosts_tab() if (!$loaded);
                   13289: 
1.838     albertel 13290: 	my ($lonid) = @_;
                   13291: 	return $hostname{$lonid};
                   13292:     }
1.845     albertel 13293: 
1.838     albertel 13294:     sub all_hostnames {
1.852     albertel 13295: 	&load_hosts_tab() if (!$loaded);
                   13296: 
1.838     albertel 13297: 	return %hostname;
                   13298:     }
1.845     albertel 13299: 
1.888     albertel 13300:     sub all_names {
1.1293    raeburn  13301:         my ($ignore_cache,$nocache) = @_;
                   13302: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13303: 
                   13304: 	return %name_to_host;
                   13305:     }
                   13306: 
1.974     raeburn  13307:     sub all_host_domain {
                   13308:         &load_hosts_tab() if (!$loaded);
                   13309:         return %hostdom;
                   13310:     }
                   13311: 
1.1339    raeburn  13312:     sub all_host_intdom {
                   13313:         &load_hosts_tab() if (!$loaded);
                   13314:         return %internetdom;
                   13315:     }
                   13316: 
1.845     albertel 13317:     sub is_library {
1.852     albertel 13318: 	&load_hosts_tab() if (!$loaded);
                   13319: 
1.845     albertel 13320: 	return exists($libserv{$_[0]});
                   13321:     }
                   13322: 
                   13323:     sub all_library {
1.852     albertel 13324: 	&load_hosts_tab() if (!$loaded);
                   13325: 
1.845     albertel 13326: 	return %libserv;
                   13327:     }
                   13328: 
1.1062    droeschl 13329:     sub unique_library {
                   13330: 	#2x reverse removes all hostnames that appear more than once
                   13331:         my %unique = reverse &all_library();
                   13332:         return reverse %unique;
                   13333:     }
                   13334: 
1.841     albertel 13335:     sub get_servers {
1.852     albertel 13336: 	&load_hosts_tab() if (!$loaded);
                   13337: 
1.841     albertel 13338: 	my ($domain,$type) = @_;
                   13339: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13340: 	                                          : %hostname;
                   13341: 	my %result;
1.842     albertel 13342: 	if (ref($domain) eq 'ARRAY') {
                   13343: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13344: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13345: 		    $result{$host} = $hostname;
                   13346: 		}
                   13347: 	    }
                   13348: 	} else {
                   13349: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13350: 		if ($hostdom{$host} eq $domain) {
                   13351: 		    $result{$host} = $hostname;
                   13352: 		}
1.841     albertel 13353: 	    }
                   13354: 	}
                   13355: 	return %result;
                   13356:     }
1.845     albertel 13357: 
1.1062    droeschl 13358:     sub get_unique_servers {
                   13359:         my %unique = reverse &get_servers(@_);
                   13360: 	return reverse %unique;
                   13361:     }
                   13362: 
1.844     albertel 13363:     sub host_domain {
1.852     albertel 13364: 	&load_hosts_tab() if (!$loaded);
                   13365: 
1.844     albertel 13366: 	my ($lonid) = @_;
                   13367: 	return $hostdom{$lonid};
                   13368:     }
                   13369: 
1.841     albertel 13370:     sub all_domains {
1.852     albertel 13371: 	&load_hosts_tab() if (!$loaded);
                   13372: 
1.841     albertel 13373: 	my %seen;
                   13374: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13375: 	return @uniq;
                   13376:     }
1.1074    raeburn  13377: 
                   13378:     sub internet_dom {
                   13379:         &load_hosts_tab() if (!$loaded);
                   13380: 
                   13381:         my ($lonid) = @_;
                   13382:         return $internetdom{$lonid};
                   13383:     }
1.1107    raeburn  13384: 
                   13385:     sub is_LC_dns {
                   13386:         &load_hosts_tab() if (!$loaded);
                   13387: 
                   13388:         my ($hostname) = @_;
                   13389:         return exists($LC_dns_serv{$hostname});
                   13390:     }
                   13391: 
1.1       albertel 13392: }
                   13393: 
1.847     albertel 13394: { 
                   13395:     my %iphost;
1.856     albertel 13396:     my %name_to_ip;
                   13397:     my %lonid_to_ip;
1.869     albertel 13398: 
1.847     albertel 13399:     sub get_hosts_from_ip {
                   13400: 	my ($ip) = @_;
                   13401: 	my %iphosts = &get_iphost();
                   13402: 	if (ref($iphosts{$ip})) {
                   13403: 	    return @{$iphosts{$ip}};
                   13404: 	}
                   13405: 	return;
1.839     albertel 13406:     }
1.864     albertel 13407:     
                   13408:     sub reset_hosts_ip_info {
                   13409: 	undef(%iphost);
                   13410: 	undef(%name_to_ip);
                   13411: 	undef(%lonid_to_ip);
                   13412:     }
1.856     albertel 13413: 
                   13414:     sub get_host_ip {
                   13415: 	my ($lonid) = @_;
                   13416: 	if (exists($lonid_to_ip{$lonid})) {
                   13417: 	    return $lonid_to_ip{$lonid};
                   13418: 	}
                   13419: 	my $name=&hostname($lonid);
                   13420:    	my $ip = gethostbyname($name);
                   13421: 	return if (!$ip || length($ip) ne 4);
                   13422: 	$ip=inet_ntoa($ip);
                   13423: 	$name_to_ip{$name}   = $ip;
                   13424: 	$lonid_to_ip{$lonid} = $ip;
                   13425: 	return $ip;
                   13426:     }
1.847     albertel 13427:     
                   13428:     sub get_iphost {
1.1293    raeburn  13429: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13430: 
1.869     albertel 13431: 	if (!$ignore_cache) {
                   13432: 	    if (%iphost) {
                   13433: 		return %iphost;
                   13434: 	    }
                   13435: 	    my ($ip_info,$cached)=
                   13436: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13437: 	    if ($cached) {
                   13438: 		%iphost      = %{$ip_info->[0]};
                   13439: 		%name_to_ip  = %{$ip_info->[1]};
                   13440: 		%lonid_to_ip = %{$ip_info->[2]};
                   13441: 		return %iphost;
                   13442: 	    }
                   13443: 	}
1.894     albertel 13444: 
                   13445: 	# get yesterday's info for fallback
                   13446: 	my %old_name_to_ip;
                   13447: 	my ($ip_info,$cached)=
                   13448: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13449: 	if ($cached) {
                   13450: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13451: 	}
                   13452: 
1.1293    raeburn  13453: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13454: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13455: 	    my $ip;
                   13456: 	    if (!exists($name_to_ip{$name})) {
                   13457: 		$ip = gethostbyname($name);
                   13458: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13459: 		    if (defined($old_name_to_ip{$name})) {
                   13460: 			$ip = $old_name_to_ip{$name};
                   13461: 			&logthis("Can't find $name defaulting to old $ip");
                   13462: 		    } else {
                   13463: 			&logthis("Name $name no IP found");
                   13464: 			next;
                   13465: 		    }
                   13466: 		} else {
                   13467: 		    $ip=inet_ntoa($ip);
1.847     albertel 13468: 		}
                   13469: 		$name_to_ip{$name} = $ip;
                   13470: 	    } else {
                   13471: 		$ip = $name_to_ip{$name};
1.653     albertel 13472: 	    }
1.888     albertel 13473: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13474: 		$lonid_to_ip{$id} = $ip;
                   13475: 	    }
                   13476: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13477: 	}
1.1293    raeburn  13478:         unless ($nocache) {
                   13479: 	    &do_cache_new('iphost','iphost',
                   13480: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13481: 		          48*60*60);
                   13482:         }
1.869     albertel 13483: 
1.847     albertel 13484: 	return %iphost;
1.598     albertel 13485:     }
                   13486: 
1.992     raeburn  13487:     #
                   13488:     #  Given a DNS returns the loncapa host name for that DNS 
                   13489:     # 
                   13490:     sub host_from_dns {
                   13491:         my ($dns) = @_;
                   13492:         my @hosts;
                   13493:         my $ip;
                   13494: 
1.993     raeburn  13495:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13496:             $ip = $name_to_ip{$dns};
                   13497:         }
                   13498:         if (!$ip) {
                   13499:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13500:             if (length($ip) == 4) { 
                   13501: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13502:             }
                   13503:         }
                   13504:         if ($ip) {
                   13505: 	    @hosts = get_hosts_from_ip($ip);
                   13506: 	    return $hosts[0];
                   13507:         }
                   13508:         return undef;
1.986     foxr     13509:     }
1.992     raeburn  13510: 
1.1074    raeburn  13511:     sub get_internet_names {
                   13512:         my ($lonid) = @_;
                   13513:         return if ($lonid eq '');
                   13514:         my ($idnref,$cached)=
                   13515:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13516:         if ($cached) {
                   13517:             return $idnref;
                   13518:         }
                   13519:         my $ip = &get_host_ip($lonid);
                   13520:         my @hosts = &get_hosts_from_ip($ip);
                   13521:         my %iphost = &get_iphost();
                   13522:         my (@idns,%seen);
                   13523:         foreach my $id (@hosts) {
                   13524:             my $dom = &host_domain($id);
                   13525:             my $prim_id = &domain($dom,'primary');
                   13526:             my $prim_ip = &get_host_ip($prim_id);
                   13527:             next if ($seen{$prim_ip});
                   13528:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13529:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13530:                     my $intdom = &internet_dom($id);
                   13531:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13532:                         push(@idns,$intdom);
                   13533:                     }
                   13534:                 }
                   13535:             }
                   13536:             $seen{$prim_ip} = 1;
                   13537:         }
1.1219    raeburn  13538:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13539:     }
                   13540: 
1.986     foxr     13541: }
                   13542: 
1.1079    raeburn  13543: sub all_loncaparevs {
1.1249    raeburn  13544:     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  13545: }
                   13546: 
1.1227    raeburn  13547: # ---------------------------------------------------------- Read loncaparev table
                   13548: {
                   13549:     sub load_loncaparevs { 
                   13550:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13551:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13552:                 while (my $configline=<$config>) {
                   13553:                     chomp($configline);
                   13554:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13555:                     $loncaparevs{$hostid}=$loncaparev;
                   13556:                 }
                   13557:                 close($config);
                   13558:             }
                   13559:         }
                   13560:     }
                   13561: }
                   13562: 
                   13563: # ---------------------------------------------------------- Read serverhostID table
                   13564: {
                   13565:     sub load_serverhomeIDs {
                   13566:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13567:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13568:                 while (my $configline=<$config>) {
                   13569:                     chomp($configline);
                   13570:                     my ($name,$id)=split(/:/,$configline);
                   13571:                     $serverhomeIDs{$name}=$id;
                   13572:                 }
                   13573:                 close($config);
                   13574:             }
                   13575:         }
                   13576:     }
                   13577: }
                   13578: 
                   13579: 
1.862     albertel 13580: BEGIN {
                   13581: 
                   13582: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13583:     unless ($readit) {
                   13584: {
                   13585:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13586:     %perlvar = (%perlvar,%{$configvars});
                   13587: }
                   13588: 
                   13589: 
1.1       albertel 13590: # ------------------------------------------------------ Read spare server file
                   13591: {
1.448     albertel 13592:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13593: 
                   13594:     while (my $configline=<$config>) {
                   13595:        chomp($configline);
1.284     matthew  13596:        if ($configline) {
1.784     albertel 13597: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13598: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13599: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13600:        }
                   13601:     }
1.448     albertel 13602:     close($config);
1.1       albertel 13603: }
1.11      www      13604: # ------------------------------------------------------------ Read permissions
                   13605: {
1.448     albertel 13606:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13607: 
                   13608:     while (my $configline=<$config>) {
1.448     albertel 13609: 	chomp($configline);
                   13610: 	if ($configline) {
                   13611: 	    my ($role,$perm)=split(/ /,$configline);
                   13612: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13613: 	}
1.11      www      13614:     }
1.448     albertel 13615:     close($config);
1.11      www      13616: }
                   13617: 
                   13618: # -------------------------------------------- Read plain texts for permissions
                   13619: {
1.448     albertel 13620:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13621: 
                   13622:     while (my $configline=<$config>) {
1.448     albertel 13623: 	chomp($configline);
                   13624: 	if ($configline) {
1.742     raeburn  13625: 	    my ($short,@plain)=split(/:/,$configline);
                   13626:             %{$prp{$short}} = ();
                   13627: 	    if (@plain > 0) {
                   13628:                 $prp{$short}{'std'} = $plain[0];
                   13629:                 for (my $i=1; $i<@plain; $i++) {
                   13630:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13631:                 }
                   13632:             }
1.448     albertel 13633: 	}
1.135     www      13634:     }
1.448     albertel 13635:     close($config);
1.135     www      13636: }
                   13637: 
                   13638: # ---------------------------------------------------------- Read package table
                   13639: {
1.448     albertel 13640:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13641: 
                   13642:     while (my $configline=<$config>) {
1.483     albertel 13643: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13644: 	chomp($configline);
                   13645: 	my ($short,$plain)=split(/:/,$configline);
                   13646: 	my ($pack,$name)=split(/\&/,$short);
                   13647: 	if ($plain ne '') {
                   13648: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13649: 	    $packagetab{$short}=$plain; 
                   13650: 	}
1.11      www      13651:     }
1.448     albertel 13652:     close($config);
1.329     matthew  13653: }
                   13654: 
1.1073    raeburn  13655: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13656: 
                   13657: &load_loncaparevs();
1.1073    raeburn  13658: 
1.1074    raeburn  13659: # ---------------------------------------------------------- Read serverhostID table
                   13660: 
1.1227    raeburn  13661: &load_serverhomeIDs();
                   13662: 
                   13663: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13664: {
                   13665:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13666:     if (-e $file) {
                   13667:         my $parser = HTML::LCParser->new($file);
                   13668:         while (my $token = $parser->get_token()) {
                   13669:             if ($token->[0] eq 'S') {
                   13670:                 my $item = $token->[1];
                   13671:                 my $name = $token->[2]{'name'};
                   13672:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13673:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13674:                 my $namematch = $token->[2]{'namematch'};
                   13675:                 if ($item eq 'parameter') {
                   13676:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13677:                         my $release = $parser->get_text();
                   13678:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13679:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13680:                     }
                   13681:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13682:                     my $release = $parser->get_text();
                   13683:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13684:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13685:                 }
                   13686:             }
                   13687:         }
                   13688:     }
1.1073    raeburn  13689: }
                   13690: 
1.1138    raeburn  13691: # ---------------------------------------------------------- Read managers table
                   13692: {
                   13693:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13694:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13695:             while (my $configline=<$config>) {
                   13696:                 chomp($configline);
                   13697:                 next if ($configline =~ /^\#/);
                   13698:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13699:                     $managerstab{$configline} = 1;
                   13700:                 }
                   13701:             }
                   13702:             close($config);
                   13703:         }
                   13704:     }
                   13705: }
                   13706: 
1.329     matthew  13707: # ------------- set up temporary directory
                   13708: {
1.1117    foxr     13709:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13710: 
1.11      www      13711: }
                   13712: 
1.794     albertel 13713: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13714: 				'compress_threshold'=> 20_000,
                   13715:  			        });
1.185     www      13716: 
1.281     www      13717: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13718: $dumpcount=0;
1.958     www      13719: $locknum=0;
1.22      www      13720: 
1.163     harris41 13721: &logtouch();
1.672     albertel 13722: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13723: $readit=1;
1.564     albertel 13724:     {
                   13725: 	use integer;
                   13726: 	my $test=(2**32)+1;
1.568     albertel 13727: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13728: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13729:     }
1.195     www      13730: }
1.1       albertel 13731: }
1.179     www      13732: 
1.1       albertel 13733: 1;
1.191     harris41 13734: __END__
                   13735: 
1.243     albertel 13736: =pod
                   13737: 
1.191     harris41 13738: =head1 NAME
                   13739: 
1.243     albertel 13740: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13741: 
                   13742: =head1 SYNOPSIS
                   13743: 
1.243     albertel 13744: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13745: 
                   13746:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13747: 
1.243     albertel 13748: Common parameters:
                   13749: 
                   13750: =over 4
                   13751: 
                   13752: =item *
                   13753: 
                   13754: $uname : an internal username (if $cname expecting a course Id specifically)
                   13755: 
                   13756: =item *
                   13757: 
                   13758: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13759: 
                   13760: =item *
                   13761: 
                   13762: $symb : a resource instance identifier
                   13763: 
                   13764: =item *
                   13765: 
                   13766: $namespace : the name of a .db file that contains the data needed or
                   13767: being set.
                   13768: 
                   13769: =back
                   13770: 
1.394     bowersj2 13771: =head1 OVERVIEW
1.191     harris41 13772: 
1.394     bowersj2 13773: lonnet provides subroutines which interact with the
                   13774: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13775: about classes, users, and resources.
1.243     albertel 13776: 
                   13777: For many of these objects you can also use this to store data about
                   13778: them or modify them in various ways.
1.191     harris41 13779: 
1.394     bowersj2 13780: =head2 Symbs
1.191     harris41 13781: 
1.394     bowersj2 13782: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13783: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13784: map, the resource number of the resource in the map, and the URL of
                   13785: the resource itself. The latter is somewhat redundant, but might help
                   13786: if maps change.
                   13787: 
                   13788: An example is
                   13789: 
                   13790:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13791: 
                   13792: The respective map entry is
                   13793: 
                   13794:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13795:   title="Problem 2">
                   13796:  </resource>
                   13797: 
                   13798: Symbs are used by the random number generator, as well as to store and
                   13799: restore data specific to a certain instance of for example a problem.
                   13800: 
                   13801: =head2 Storing And Retrieving Data
                   13802: 
                   13803: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13804: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13805: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13806: is is the non-critical message twin of cstore. These functions are for
                   13807: handlers to store a perl hash to a user's permanent data space in an
                   13808: easy manner, and to retrieve it again on another call. It is expected
                   13809: that a handler would use this once at the beginning to retrieve data,
                   13810: and then again once at the end to send only the new data back.
                   13811: 
                   13812: The data is stored in the user's data directory on the user's
                   13813: homeserver under the ID of the course.
                   13814: 
                   13815: The hash that is returned by restore will have all of the previous
                   13816: value for all of the elements of the hash.
                   13817: 
                   13818: Example:
                   13819: 
                   13820:  #creating a hash
                   13821:  my %hash;
                   13822:  $hash{'foo'}='bar';
                   13823: 
                   13824:  #storing it
                   13825:  &Apache::lonnet::cstore(\%hash);
                   13826: 
                   13827:  #changing a value
                   13828:  $hash{'foo'}='notbar';
                   13829: 
                   13830:  #adding a new value
                   13831:  $hash{'bar'}='foo';
                   13832:  &Apache::lonnet::cstore(\%hash);
                   13833: 
                   13834:  #retrieving the hash
                   13835:  my %history=&Apache::lonnet::restore();
                   13836: 
                   13837:  #print the hash
                   13838:  foreach my $key (sort(keys(%history))) {
                   13839:    print("\%history{$key} = $history{$key}");
                   13840:  }
                   13841: 
                   13842: Will print out:
1.191     harris41 13843: 
1.394     bowersj2 13844:  %history{1:foo} = bar
                   13845:  %history{1:keys} = foo:timestamp
                   13846:  %history{1:timestamp} = 990455579
                   13847:  %history{2:bar} = foo
                   13848:  %history{2:foo} = notbar
                   13849:  %history{2:keys} = foo:bar:timestamp
                   13850:  %history{2:timestamp} = 990455580
                   13851:  %history{bar} = foo
                   13852:  %history{foo} = notbar
                   13853:  %history{timestamp} = 990455580
                   13854:  %history{version} = 2
                   13855: 
                   13856: Note that the special hash entries C<keys>, C<version> and
                   13857: C<timestamp> were added to the hash. C<version> will be equal to the
                   13858: total number of versions of the data that have been stored. The
                   13859: C<timestamp> attribute will be the UNIX time the hash was
                   13860: stored. C<keys> is available in every historical section to list which
                   13861: keys were added or changed at a specific historical revision of a
                   13862: hash.
                   13863: 
                   13864: B<Warning>: do not store the hash that restore returns directly. This
                   13865: will cause a mess since it will restore the historical keys as if the
                   13866: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13867: 
1.394     bowersj2 13868: Calling convention:
1.191     harris41 13869: 
1.1225    raeburn  13870:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13871:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13872: 
1.394     bowersj2 13873: For more detailed information, see lonnet specific documentation.
1.191     harris41 13874: 
1.394     bowersj2 13875: =head1 RETURN MESSAGES
1.191     harris41 13876: 
1.394     bowersj2 13877: =over 4
1.191     harris41 13878: 
1.394     bowersj2 13879: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13880: 
1.394     bowersj2 13881: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13882: when the connection is brought back up
1.191     harris41 13883: 
1.394     bowersj2 13884: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13885: for later delivery
1.191     harris41 13886: 
1.967     bisitz   13887: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13888: 
1.394     bowersj2 13889: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13890: that was requested
1.191     harris41 13891: 
1.243     albertel 13892: =back
1.191     harris41 13893: 
1.243     albertel 13894: =head1 PUBLIC SUBROUTINES
1.191     harris41 13895: 
1.243     albertel 13896: =head2 Session Environment Functions
1.191     harris41 13897: 
1.243     albertel 13898: =over 4
1.191     harris41 13899: 
1.394     bowersj2 13900: =item * 
                   13901: X<appenv()>
1.949     raeburn  13902: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13903: the user envirnoment file, and will be restored for each access this
1.620     albertel 13904: user makes during this session, also modifies the %env for the current
1.949     raeburn  13905: process. Optional rolesarrayref - if defined contains a reference to an array
                   13906: of roles which are exempt from the restriction on modifying user.role entries 
                   13907: in the user's environment.db and in %env.    
1.191     harris41 13908: 
                   13909: =item *
1.394     bowersj2 13910: X<delenv()>
1.987     raeburn  13911: B<delenv($delthis,$regexp)>: removes all items from the session
                   13912: environment file that begin with $delthis. If the 
                   13913: optional second arg - $regexp - is true, $delthis is treated as a 
                   13914: regular expression, otherwise \Q$delthis\E is used. 
                   13915: The values are also deleted from the current processes %env.
1.191     harris41 13916: 
1.795     albertel 13917: =item * get_env_multiple($name) 
                   13918: 
                   13919: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13920: values may be defined and end up as an array ref.
                   13921: 
                   13922: returns an array of values
                   13923: 
1.243     albertel 13924: =back
                   13925: 
                   13926: =head2 User Information
1.191     harris41 13927: 
1.243     albertel 13928: =over 4
1.191     harris41 13929: 
                   13930: =item *
1.394     bowersj2 13931: X<queryauthenticate()>
                   13932: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13933: authentication scheme
                   13934: 
                   13935: =item *
1.394     bowersj2 13936: X<authenticate()>
1.1073    raeburn  13937: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13938: authenticate user from domain's lib servers (first use the current
                   13939: one). C<$upass> should be the users password.
1.1073    raeburn  13940: $checkdefauth is optional (value is 1 if a check should be made to
                   13941:    authenticate user using default authentication method, and allow
                   13942:    account creation if username does not have account in the domain).
                   13943: $clientcancheckhost is optional (value is 1 if checking whether the
                   13944:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13945: 
                   13946: =item *
1.394     bowersj2 13947: X<homeserver()>
                   13948: B<homeserver($uname,$udom)>: find the server which has
                   13949: the user's directory and files (there must be only one), this caches
                   13950: the answer, and also caches if there is a borken connection.
1.191     harris41 13951: 
                   13952: =item *
1.394     bowersj2 13953: X<idget()>
1.1300    raeburn  13954: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13955: a list of student/employee IDs or clicker IDs
                   13956: (student/employee IDs are a unique resource in a domain, there must be 
                   13957: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13958: clickerIDs are not necessarily unique, as students might share clickers.
                   13959: (returns hash: id=>name,id=>name)
1.191     harris41 13960: 
                   13961: =item *
1.394     bowersj2 13962: X<idrget()>
                   13963: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13964: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13965: 
                   13966: =item *
1.394     bowersj2 13967: X<idput()>
1.1300    raeburn  13968: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13969: names and associated student/employee IDs or clicker IDs.
                   13970: 
                   13971: =item *
                   13972: X<iddel()>
                   13973: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13974: student/employee ID or clicker ID username look-ups from domain.
                   13975: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13976: If no $uhome is provided, it will be determined usig &homeserver()
                   13977: for each user.  If no $namespace is provided, the default is ids.
                   13978: 
                   13979: =item *
                   13980: X<updateclickers()>
                   13981: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13982: clicker ID-to-username look-ups in clickers.db on library server.
                   13983: Permitted actions are add or del (i.e., add or delete). The 
                   13984: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13985: value is an escaped comma-separated list of usernames (for whom the
                   13986: library server is the homeserver), who registered that particular ID.
                   13987: If $critical is true, the update will be sent via &critical, otherwise
                   13988: &reply() will be used.
1.191     harris41 13989: 
                   13990: =item *
1.394     bowersj2 13991: X<rolesinit()>
1.1169    droeschl 13992: B<rolesinit($udom,$username)>: get user privileges.
                   13993: returns user role, first access and timer interval hashes
1.243     albertel 13994: 
                   13995: =item *
1.1171    droeschl 13996: X<privileged()>
                   13997: B<privileged($username,$domain)>: returns a true if user has a
                   13998: privileged and active role (i.e. su or dc), false otherwise.
                   13999: 
                   14000: =item *
1.551     albertel 14001: X<getsection()>
                   14002: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14003: course $cname, return section name/number or '' for "not in course"
                   14004: and '-1' for "no section"
                   14005: 
                   14006: =item *
1.394     bowersj2 14007: X<userenvironment()>
                   14008: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14009: passed in @what from the requested user's environment, returns a hash
                   14010: 
1.858     raeburn  14011: =item * 
                   14012: X<userlog_query()>
1.859     albertel 14013: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14014: activity.log file. %filters defines filters applied when parsing the
                   14015: log file. These can be start or end timestamps, or the type of action
                   14016: - log to look for Login or Logout events, check for Checkin or
                   14017: Checkout, role for role selection. The response is in the form
                   14018: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14019: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14020: 
1.243     albertel 14021: =back
                   14022: 
                   14023: =head2 User Roles
                   14024: 
                   14025: =over 4
                   14026: 
                   14027: =item *
                   14028: 
1.1284    raeburn  14029: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14030: returns codes for allowed actions.
                   14031: 
                   14032: The first argument is required, all others are optional.
                   14033: 
                   14034: $priv is the privilege being checked.
                   14035: $uri contains additional information about what is being checked for access (e.g.,
                   14036: URL, course ID etc.). 
                   14037: $symb is the unique resource instance identifier in a course; if needed,
                   14038: but not provided, it will be retrieved via a call to &symbread(). 
                   14039: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14040: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14041: files).
                   14042: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14043: prevents recursive calls to &allowed.
                   14044: 
1.243     albertel 14045:  F: full access
                   14046:  U,I,K: authentication modes (cxx only)
                   14047:  '': forbidden
                   14048:  1: user needs to choose course
                   14049:  2: browse allowed
1.766     albertel 14050:  A: passphrase authentication needed
1.1284    raeburn  14051:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14052: 
                   14053: =item *
                   14054: 
1.1192    raeburn  14055: constructaccess($url,$setpriv) : check for access to construction space URL
                   14056: 
                   14057: See if the owner domain and name in the URL match those in the
                   14058: expected environment.  If so, return three element list
                   14059: ($ownername,$ownerdomain,$ownerhome).
                   14060: 
                   14061: Otherwise return the null string.
                   14062: 
                   14063: If second argument 'setpriv' is true, it assigns the privileges,
                   14064: and returns the same three element list, unless the owner has
                   14065: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14066: in which case the null string is returned.
                   14067: 
                   14068: =item *
                   14069: 
1.1326    raeburn  14070: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14071: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14072: for system, domain, and course level. $uname and $udom are optional (current
                   14073: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14074: 
                   14075: =item *
                   14076: 
1.988     raeburn  14077: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14078: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14079: $type is Course (default) or Community.
1.988     raeburn  14080: If $forcedefault evaluates to true, text returned will be default 
                   14081: text for $type. Otherwise, if this is a course, the text returned 
                   14082: will be a custom name for the role (if defined in the course's 
                   14083: environment).  If no custom name is defined the default is returned.
                   14084:    
1.832     raeburn  14085: =item *
                   14086: 
1.1219    raeburn  14087: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14088: All arguments are optional. Returns a hash of a roles, either for
                   14089: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14090: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14091: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14092: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14093: For each key, value is set to colon-separated start and end times for
                   14094: the role.  If no username and domain are specified, will default to
1.934     raeburn  14095: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14096: of role statuses (active, future or previous), roles 
                   14097: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14098: to restrict the list of roles reported. If no array ref is 
                   14099: provided for types, will default to return only active roles.
1.834     albertel 14100: 
1.1195    raeburn  14101: =item *
                   14102: 
                   14103: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14104: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14105: 
                   14106: Additional optional arguments are: $type (if role checking is to be restricted 
                   14107: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14108: available roles) or future (roles available in the future), and
                   14109: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14110: have active Domain Coordinator role in course's domain or in additional
                   14111: domains (specified in 'Domains to check for privileged users' in course
                   14112: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14113: 
                   14114: =item *
                   14115: 
                   14116: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14117: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14118: $possdomains and $possroles are optional array refs -- to domains to check and
                   14119: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14120: users' roles.db to check for a dc or su role in any domain. This can be
                   14121: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14122: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14123: this then allows &privileged_by_domain() to be used, which caches the identity
                   14124: of privileged users, eliminating the need for repeated calls to &dump().
                   14125: 
                   14126: =item *
                   14127: 
                   14128: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14129: where the outer hash keys are domains specified in the $possdomains array ref,
                   14130: next inner hash keys are privileged roles specified in the $roles array ref,
                   14131: and the innermost hash contains key = value pairs for username:domain = end:start
                   14132: for active or future "privileged" users with that role in that domain. To avoid
                   14133: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14134: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14135: 
1.243     albertel 14136: =back
                   14137: 
                   14138: =head2 User Modification
                   14139: 
                   14140: =over 4
                   14141: 
                   14142: =item *
                   14143: 
1.957     raeburn  14144: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14145: user for the level given by URL.  Optional start and end dates (leave empty
                   14146: string or zero for "no date")
1.191     harris41 14147: 
                   14148: =item *
                   14149: 
1.243     albertel 14150: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14151: change a users, password, possible return values are: ok,
                   14152: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14153: refused
1.191     harris41 14154: 
                   14155: =item *
                   14156: 
1.243     albertel 14157: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14158: 
                   14159: =item *
                   14160: 
1.1058    raeburn  14161: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14162:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14163: 
                   14164: will update user information (firstname,middlename,lastname,generation,
                   14165: permanentemail), and if forceid is true, student/employee ID also.
                   14166: A user's institutional affiliation(s) can also be updated.
                   14167: User information fields will not be overwritten with empty entries 
                   14168: unless the field is included in the $candelete array reference.
                   14169: This array is included when a single user is modified via "Manage Users",
                   14170: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14171: 
                   14172: =item *
                   14173: 
1.286     matthew  14174: modifystudent
                   14175: 
1.957     raeburn  14176: modify a student's enrollment and identification information.
1.1235    raeburn  14177: The course id is resolved based on the current user's environment.  
                   14178: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14179: associated with a course.
                   14180: 
1.297     matthew  14181: This call is essentially a wrapper for lonnet::modifyuser and
                   14182: lonnet::modify_student_enrollment
1.286     matthew  14183: 
                   14184: Inputs: 
                   14185: 
                   14186: =over 4
                   14187: 
1.957     raeburn  14188: =item B<$udom> Student's loncapa domain
1.286     matthew  14189: 
1.957     raeburn  14190: =item B<$uname> Student's loncapa login name
1.286     matthew  14191: 
1.964     bisitz   14192: =item B<$uid> Student/Employee ID
1.286     matthew  14193: 
1.957     raeburn  14194: =item B<$umode> Student's authentication mode
1.286     matthew  14195: 
1.957     raeburn  14196: =item B<$upass> Student's password
1.286     matthew  14197: 
1.957     raeburn  14198: =item B<$first> Student's first name
1.286     matthew  14199: 
1.957     raeburn  14200: =item B<$middle> Student's middle name
1.286     matthew  14201: 
1.957     raeburn  14202: =item B<$last> Student's last name
1.286     matthew  14203: 
1.957     raeburn  14204: =item B<$gene> Student's generation
1.286     matthew  14205: 
1.957     raeburn  14206: =item B<$usec> Student's section in course
1.286     matthew  14207: 
                   14208: =item B<$end> Unix time of the roles expiration
                   14209: 
                   14210: =item B<$start> Unix time of the roles start date
                   14211: 
                   14212: =item B<$forceid> If defined, allow $uid to be changed
                   14213: 
                   14214: =item B<$desiredhome> server to use as home server for student
                   14215: 
1.957     raeburn  14216: =item B<$email> Student's permanent e-mail address
                   14217: 
                   14218: =item B<$type> Type of enrollment (auto or manual)
                   14219: 
1.963     raeburn  14220: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14221: 
                   14222: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14223: 
1.963     raeburn  14224: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14225: 
1.963     raeburn  14226: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14227: 
1.1216    raeburn  14228: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14229: 
                   14230: =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  14231: 
1.286     matthew  14232: =back
1.297     matthew  14233: 
                   14234: =item *
                   14235: 
                   14236: modify_student_enrollment
                   14237: 
1.1235    raeburn  14238: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14239: 'role.request.course' must be defined for this function to proceed.
                   14240: 
                   14241: Inputs:
                   14242: 
                   14243: =over 4
                   14244: 
1.1235    raeburn  14245: =item $udom, student's domain
1.297     matthew  14246: 
1.1235    raeburn  14247: =item $uname, student's name
1.297     matthew  14248: 
1.1235    raeburn  14249: =item $uid, student's user id
1.297     matthew  14250: 
1.1235    raeburn  14251: =item $first, student's first name
1.297     matthew  14252: 
                   14253: =item $middle
                   14254: 
                   14255: =item $last
                   14256: 
                   14257: =item $gene
                   14258: 
                   14259: =item $usec
                   14260: 
                   14261: =item $end
                   14262: 
                   14263: =item $start
                   14264: 
1.957     raeburn  14265: =item $type
                   14266: 
                   14267: =item $locktype
                   14268: 
                   14269: =item $cid
                   14270: 
                   14271: =item $selfenroll
                   14272: 
                   14273: =item $context
                   14274: 
1.1216    raeburn  14275: =item $credits, number of credits student will earn from this class
                   14276: 
1.1314    raeburn  14277: =item $instsec, institutional course section code for student
                   14278: 
1.297     matthew  14279: =back
                   14280: 
1.191     harris41 14281: 
                   14282: =item *
                   14283: 
1.243     albertel 14284: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14285: custom role; give a custom role to a user for the level given by URL.  Specify
                   14286: name and domain of role author, and role name
1.191     harris41 14287: 
                   14288: =item *
                   14289: 
1.243     albertel 14290: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14291: 
                   14292: =item *
                   14293: 
1.243     albertel 14294: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14295: 
                   14296: =back
                   14297: 
                   14298: =head2 Course Infomation
                   14299: 
                   14300: =over 4
1.191     harris41 14301: 
                   14302: =item *
                   14303: 
1.1118    foxr     14304: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14305: specified course id, including all environment settings for the
                   14306: course, the description of the course will be in the hash under the
                   14307: key 'description'
1.191     harris41 14308: 
1.1118    foxr     14309: $options is an optional parameter that if supplied is a hash reference that controls
                   14310: what how this function works.  It has the following key/values:
                   14311: 
                   14312: =over 4
                   14313: 
                   14314: =item freshen_cache
                   14315: 
                   14316: If defined, and the environment cache for the course is valid, it is 
                   14317: returned in the returned hash.
                   14318: 
                   14319: =item one_time
                   14320: 
                   14321: If defined, the last cache time is set to _now_
                   14322: 
                   14323: =item user
                   14324: 
                   14325: If defined, the supplied username is used instead of the current user.
                   14326: 
                   14327: 
                   14328: =back
                   14329: 
1.191     harris41 14330: =item *
                   14331: 
1.624     albertel 14332: resdata($name,$domain,$type,@which) : request for current parameter
                   14333: setting for a specific $type, where $type is either 'course' or 'user',
                   14334: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14335: answers for 10 minutes.
1.243     albertel 14336: 
1.877     foxr     14337: =item *
                   14338: 
                   14339: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14340: data base, returning a hash that is keyed by the resource name and has
                   14341: values that are the resource value.  I believe that the timestamps and
                   14342: versions are also returned.
                   14343: 
1.1236    raeburn  14344: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14345: supplemental content area. This routine caches the number of files for 
                   14346: 10 minutes.
                   14347: 
1.243     albertel 14348: =back
                   14349: 
                   14350: =head2 Course Modification
                   14351: 
                   14352: =over 4
1.191     harris41 14353: 
                   14354: =item *
                   14355: 
1.243     albertel 14356: writecoursepref($courseid,%prefs) : write preferences (environment
                   14357: database) for a course
1.191     harris41 14358: 
                   14359: =item *
                   14360: 
1.1011    raeburn  14361: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14362: 
                   14363: =item *
                   14364: 
1.1038    raeburn  14365: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14366: 
1.1167    droeschl 14367: =item *
                   14368: 
                   14369: is_course($courseid), is_course($cdom, $cnum)
                   14370: 
                   14371: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14372: two component version $cdom, $cnum. It checks if the specified course exists.
                   14373: 
                   14374: Returns:
                   14375:     undef if the course doesn't exist, otherwise
                   14376:     in scalar context the combined courseid.
                   14377:     in list context the two components of the course identifier, domain and 
                   14378:     courseid.    
                   14379: 
1.243     albertel 14380: =back
                   14381: 
                   14382: =head2 Resource Subroutines
                   14383: 
                   14384: =over 4
1.191     harris41 14385: 
                   14386: =item *
                   14387: 
1.243     albertel 14388: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14389: 
                   14390: =item *
                   14391: 
1.243     albertel 14392: repcopy($filename) : subscribes to the requested file, and attempts to
                   14393: replicate from the owning library server, Might return
1.607     raeburn  14394: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14395: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14396: resource. Expects the local filesystem pathname
                   14397: (/home/httpd/html/res/....)
                   14398: 
                   14399: =back
                   14400: 
                   14401: =head2 Resource Information
                   14402: 
                   14403: =over 4
1.191     harris41 14404: 
                   14405: =item *
                   14406: 
1.1228    raeburn  14407: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14408: and returns the value of a variety of different possible values,
                   14409: $varname should be a request string, and the other parameters can be
                   14410: used to specify who and what one is asking about. Ordinarily, $cid 
                   14411: does not need to be specified, as it is retrived from 
                   14412: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14413: within lonuserstate::loadmap() when initializing a course, before
                   14414: $env{'request.course.id'} has been set, so it needs to be provided
                   14415: in that one case.
1.243     albertel 14416: 
                   14417: Possible values for $varname are environment.lastname (or other item
                   14418: from the envirnment hash), user.name (or someother aspect about the
                   14419: user), resource.0.maxtries (or some other part and parameter of a
                   14420: resource)
1.204     albertel 14421: 
                   14422: =item *
                   14423: 
1.243     albertel 14424: directcondval($number) : get current value of a condition; reads from a state
                   14425: string
1.204     albertel 14426: 
                   14427: =item *
                   14428: 
1.243     albertel 14429: condval($condidx) : value of condition index based on state
1.204     albertel 14430: 
                   14431: =item *
                   14432: 
1.243     albertel 14433: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14434: resource's metadata, $what should be either a specific key, or either
                   14435: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14436: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14437: 
                   14438: this function automatically caches all requests
1.191     harris41 14439: 
                   14440: =item *
                   14441: 
1.243     albertel 14442: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14443: network of library servers; returns file handle of where SQL and regex results
                   14444: will be stored for query
1.191     harris41 14445: 
                   14446: =item *
                   14447: 
1.1282    raeburn  14448: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14449: return symbolic list entry (all arguments optional). 
                   14450: 
                   14451: Args: filename is the filename (including path) for the file for which a symb 
                   14452: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14453: to check access status if more than one resource was found in the bighash 
                   14454: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14455: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14456: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14457: cause possible symbs to be checked to determine if they are subject to content
                   14458: blocking, if so they will not be included as possible symbs; possibles is a
                   14459: ref to a hash, which, as a side effect, will be populated with all possible 
                   14460: symbs (content blocking not tested).
                   14461:  
1.243     albertel 14462: returns the data handle
1.191     harris41 14463: 
                   14464: =item *
                   14465: 
1.1190    raeburn  14466: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14467: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14468: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14469: on failure, user must be in a course, as it assumes the existence of
                   14470: the course initial hash, and uses $env('request.course.id'}.  The third
                   14471: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14472: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14473: encrypted; otherwise it will be null.  
1.191     harris41 14474: 
                   14475: =item *
                   14476: 
1.243     albertel 14477: symbclean($symb) : removes versions numbers from a symb, returns the
                   14478: cleaned symb
1.191     harris41 14479: 
                   14480: =item *
                   14481: 
1.243     albertel 14482: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14483: course map, user must be in a course for it to work.
1.191     harris41 14484: 
                   14485: =item *
                   14486: 
1.243     albertel 14487: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14488: 
                   14489: =item *
                   14490: 
1.243     albertel 14491: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14492: a random seed, all arguments are optional, if they aren't sent it uses the
                   14493: environment to derive them. Note: if symb isn't sent and it can't get one
                   14494: from &symbread it will use the current time as its return value
1.191     harris41 14495: 
                   14496: =item *
                   14497: 
1.243     albertel 14498: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14499: unfakeable, receipt
1.191     harris41 14500: 
                   14501: =item *
                   14502: 
1.620     albertel 14503: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14504: 
                   14505: =item *
                   14506: 
1.243     albertel 14507: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14508: 
                   14509: =item *
                   14510: 
1.243     albertel 14511: 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 14512: 
                   14513: =item *
                   14514: 
1.243     albertel 14515: 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 14516: 
                   14517: =item *
                   14518: 
1.243     albertel 14519: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14520: 
                   14521: =item *
                   14522: 
1.243     albertel 14523: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14524: forcing spreadsheet to reevaluate the resource scores next time.
                   14525: 
1.1195    raeburn  14526: =item * 
                   14527: 
1.1196    raeburn  14528: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14529: when viewing in course context.
1.1195    raeburn  14530: 
1.1196    raeburn  14531:  input: six args -- filename (decluttered), course number, course domain,
                   14532:                     url, symb (if registered) and group (if this is a 
                   14533:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14534: 
1.1196    raeburn  14535:  output: array of five scalars --
1.1195    raeburn  14536:          $cfile -- url for file editing if editable on current server
                   14537:          $home -- homeserver of resource (i.e., for author if published,
                   14538:                                           or course if uploaded.).
                   14539:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14540:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14541:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14542: 
                   14543: =item *
                   14544: 
                   14545: is_course_upload($file,$cnum,$cdom)
                   14546: 
                   14547: Used in course context to determine if current file was uploaded to 
                   14548: the course (i.e., would be found in /userfiles/docs on the course's 
                   14549: homeserver.
                   14550: 
                   14551:   input: 3 args -- filename (decluttered), course number and course domain.
                   14552:   output: boolean -- 1 if file was uploaded.
                   14553: 
1.243     albertel 14554: =back
                   14555: 
                   14556: =head2 Storing/Retreiving Data
                   14557: 
                   14558: =over 4
1.191     harris41 14559: 
                   14560: =item *
                   14561: 
1.1269    raeburn  14562: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14563: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14564: the remaining args aren't required and if they aren't passed or are '' they will
                   14565: be derived from the env (with the exception of $laststore, which is an 
                   14566: optional arg used when a user's submission is stored in grading).
                   14567: $laststore is $version=$timestamp, where $version is the most recent version
                   14568: number retrieved for the corresponding $symb in the $namespace db file, and
                   14569: $timestamp is the timestamp for that transaction (UNIX time).
                   14570: $laststore is currently only passed when cstore() is called by 
                   14571: structuretags::finalize_storage().
1.191     harris41 14572: 
                   14573: =item *
                   14574: 
1.1269    raeburn  14575: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14576: but uses critical subroutine
1.191     harris41 14577: 
                   14578: =item *
                   14579: 
1.243     albertel 14580: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14581: all args are optional
1.191     harris41 14582: 
                   14583: =item *
                   14584: 
1.717     albertel 14585: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14586: dumps the complete (or key matching regexp) namespace into a hash
                   14587: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14588: normally &store()ed into
                   14589: 
                   14590: $range should be either an integer '100' (give me the first 100
                   14591:                                            matching records)
                   14592:               or be  two integers sperated by a - with no spaces
                   14593:                  '30-50' (give me the 30th through the 50th matching
                   14594:                           records)
                   14595: 
                   14596: 
                   14597: =item *
                   14598: 
1.1269    raeburn  14599: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14600: replaces a &store() version of data with a replacement set of data
                   14601: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14602: reference. If $tolog is true, the transaction is logged in the courselog
                   14603: with an action=PUTSTORE.
1.717     albertel 14604: 
                   14605: =item *
                   14606: 
1.243     albertel 14607: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14608: works very similar to store/cstore, but all data is stored in a
                   14609: temporary location and can be reset using tmpreset, $storehash should
                   14610: be a hash reference, returns nothing on success
1.191     harris41 14611: 
                   14612: =item *
                   14613: 
1.243     albertel 14614: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14615: similar to restore, but all data is stored in a temporary location and
                   14616: can be reset using tmpreset. Returns a hash of values on success,
                   14617: error string otherwise.
1.191     harris41 14618: 
                   14619: =item *
                   14620: 
1.243     albertel 14621: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14622: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14623: 
                   14624: =item *
                   14625: 
1.243     albertel 14626: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14627: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14628: 
                   14629: =item *
                   14630: 
1.243     albertel 14631: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14632: namesp ($udom and $uname are optional)
1.191     harris41 14633: 
                   14634: =item *
                   14635: 
1.702     albertel 14636: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14637: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14638: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14639: 
1.702     albertel 14640: $range should be either an integer '100' (give me the first 100
                   14641:                                            matching records)
                   14642:               or be  two integers sperated by a - with no spaces
                   14643:                  '30-50' (give me the 30th through the 50th matching
                   14644:                           records)
1.449     matthew  14645: =item *
                   14646: 
                   14647: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14648: $store can be a scalar, an array reference, or if the amount to be 
                   14649: incremented is > 1, a hash reference.
                   14650: 
                   14651: ($udom and $uname are optional)
1.191     harris41 14652: 
                   14653: =item *
                   14654: 
1.243     albertel 14655: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14656: ($udom and $uname are optional)
1.191     harris41 14657: 
                   14658: =item *
                   14659: 
1.243     albertel 14660: cput($namespace,$storehash,$udom,$uname) : critical put
                   14661: ($udom and $uname are optional)
1.191     harris41 14662: 
                   14663: =item *
                   14664: 
1.748     albertel 14665: newput($namespace,$storehash,$udom,$uname) :
                   14666: 
                   14667: Attempts to store the items in the $storehash, but only if they don't
                   14668: currently exist, if this succeeds you can be certain that you have 
                   14669: successfully created a new key value pair in the $namespace db.
                   14670: 
                   14671: 
                   14672: Args:
                   14673:  $namespace: name of database to store values to
                   14674:  $storehash: hashref to store to the db
                   14675:  $udom: (optional) domain of user containing the db
                   14676:  $uname: (optional) name of user caontaining the db
                   14677: 
                   14678: Returns:
                   14679:  'ok' -> succeeded in storing all keys of $storehash
                   14680:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14681:                         least <key> already existed in the db (other
                   14682:                         requested keys may also already exist)
1.967     bisitz   14683:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14684:  'con_lost' -> unable to contact request server
                   14685:  'refused' -> action was not allowed by remote machine
                   14686: 
                   14687: 
                   14688: =item *
                   14689: 
1.243     albertel 14690: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14691: reference filled in from namesp (encrypts the return communication)
                   14692: ($udom and $uname are optional)
1.191     harris41 14693: 
                   14694: =item *
                   14695: 
1.243     albertel 14696: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14697: critical subroutine
                   14698: 
1.806     raeburn  14699: =item *
                   14700: 
1.860     raeburn  14701: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14702: array reference filled in from namespace found in domain level on either
                   14703: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14704: 
                   14705: =item *
                   14706: 
1.860     raeburn  14707: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14708: domain level either on specified domain server ($uhome) or primary domain 
                   14709: server ($udom and $uhome are optional)
1.806     raeburn  14710: 
1.943     raeburn  14711: =item * 
                   14712: 
1.1240    raeburn  14713: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14714: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14715: the target domain.
                   14716: 
                   14717: May also include additional key => value pairs for the following groups:
                   14718: 
                   14719: =over
                   14720: 
                   14721: =item
                   14722: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14723: 
                   14724: =over
                   14725: 
                   14726: =item defaultquota, authorquota
                   14727: 
                   14728: =back
                   14729: 
                   14730: =item
                   14731: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14732: portfolio for users).
                   14733: 
                   14734: =over
                   14735: 
                   14736: =item
                   14737: aboutme, blog, webdav, portfolio
                   14738: 
                   14739: =back
                   14740: 
                   14741: =item
                   14742: requestcourses: ability to request courses, and how requests are processed.
                   14743: 
                   14744: =over
                   14745: 
                   14746: =item
1.1305    raeburn  14747: official, unofficial, community, textbook, placement
1.1240    raeburn  14748: 
                   14749: =back
                   14750: 
                   14751: =item
                   14752: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14753: 
                   14754: =over
                   14755: 
                   14756: =item
1.1256    raeburn  14757: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14758: 
                   14759: =back
                   14760: 
                   14761: =item
                   14762: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14763: for course's uploaded content.
                   14764: 
                   14765: =over
                   14766: 
                   14767: =item
1.1246    raeburn  14768: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14769: communityquota, textbookquota, placementquota
1.1240    raeburn  14770: 
                   14771: =back
                   14772: 
                   14773: =item
                   14774: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14775: on your servers.
                   14776: 
                   14777: =over
                   14778: 
                   14779: =item 
                   14780: remotesessions, hostedsessions
                   14781: 
                   14782: =back
                   14783: 
                   14784: =back
                   14785: 
                   14786: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14787: utility to create a configuration.db file on a domain's primary library server 
                   14788: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14789: -- corresponding values are authentication type (internal, krb4, krb5,
                   14790: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14791: will be available. Values are retrieved from cache (if current), unless the
                   14792: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14793: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14794: 
                   14795: Typical usage:
1.943     raeburn  14796: 
1.1240    raeburn  14797: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14798: 
1.243     albertel 14799: =back
                   14800: 
                   14801: =head2 Network Status Functions
                   14802: 
                   14803: =over 4
1.191     harris41 14804: 
                   14805: =item *
                   14806: 
1.1137    raeburn  14807: dirlist() : return directory list based on URI (first arg).
                   14808: 
                   14809: Inputs: 1 required, 5 optional.
                   14810: 
                   14811: =over
                   14812: 
                   14813: =item 
                   14814: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14815: 
                   14816: =item
                   14817: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14818: 
                   14819: =item
                   14820: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14821: 
                   14822: =item
                   14823: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14824: 
                   14825: =item
                   14826: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14827: 
                   14828: =item 
                   14829: $alternateRoot - path to prepend in place of path from $uri.
                   14830: 
                   14831: =back
                   14832: 
                   14833: Returns: Array of up to two items.
                   14834: 
                   14835: =over
                   14836: 
                   14837: a reference to an array of files/subdirectories
                   14838: 
                   14839: =over
                   14840: 
                   14841: Each element in the array of files/subdirectories is a & separated list of
                   14842: item name and the result of running stat on the item.  If dirlist was requested
                   14843: for a file instead of a directory, the item name will be ''. For a directory 
                   14844: listing, if the item is a metadata file, the element will end &N&M 
                   14845: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14846: default copyright set (1).  
                   14847: 
                   14848: =back
                   14849: 
                   14850: a scalar containing error condition (if encountered).
                   14851: 
                   14852: =over
                   14853: 
                   14854: =item 
                   14855: no_host (no homeserver identified for $username:$domain).
                   14856: 
                   14857: =item 
                   14858: no_such_host (server contacted for listing not identified as valid host).
                   14859: 
                   14860: =item 
                   14861: con_lost (connection to remote server failed).
                   14862: 
                   14863: =item 
                   14864: refused (invalid $username:$domain received on lond side).
                   14865: 
                   14866: =item 
                   14867: no_such_dir (directory at specified path on lond side does not exist). 
                   14868: 
                   14869: =item 
                   14870: empty (directory at specified path on lond side is empty).
                   14871: 
                   14872: =over
                   14873: 
                   14874: This is currently not encountered because the &ls3, &ls2, 
                   14875: &ls (_handler) routines on the lond side do not filter out
                   14876: . and .. from a directory listing. 
                   14877: 
                   14878: =back
                   14879: 
                   14880: =back
                   14881: 
                   14882: =back
1.191     harris41 14883: 
                   14884: =item *
                   14885: 
1.243     albertel 14886: spareserver() : find server with least workload from spare.tab
                   14887: 
1.986     foxr     14888: 
                   14889: =item *
                   14890: 
                   14891: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14892: if there is no corresponding loncapa host.
                   14893: 
1.243     albertel 14894: =back
                   14895: 
1.986     foxr     14896: 
1.243     albertel 14897: =head2 Apache Request
                   14898: 
                   14899: =over 4
1.191     harris41 14900: 
                   14901: =item *
                   14902: 
1.243     albertel 14903: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14904: localhost, posts hash
                   14905: 
                   14906: =back
                   14907: 
                   14908: =head2 Data to String to Data
                   14909: 
                   14910: =over 4
1.191     harris41 14911: 
                   14912: =item *
                   14913: 
1.243     albertel 14914: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14915: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14916: 
                   14917: =item *
                   14918: 
1.243     albertel 14919: hashref2str($hashref) : convert a hashref into a string complete with
                   14920: escaping and '=' and '&' separators, supports elements that are
                   14921: arrayrefs and hashrefs
1.191     harris41 14922: 
                   14923: =item *
                   14924: 
1.243     albertel 14925: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14926: with escaping and '&' separators, supports elements that are arrayrefs
                   14927: and hashrefs
1.191     harris41 14928: 
                   14929: =item *
                   14930: 
1.243     albertel 14931: str2hash($string) : convert string to hash using unescaping and
                   14932: splitting on '=' and '&', supports elements that are arrayrefs and
                   14933: hashrefs
1.191     harris41 14934: 
                   14935: =item *
                   14936: 
1.243     albertel 14937: str2array($string) : convert string to hash using unescaping and
                   14938: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14939: 
                   14940: =back
                   14941: 
                   14942: =head2 Logging Routines
                   14943: 
                   14944: 
                   14945: These routines allow one to make log messages in the lonnet.log and
                   14946: lonnet.perm logfiles.
1.191     harris41 14947: 
1.1119    foxr     14948: =over 4
                   14949: 
1.191     harris41 14950: =item *
                   14951: 
1.243     albertel 14952: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14953: 
                   14954: =item *
                   14955: 
1.243     albertel 14956: logthis() : append message to the normal lonnet.log file, it gets
                   14957: preiodically rolled over and deleted.
1.191     harris41 14958: 
                   14959: =item *
                   14960: 
1.243     albertel 14961: logperm() : append a permanent message to lonnet.perm.log, this log
                   14962: file never gets deleted by any automated portion of the system, only
                   14963: messages of critical importance should go in here.
                   14964: 
1.1119    foxr     14965: 
1.243     albertel 14966: =back
                   14967: 
                   14968: =head2 General File Helper Routines
                   14969: 
                   14970: =over 4
1.191     harris41 14971: 
                   14972: =item *
                   14973: 
1.481     raeburn  14974: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14975: (a) files in /uploaded
                   14976:   (i) If a local copy of the file exists - 
                   14977:       compares modification date of local copy with last-modified date for 
                   14978:       definitive version stored on home server for course. If local copy is 
                   14979:       stale, requests a new version from the home server and stores it. 
                   14980:       If the original has been removed from the home server, then local copy 
                   14981:       is unlinked.
                   14982:   (ii) If local copy does not exist -
                   14983:       requests the file from the home server and stores it. 
                   14984:   
                   14985:   If $caller is 'uploadrep':  
                   14986:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14987:     for request for files originally uploaded via DOCS. 
                   14988:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14989:   
                   14990:   Otherwise:
                   14991:      This indicates a call from the content generation phase of the request.
                   14992:      -  returns the entire contents of the file or -1.
                   14993:      
                   14994: (b) files in /res
                   14995:    - returns the entire contents of a file or -1; 
                   14996:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14997: 
1.712     albertel 14998: 
                   14999: =item *
                   15000: 
                   15001: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15002:                   reference
                   15003: 
                   15004: returns either a stat() list of data about the file or an empty list
                   15005: if the file doesn't exist or couldn't find out about it (connection
                   15006: problems or user unknown)
                   15007: 
1.191     harris41 15008: =item *
                   15009: 
1.243     albertel 15010: filelocation($dir,$file) : returns file system location of a file
                   15011: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15012: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15013: and a file of ../bob will become /a/bob)
1.191     harris41 15014: 
                   15015: =item *
                   15016: 
                   15017: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15018: filelocation except for hrefs
                   15019: 
                   15020: =item *
                   15021: 
1.1261    raeburn  15022: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15023: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15024: 
1.243     albertel 15025: =back
                   15026: 
1.608     albertel 15027: =head2 Usererfile file routines (/uploaded*)
                   15028: 
                   15029: =over 4
                   15030: 
                   15031: =item *
                   15032: 
                   15033: userfileupload(): main rotine for putting a file in a user or course's
                   15034:                   filespace, arguments are,
                   15035: 
1.620     albertel 15036:  formname - required - this is the name of the element in $env where the
1.608     albertel 15037:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15038:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15039:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15040:  context - if coursedoc, store the file in the course of the active role
                   15041:              of the current user; 
                   15042:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15043:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15044:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15045:          if undefined, it will be placed in "unknown"
                   15046: 
                   15047:  (This routine calls clean_filename() to remove any dangerous
                   15048:  characters from the filename, and then calls finuserfileupload() to
                   15049:  complete the transaction)
                   15050: 
                   15051:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15052:  and /adm/notfound.html if unsuccessful
                   15053: 
                   15054: =item *
                   15055: 
                   15056: clean_filename(): routine for cleaing a filename up for storage in
                   15057:                  userfile space, argument is:
                   15058: 
                   15059:  filename - proposed filename
                   15060: 
                   15061: returns: the new clean filename
                   15062: 
                   15063: =item *
                   15064: 
1.1090    raeburn  15065: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15066: userspace, probably shouldn't be called directly
                   15067: 
                   15068:   docuname: username or courseid of destination for the file
                   15069:   docudom: domain of user/course of destination for the file
                   15070:   formname: same as for userfileupload()
1.1090    raeburn  15071:   fname: filename (including subdirectories) for the file
                   15072:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15073:   allfiles: reference to hash used to store objects found by parser
                   15074:   codebase: reference to hash used for codebases of java objects found by parser
                   15075:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15076:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15077:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15078:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15079:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15080:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15081:   mimetype: reference to scalar to accommodate mime type determined
                   15082:             from File::MMagic if $parser = parse.
1.608     albertel 15083: 
                   15084:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15085:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15086:  was 'overwrite').
                   15087:  
1.608     albertel 15088: 
                   15089: =item *
                   15090: 
                   15091: renameuserfile(): renames an existing userfile to a new name
                   15092: 
                   15093:   Args:
                   15094:    docuname: username or courseid of destination for the file
                   15095:    docudom: domain of user/course of destination for the file
                   15096:    old: current file name (including any subdirs under userfiles)
                   15097:    new: desired file name (including any subdirs under userfiles)
                   15098: 
                   15099: =item *
                   15100: 
                   15101: mkdiruserfile(): creates a directory is a userfiles dir
                   15102: 
                   15103:   Args:
                   15104:    docuname: username or courseid of destination for the file
                   15105:    docudom: domain of user/course of destination for the file
                   15106:    dir: dir to create (including any subdirs under userfiles)
                   15107: 
                   15108: =item *
                   15109: 
                   15110: removeuserfile(): removes a file that exists in userfiles
                   15111: 
                   15112:   Args:
                   15113:    docuname: username or courseid of destination for the file
                   15114:    docudom: domain of user/course of destination for the file
                   15115:    fname: filname to delete (including any subdirs under userfiles)
                   15116: 
                   15117: =item *
                   15118: 
                   15119: removeuploadedurl(): convience function for removeuserfile()
                   15120: 
                   15121:   Args:
                   15122:    url:  a full /uploaded/... url to delete
                   15123: 
1.747     albertel 15124: =item * 
                   15125: 
                   15126: get_portfile_permissions():
                   15127:   Args:
                   15128:     domain: domain of user or course contain the portfolio files
                   15129:     user: name of user or num of course contain the portfolio files
                   15130:   Returns:
                   15131:     hashref of a dump of the proper file_permissions.db
                   15132:    
                   15133: 
                   15134: =item * 
                   15135: 
                   15136: get_access_controls():
                   15137: 
                   15138: Args:
                   15139:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15140:   group: (optional) the group you want the files associated with
                   15141:   file: (optional) the file you want access info on
                   15142: 
                   15143: Returns:
1.749     raeburn  15144:     a hash (keys are file names) of hashes containing
                   15145:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15146:         values are XML containing access control settings (see below) 
1.747     albertel 15147: 
                   15148: Internal notes:
                   15149: 
1.749     raeburn  15150:  access controls are stored in file_permissions.db as key=value pairs.
                   15151:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15152:         where scope -> public,guest,course,group,domains or users.
                   15153:               end -> UNIX time for end of access (0 -> no end date)
                   15154:               start -> UNIX time for start of access
                   15155: 
                   15156:     value -> XML description of access control
                   15157:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15158:             <start></start>
                   15159:             <end></end>
                   15160: 
                   15161:             <password></password>  for scope type = guest
                   15162: 
                   15163:             <domain></domain>     for scope type = course or group
                   15164:             <number></number>
                   15165:             <roles id="">
                   15166:              <role></role>
                   15167:              <access></access>
                   15168:              <section></section>
                   15169:              <group></group>
                   15170:             </roles>
                   15171: 
                   15172:             <dom></dom>         for scope type = domains
                   15173: 
                   15174:             <users>             for scope type = users
                   15175:              <user>
                   15176:               <uname></uname>
                   15177:               <udom></udom>
                   15178:              </user>
                   15179:             </users>
                   15180:            </scope> 
                   15181:               
                   15182:  Access data is also aggregated for each file in an additional key=value pair:
                   15183:  key -> path to file/file_name\0accesscontrol 
                   15184:  value -> reference to hash
                   15185:           hash contains key = value pairs
                   15186:           where key = uniqueID:scope_end_start
                   15187:                 value = UNIX time record was last updated
                   15188: 
                   15189:           Used to improve speed of look-ups of access controls for each file.  
                   15190:  
                   15191:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15192: 
1.1198    raeburn  15193: =item *
                   15194: 
1.749     raeburn  15195: modify_access_controls():
                   15196: 
                   15197: Modifies access controls for a portfolio file
                   15198: Args
                   15199: 1. file name
                   15200: 2. reference to hash of required changes,
                   15201: 3. domain
                   15202: 4. username
                   15203:   where domain,username are the domain of the portfolio owner 
                   15204:   (either a user or a course) 
                   15205: 
                   15206: Returns:
                   15207: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15208: 2. result of deletions ('ok' or 'error', with error message).
                   15209: 3. reference to hash of any new or updated access controls.
                   15210: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15211:    key = integer (inbound ID)
1.1198    raeburn  15212:    value = uniqueID
                   15213: 
                   15214: =item *
                   15215: 
                   15216: get_timebased_id():
                   15217: 
                   15218: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15219: course via the Course Editor (e.g., folders, composite pages, 
                   15220: group bulletin boards).
                   15221: 
                   15222: Args: (first three required; six others optional)
                   15223: 
                   15224: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15225:    docssequence, or name of group
                   15226: 
                   15227: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15228:    e.g., num, boardids
                   15229: 
                   15230: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15231:    file will be named nohist_namespace.db
                   15232: 
                   15233: 4. cdom: domain of course; default is current course domain from %env
                   15234: 
                   15235: 5. cnum: course number; default is current course number from %env
                   15236: 
                   15237: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15238:    unix timestamp to form the suffix, if the plain timestamp is already
                   15239:    in use.  Default is to not do this, but simply increment the unix 
                   15240:    timestamp by 1 until a unique key is obtained.
                   15241: 
                   15242: 7. who: holder of locking key; defaults to user:domain for user.
                   15243: 
                   15244: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15245:    retrying); default is 3.
                   15246: 
                   15247: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15248: 
                   15249: Returns:
                   15250: 
                   15251: 1. suffix obtained (numeric)
                   15252: 
                   15253: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15254: 
                   15255: 3. error: contains (localized) error message if an error occurred.
                   15256: 
1.747     albertel 15257: 
1.608     albertel 15258: =back
                   15259: 
1.243     albertel 15260: =head2 HTTP Helper Routines
                   15261: 
                   15262: =over 4
                   15263: 
1.191     harris41 15264: =item *
                   15265: 
                   15266: escape() : unpack non-word characters into CGI-compatible hex codes
                   15267: 
                   15268: =item *
                   15269: 
                   15270: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15271: 
1.243     albertel 15272: =back
                   15273: 
                   15274: =head1 PRIVATE SUBROUTINES
                   15275: 
                   15276: =head2 Underlying communication routines (Shouldn't call)
                   15277: 
                   15278: =over 4
                   15279: 
                   15280: =item *
                   15281: 
                   15282: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15283: 
                   15284: =item *
                   15285: 
                   15286: reply() : uses subreply to send a message to remote machine, logs all failures
                   15287: 
                   15288: =item *
                   15289: 
                   15290: critical() : passes a critical message to another server; if cannot
                   15291: get through then place message in connection buffer directory and
                   15292: returns con_delayed, if incapable of saving message, returns
                   15293: con_failed
                   15294: 
                   15295: =item *
                   15296: 
                   15297: reconlonc() : tries to reconnect lonc client processes.
                   15298: 
                   15299: =back
                   15300: 
                   15301: =head2 Resource Access Logging
                   15302: 
                   15303: =over 4
                   15304: 
                   15305: =item *
                   15306: 
                   15307: flushcourselogs() : flush (save) buffer logs and access logs
                   15308: 
                   15309: =item *
                   15310: 
                   15311: courselog($what) : save message for course in hash
                   15312: 
                   15313: =item *
                   15314: 
                   15315: courseacclog($what) : save message for course using &courselog().  Perform
                   15316: special processing for specific resource types (problems, exams, quizzes, etc).
                   15317: 
1.191     harris41 15318: =item *
                   15319: 
                   15320: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15321: as a PerlChildExitHandler
1.243     albertel 15322: 
                   15323: =back
                   15324: 
                   15325: =head2 Other
                   15326: 
                   15327: =over 4
                   15328: 
                   15329: =item *
                   15330: 
                   15331: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15332: 
                   15333: =back
                   15334: 
                   15335: =cut
1.877     foxr     15336: 

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