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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1332  ! raeburn     4: # $Id: lonnet.pm,v 1.1331 2016/12/05 00:52:02 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.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.1155    raeburn   653:     if ($name eq '') {
                    654:         $name = 'lonID';
                    655:     }
                    656:     my $lonid=$cookies{$name};
1.916     albertel  657:     return undef if (!$lonid);
                    658: 
                    659:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   660:     my $lonidsdir;
                    661:     if ($name eq 'lonDAV') {
                    662:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    663:     } else {
                    664:         $lonidsdir=$r->dir_config('lonIDsDir');
                    665:     }
1.916     albertel  666:     return undef if (!-e "$lonidsdir/$handle.id");
                    667: 
1.917     albertel  668:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    669:     return undef if (!$opened);
1.916     albertel  670: 
                    671:     flock($idf,LOCK_SH);
                    672:     my %disk_env;
                    673:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    674: 	    &GDBM_READER(),0640)) {
                    675: 	return undef;	
                    676:     }
                    677: 
                    678:     if (!defined($disk_env{'user.name'})
                    679: 	|| !defined($disk_env{'user.domain'})) {
                    680: 	return undef;
                    681:     }
1.1245    raeburn   682: 
                    683:     if (ref($userhashref) eq 'HASH') {
                    684:         $userhashref->{'name'} = $disk_env{'user.name'};
                    685:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   686:     }
1.1245    raeburn   687: 
1.916     albertel  688:     return $handle;
                    689: }
                    690: 
1.830     albertel  691: sub timed_flock {
                    692:     my ($file,$lock_type) = @_;
                    693:     my $failed=0;
                    694:     eval {
                    695: 	local $SIG{__DIE__}='DEFAULT';
                    696: 	local $SIG{ALRM}=sub {
                    697: 	    $failed=1;
                    698: 	    die("failed lock");
                    699: 	};
                    700: 	alarm(13);
                    701: 	flock($file,$lock_type);
                    702: 	alarm(0);
                    703:     };
                    704:     if ($failed) {
                    705: 	return undef;
                    706:     } else {
                    707: 	return 1;
                    708:     }
                    709: }
                    710: 
1.5       www       711: # ---------------------------------------------------------- Append Environment
                    712: 
                    713: sub appenv {
1.949     raeburn   714:     my ($newenv,$roles) = @_;
                    715:     if (ref($newenv) eq 'HASH') {
                    716:         foreach my $key (keys(%{$newenv})) {
                    717:             my $refused = 0;
                    718: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    719:                 $refused = 1;
                    720:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   721:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   722:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    723:                         $refused = 0;
                    724:                     }
                    725:                 }
                    726:             }
                    727:             if ($refused) {
                    728:                 &logthis("<font color=\"blue\">WARNING: ".
                    729:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    730:                          .'</font>');
                    731: 	        delete($newenv->{$key});
                    732:             } else {
                    733:                 $env{$key}=$newenv->{$key};
                    734:             }
                    735:         }
                    736:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    737:         if ($opened
                    738: 	    && &timed_flock($env_file,LOCK_EX)
                    739: 	    &&
                    740: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    741: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    742: 	    while (my ($key,$value) = each(%{$newenv})) {
                    743: 	        $disk_env{$key} = $value;
                    744: 	    }
                    745: 	    untie(%disk_env);
1.35      www       746:         }
1.191     harris41  747:     }
1.56      www       748:     return 'ok';
                    749: }
                    750: # ----------------------------------------------------- Delete from Environment
                    751: 
                    752: sub delenv {
1.1104    raeburn   753:     my ($delthis,$regexp,$roles) = @_;
                    754:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    755:         my $refused = 1;
                    756:         if (ref($roles) eq 'ARRAY') {
                    757:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    758:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    759:                 $refused = 0;
                    760:             }
                    761:         }
                    762:         if ($refused) {
                    763:             &logthis("<font color=\"blue\">WARNING: ".
                    764:                      "Attempt to delete from environment ".$delthis);
                    765:             return 'error';
                    766:         }
1.56      www       767:     }
1.917     albertel  768:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    769:     if ($opened
1.915     albertel  770: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  771: 	&&
                    772: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    773: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  774: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   775: 	    if ($regexp) {
                    776:                 if ($key=~/^$delthis/) {
                    777:                     delete($env{$key});
                    778:                     delete($disk_env{$key});
                    779:                 } 
                    780:             } else {
                    781:                 if ($key=~/^\Q$delthis\E/) {
                    782: 		    delete($env{$key});
                    783: 		    delete($disk_env{$key});
                    784: 	        }
                    785:             }
1.448     albertel  786: 	}
1.783     albertel  787: 	untie(%disk_env);
1.5       www       788:     }
                    789:     return 'ok';
1.369     albertel  790: }
                    791: 
1.790     albertel  792: sub get_env_multiple {
                    793:     my ($name) = @_;
                    794:     my @values;
                    795:     if (defined($env{$name})) {
                    796:         # exists is it an array
                    797:         if (ref($env{$name})) {
                    798:             @values=@{ $env{$name} };
                    799:         } else {
                    800:             $values[0]=$env{$name};
                    801:         }
                    802:     }
                    803:     return(@values);
                    804: }
                    805: 
1.958     www       806: # ------------------------------------------------------------------- Locking
                    807: 
                    808: sub set_lock {
                    809:     my ($text)=@_;
                    810:     $locknum++;
                    811:     my $id=$$.'-'.$locknum;
                    812:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    813:              'session.lock.'.$id => $text});
                    814:     return $id;
                    815: }
                    816: 
                    817: sub get_locks {
                    818:     my $num=0;
                    819:     my %texts=();
                    820:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    821:        if ($lock=~/\w/) {
                    822:           $num++;
                    823:           $texts{$lock}=$env{'session.lock.'.$lock};
                    824:        }
                    825:    }
                    826:    return ($num,%texts);
                    827: }
                    828: 
                    829: sub remove_lock {
                    830:     my ($id)=@_;
                    831:     my $newlocks='';
                    832:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    833:        if (($lock=~/\w/) && ($lock ne $id)) {
                    834:           $newlocks.=','.$lock;
                    835:        }
                    836:     }
                    837:     &appenv({'session.locks' => $newlocks});
                    838:     &delenv('session.lock.'.$id);
                    839: }
                    840: 
                    841: sub remove_all_locks {
                    842:     my $activelocks=$env{'session.locks'};
                    843:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    844:        if ($lock=~/\w/) {
                    845:           &remove_lock($lock);
                    846:        }
                    847:     }
                    848: }
                    849: 
                    850: 
1.369     albertel  851: # ------------------------------------------ Find out current server userload
                    852: sub userload {
                    853:     my $numusers=0;
                    854:     {
                    855: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    856: 	my $filename;
                    857: 	my $curtime=time;
                    858: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  859: 	    next if ($filename eq '.' || $filename eq '..');
                    860: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  861: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  862: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  863: 	}
                    864: 	closedir(LONIDS);
                    865:     }
                    866:     my $userloadpercent=0;
                    867:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    868:     if ($maxuserload) {
1.371     albertel  869: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  870:     }
1.372     albertel  871:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  872:     return $userloadpercent;
1.283     www       873: }
                    874: 
1.1       albertel  875: # ------------------------------ Find server with least workload from spare.tab
1.11      www       876: 
1.1       albertel  877: sub spareserver {
1.1083    raeburn   878:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  879:     my $spare_server;
1.370     albertel  880:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  881:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    882:                                                      :  $userloadpercent;
1.1083    raeburn   883:     my ($uint_dom,$remotesessions);
                    884:     if (($udom ne '') && (&domain($udom) ne '')) {
                    885:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    886:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    887:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    888:         $remotesessions = $udomdefaults{'remotesessions'};
                    889:     }
1.1123    raeburn   890:     my $spareshash = &this_host_spares($udom);
                    891:     if (ref($spareshash) eq 'HASH') {
                    892:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    893:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   894:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    895:                                              $try_server));
1.1123    raeburn   896: 	        ($spare_server, $lowest_load) =
                    897: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    898:             }
1.1083    raeburn   899:         }
1.784     albertel  900: 
1.1123    raeburn   901:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    902: 
                    903:         if (!$found_server) {
                    904:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    905: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   906:                     next unless (&spare_can_host($udom,$uint_dom,
                    907:                                                  $remotesessions,$try_server));
1.1123    raeburn   908: 	            ($spare_server, $lowest_load) =
                    909: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    910:                 }
                    911: 	    }
                    912:         }
1.784     albertel  913:     }
                    914: 
                    915:     if (!$want_server_name) {
1.968     raeburn   916:         my $protocol = 'http';
                    917:         if ($protocol{$spare_server} eq 'https') {
                    918:             $protocol = $protocol{$spare_server};
                    919:         }
1.1001    raeburn   920:         if (defined($spare_server)) {
                    921:             my $hostname = &hostname($spare_server);
1.1083    raeburn   922:             if (defined($hostname)) {
1.1001    raeburn   923: 	        $spare_server = $protocol.'://'.$hostname;
                    924:             }
                    925:         }
1.784     albertel  926:     }
                    927:     return $spare_server;
                    928: }
                    929: 
                    930: sub compare_server_load {
1.1253    raeburn   931:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    932: 
                    933:     if ($required) {
                    934:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    935:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    936:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    937:         if (($major eq '' && $minor eq '') ||
                    938:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    939:             return ($spare_server,$lowest_load);
                    940:         }
                    941:     }
1.784     albertel  942: 
                    943:     my $loadans     = &reply('load',    $try_server);
                    944:     my $userloadans = &reply('userload',$try_server);
                    945: 
                    946:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   947: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  948:     }
                    949: 
                    950:     my $load;
                    951:     if ($loadans =~ /\d/) {
                    952: 	if ($userloadans =~ /\d/) {
                    953: 	    #both are numbers, pick the bigger one
                    954: 	    $load = ($loadans > $userloadans) ? $loadans 
                    955: 		                              : $userloadans;
1.411     albertel  956: 	} else {
1.784     albertel  957: 	    $load = $loadans;
1.411     albertel  958: 	}
1.784     albertel  959:     } else {
                    960: 	$load = $userloadans;
                    961:     }
                    962: 
                    963:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    964: 	$spare_server = $try_server;
                    965: 	$lowest_load  = $load;
1.370     albertel  966:     }
1.784     albertel  967:     return ($spare_server,$lowest_load);
1.202     matthew   968: }
1.914     albertel  969: 
                    970: # --------------------------- ask offload servers if user already has a session
                    971: sub find_existing_session {
                    972:     my ($udom,$uname) = @_;
1.1123    raeburn   973:     my $spareshash = &this_host_spares($udom);
                    974:     if (ref($spareshash) eq 'HASH') {
                    975:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    976:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    977:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    978:             }
                    979:         }
                    980:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    981:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    982:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    983:             }
                    984:         }
1.914     albertel  985:     }
                    986:     return;
                    987: }
                    988: 
                    989: # -------------------------------- ask if server already has a session for user
                    990: sub has_user_session {
                    991:     my ($lonid,$udom,$uname) = @_;
                    992:     my $result = &reply(join(':','userhassession',
                    993: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    994:     return 1 if ($result eq 'ok');
                    995: 
                    996:     return 0;
                    997: }
                    998: 
1.1076    raeburn   999: # --------- determine least loaded server in a user's domain which allows login
                   1000: 
                   1001: sub choose_server {
1.1259    raeburn  1002:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1003:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1004:     my %servers = &get_servers($udom);
1.1076    raeburn  1005:     my $lowest_load = 30000;
1.1259    raeburn  1006:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1007:     if ($skiploadbal) {
                   1008:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1009:         unless (defined($cached)) {
                   1010:             my $cachetime = 60*60*24;
                   1011:             my %domconfig =
                   1012:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1013:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1014:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1015:                                            $cachetime);
                   1016:             }
                   1017:         }
                   1018:     }
1.1076    raeburn  1019:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1020:         if ($skiploadbal) {
                   1021:             if (ref($balancers) eq 'HASH') {
                   1022:                 next if (exists($balancers->{$lonhost}));
                   1023:             }
                   1024:         }   
1.1115    raeburn  1025:         my $loginvia;
                   1026:         if ($checkloginvia) {
                   1027:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1028:             if ($loginvia) {
                   1029:                 my ($server,$path) = split(/:/,$loginvia);
                   1030:                 ($login_host, $lowest_load) =
1.1253    raeburn  1031:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1032:                 if ($login_host eq $server) {
                   1033:                     $portal_path = $path;
1.1151    raeburn  1034:                     $isredirect = 1;
1.1116    raeburn  1035:                 }
                   1036:             } else {
                   1037:                 ($login_host, $lowest_load) =
1.1253    raeburn  1038:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1039:                 if ($login_host eq $lonhost) {
                   1040:                     $portal_path = '';
1.1151    raeburn  1041:                     $isredirect = ''; 
1.1116    raeburn  1042:                 }
                   1043:             }
                   1044:         } else {
1.1076    raeburn  1045:             ($login_host, $lowest_load) =
1.1253    raeburn  1046:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1047:         }
                   1048:     }
                   1049:     if ($login_host ne '') {
1.1116    raeburn  1050:         $hostname = &hostname($login_host);
1.1076    raeburn  1051:     }
1.1331    raeburn  1052:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1053: }
                   1054: 
1.202     matthew  1055: # --------------------------------------------- Try to change a user's password
                   1056: 
                   1057: sub changepass {
1.799     raeburn  1058:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1059:     $currentpass = &escape($currentpass);
                   1060:     $newpass     = &escape($newpass);
1.1030    raeburn  1061:     my $lonhost = $perlvar{'lonHostID'};
                   1062:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1063: 		       $server);
                   1064:     if (! $answer) {
                   1065: 	&logthis("No reply on password change request to $server ".
                   1066: 		 "by $uname in domain $udom.");
                   1067:     } elsif ($answer =~ "^ok") {
                   1068:         &logthis("$uname in $udom successfully changed their password ".
                   1069: 		 "on $server.");
                   1070:     } elsif ($answer =~ "^pwchange_failure") {
                   1071: 	&logthis("$uname in $udom was unable to change their password ".
                   1072: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1073: 		 "or pwchange");
                   1074:     } elsif ($answer =~ "^non_authorized") {
                   1075:         &logthis("$uname in $udom did not get their password correct when ".
                   1076: 		 "attempting to change it on $server.");
                   1077:     } elsif ($answer =~ "^auth_mode_error") {
                   1078:         &logthis("$uname in $udom attempted to change their password despite ".
                   1079: 		 "not being locally or internally authenticated on $server.");
                   1080:     } elsif ($answer =~ "^unknown_user") {
                   1081:         &logthis("$uname in $udom attempted to change their password ".
                   1082: 		 "on $server but were unable to because $server is not ".
                   1083: 		 "their home server.");
                   1084:     } elsif ($answer =~ "^refused") {
                   1085: 	&logthis("$server refused to change $uname in $udom password because ".
                   1086: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1087:     } elsif ($answer =~ "invalid_client") {
                   1088:         &logthis("$server refused to change $uname in $udom password because ".
                   1089:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1090:     }
                   1091:     return $answer;
1.1       albertel 1092: }
                   1093: 
1.169     harris41 1094: # ----------------------- Try to determine user's current authentication scheme
                   1095: 
                   1096: sub queryauthenticate {
                   1097:     my ($uname,$udom)=@_;
1.456     albertel 1098:     my $uhome=&homeserver($uname,$udom);
                   1099:     if (!$uhome) {
                   1100: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1101: 	return 'no_host';
                   1102:     }
                   1103:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1104:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1105: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1106:     }
1.456     albertel 1107:     return $answer;
1.169     harris41 1108: }
                   1109: 
1.1       albertel 1110: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1111: 
1.1       albertel 1112: sub authenticate {
1.1073    raeburn  1113:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1114:     $upass=&escape($upass);
                   1115:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1116:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1117:     my $newhome;
1.836     www      1118:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1119: # Maybe the machine was offline and only re-appeared again recently?
                   1120:         &reconlonc();
                   1121: # One more
1.952     raeburn  1122: 	$uhome=&homeserver($uname,$udom,1);
                   1123:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1124:             if (defined(&domain($udom,'primary'))) {
                   1125:                 $newhome=&domain($udom,'primary');
                   1126:             }
                   1127:             if ($newhome ne '') {
                   1128:                 $uhome = $newhome;
                   1129:             }
                   1130:         }
1.836     www      1131: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1132: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1133: 	    return 'no_host';
                   1134:         }
1.1       albertel 1135:     }
1.1073    raeburn  1136:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1137:     if ($answer eq 'authorized') {
1.952     raeburn  1138:         if ($newhome) {
                   1139:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1140:             return 'no_account_on_host'; 
                   1141:         } else {
                   1142:             &logthis("User $uname at $udom authorized by $uhome");
                   1143:             return $uhome;
                   1144:         }
1.471     albertel 1145:     }
                   1146:     if ($answer eq 'non_authorized') {
                   1147: 	&logthis("User $uname at $udom rejected by $uhome");
                   1148: 	return 'no_host'; 
1.9       www      1149:     }
1.471     albertel 1150:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1151:     return 'no_host';
                   1152: }
                   1153: 
1.1073    raeburn  1154: sub can_host_session {
1.1074    raeburn  1155:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1156:     my $canhost = 1;
1.1074    raeburn  1157:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1158:     if (ref($remotesessions) eq 'HASH') {
                   1159:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1160:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1161:                 $canhost = 0;
                   1162:             } else {
                   1163:                 $canhost = 1;
                   1164:             }
                   1165:         }
                   1166:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1167:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1168:                 $canhost = 1;
                   1169:             } else {
                   1170:                 $canhost = 0;
                   1171:             }
                   1172:         }
                   1173:         if ($canhost) {
                   1174:             if ($remotesessions->{'version'} ne '') {
                   1175:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1176:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1177:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1178:                         my $major = $1;
                   1179:                         my $minor = $2;
                   1180:                         if (($major < $reqmajor ) ||
                   1181:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1182:                             $canhost = 0;
                   1183:                         }
                   1184:                     } else {
                   1185:                         $canhost = 0;
                   1186:                     }
                   1187:                 }
                   1188:             }
                   1189:         }
                   1190:     }
                   1191:     if ($canhost) {
                   1192:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1193:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1194:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1195:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1196:                 if (($uint_dom ne '') && 
                   1197:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1198:                     $canhost = 0;
                   1199:                 } else {
                   1200:                     $canhost = 1;
                   1201:                 }
                   1202:             }
                   1203:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1204:                 if (($uint_dom ne '') && 
                   1205:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1206:                     $canhost = 1;
                   1207:                 } else {
                   1208:                     $canhost = 0;
                   1209:                 }
                   1210:             }
                   1211:         }
                   1212:     }
                   1213:     return $canhost;
                   1214: }
                   1215: 
1.1083    raeburn  1216: sub spare_can_host {
                   1217:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1218:     my $canhost=1;
1.1279    raeburn  1219:     my $try_server_hostname = &hostname($try_server);
                   1220:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1221:     my $serverhomedom = &host_domain($serverhomeID);
                   1222:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1223:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1224:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1225:             $canhost = 0;
                   1226:         }
                   1227:     }
                   1228:     if (($canhost) && ($uint_dom)) {
                   1229:         my @intdoms;
                   1230:         my $internet_names = &get_internet_names($try_server);
                   1231:         if (ref($internet_names) eq 'ARRAY') {
                   1232:             @intdoms = @{$internet_names};
                   1233:         }
                   1234:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1235:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1236:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1237:                                          $remotesessions,
                   1238:                                          $defdomdefaults{'hostedsessions'});
                   1239:         }
1.1083    raeburn  1240:     }
                   1241:     return $canhost;
                   1242: }
                   1243: 
1.1123    raeburn  1244: sub this_host_spares {
                   1245:     my ($dom) = @_;
1.1126    raeburn  1246:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1247:     my @hosts = &current_machine_ids();
                   1248:     foreach my $lonhost (@hosts) {
                   1249:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1250:             $dom_in_use = $dom;
                   1251:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1252:             last;
                   1253:         }
                   1254:     }
1.1126    raeburn  1255:     if ($dom_in_use ne '') {
                   1256:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1257:     }
                   1258:     if (ref($result) ne 'HASH') {
                   1259:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1260:         $dom_in_use = &host_domain($lonhost_in_use);
                   1261:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1262:         if (ref($result) ne 'HASH') {
                   1263:             $result = \%spareid;
                   1264:         }
                   1265:     }
                   1266:     return $result;
                   1267: }
                   1268: 
                   1269: sub spares_for_offload  {
                   1270:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1271:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1272:     if (defined($cached)) {
                   1273:         return $result;
                   1274:     } else {
1.1126    raeburn  1275:         my $cachetime = 60*60*24;
                   1276:         my %domconfig =
                   1277:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1278:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1279:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1280:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1281:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1282:                 }
                   1283:             }
                   1284:         }
                   1285:     }
1.1126    raeburn  1286:     return;
1.1123    raeburn  1287: }
                   1288: 
1.1129    raeburn  1289: sub get_lonbalancer_config {
                   1290:     my ($servers) = @_;
                   1291:     my ($currbalancer,$currtargets);
                   1292:     if (ref($servers) eq 'HASH') {
                   1293:         foreach my $server (keys(%{$servers})) {
                   1294:             my %what = (
                   1295:                          spareid => 1,
                   1296:                          perlvar => 1,
                   1297:                        );
                   1298:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1299:             if ($result eq 'ok') {
                   1300:                 if (ref($returnhash) eq 'HASH') {
                   1301:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1302:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1303:                             $currbalancer = $server;
                   1304:                             $currtargets = {};
                   1305:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1306:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1307:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1308:                                 }
                   1309:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1310:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1311:                                 }
                   1312:                             }
                   1313:                             last;
                   1314:                         }
                   1315:                     }
                   1316:                 }
                   1317:             }
                   1318:         }
                   1319:     }
                   1320:     return ($currbalancer,$currtargets);
                   1321: }
                   1322: 
                   1323: sub check_loadbalancing {
1.1331    raeburn  1324:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1325:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1326:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1327:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1328:     my @hosts = &current_machine_ids();
1.1129    raeburn  1329:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1330:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1331:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1332:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1333:     my $domneedscache;
1.1129    raeburn  1334:     my $cachetime = 60*60*24;
                   1335: 
                   1336:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1337:         $dom_in_use = $udom;
                   1338:         $homeintdom = 1;
                   1339:     } else {
                   1340:         $dom_in_use = $serverhomedom;
                   1341:     }
                   1342:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1343:     unless (defined($cached)) {
                   1344:         my %domconfig =
                   1345:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1346:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1347:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1348:         } else {
                   1349:             $domneedscache = $dom_in_use;
1.1129    raeburn  1350:         }
                   1351:     }
                   1352:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1353:         ($is_balancer,$currtargets,$currrules) = 
                   1354:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1355:         if ($is_balancer) {
                   1356:             if (ref($currrules) eq 'HASH') {
                   1357:                 if ($homeintdom) {
                   1358:                     if ($uname ne '') {
                   1359:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1360:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1361:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1362:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1363:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1364:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1365:                             }
                   1366:                         }
                   1367:                         if ($rule_in_effect eq '') {
                   1368:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1369:                             if ($userenv{'inststatus'} ne '') {
                   1370:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1371:                                 my ($othertitle,$usertypes,$types) =
                   1372:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1373:                                 if (ref($types) eq 'ARRAY') {
                   1374:                                     foreach my $type (@{$types}) {
                   1375:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1376:                                             if (exists($currrules->{$type})) {
                   1377:                                                 $rule_in_effect = $currrules->{$type};
                   1378:                                             }
                   1379:                                         }
                   1380:                                     }
                   1381:                                 }
                   1382:                             } else {
                   1383:                                 if (exists($currrules->{'default'})) {
                   1384:                                     $rule_in_effect = $currrules->{'default'};
                   1385:                                 }
                   1386:                             }
                   1387:                         }
                   1388:                     } else {
                   1389:                         if (exists($currrules->{'default'})) {
                   1390:                             $rule_in_effect = $currrules->{'default'};
                   1391:                         }
                   1392:                     }
                   1393:                 } else {
                   1394:                     if ($currrules->{'_LC_external'} ne '') {
                   1395:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1396:                     }
                   1397:                 }
                   1398:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1399:                                                        $uname,$udom);
                   1400:             }
                   1401:         }
                   1402:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1403:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1404:         unless (defined($cached)) {
                   1405:             my %domconfig =
                   1406:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1407:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1408:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1409:             } else {
                   1410:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1411:             }
                   1412:         }
                   1413:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1414:             ($is_balancer,$currtargets,$currrules) = 
                   1415:                 &check_balancer_result($result,@hosts);
                   1416:             if ($is_balancer) {
1.1129    raeburn  1417:                 if (ref($currrules) eq 'HASH') {
                   1418:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1419:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1420:                     }
                   1421:                 }
                   1422:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1423:                                                        $uname,$udom);
                   1424:             }
                   1425:         } else {
                   1426:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1427:                 $is_balancer = 1;
                   1428:                 $offloadto = &this_host_spares($dom_in_use);
                   1429:             }
1.1307    raeburn  1430:             unless (defined($cached)) {
                   1431:                 $domneedscache = $serverhomedom;
                   1432:             }
1.1129    raeburn  1433:         }
                   1434:     } else {
                   1435:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1436:             $is_balancer = 1;
                   1437:             $offloadto = &this_host_spares($dom_in_use);
                   1438:         }
1.1307    raeburn  1439:         unless (defined($cached)) {
                   1440:             $domneedscache = $serverhomedom;
                   1441:         }
                   1442:     }
                   1443:     if ($domneedscache) {
                   1444:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1445:     }
1.1176    raeburn  1446:     if ($is_balancer) {
                   1447:         my $lowest_load = 30000;
                   1448:         if (ref($offloadto) eq 'HASH') {
                   1449:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1450:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1451:                     ($otherserver,$lowest_load) =
                   1452:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1453:                 }
1.1129    raeburn  1454:             }
1.1176    raeburn  1455:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1456: 
1.1176    raeburn  1457:             if (!$found_server) {
                   1458:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1459:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1460:                         ($otherserver,$lowest_load) =
                   1461:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1462:                     }
                   1463:                 }
                   1464:             }
                   1465:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1466:             if (@{$offloadto} == 1) {
                   1467:                 $otherserver = $offloadto->[0];
                   1468:             } elsif (@{$offloadto} > 1) {
                   1469:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1470:                     ($otherserver,$lowest_load) =
                   1471:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1472:                 }
                   1473:             }
                   1474:         }
1.1331    raeburn  1475:         unless ($caller eq 'login') {
                   1476:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1477:                 $is_balancer = 0;
                   1478:                 if ($uname ne '' && $udom ne '') {
                   1479:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1480:                     
1.1331    raeburn  1481:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1482:                                  'user.loadbalcheck.time' => time});
                   1483:                     }
1.1176    raeburn  1484:                 }
1.1129    raeburn  1485:             }
                   1486:         }
                   1487:     }
                   1488:     return ($is_balancer,$otherserver);
                   1489: }
                   1490: 
1.1191    raeburn  1491: sub check_balancer_result {
                   1492:     my ($result,@hosts) = @_;
                   1493:     my ($is_balancer,$currtargets,$currrules);
                   1494:     if (ref($result) eq 'HASH') {
                   1495:         if ($result->{'lonhost'} ne '') {
                   1496:             my $currbalancer = $result->{'lonhost'};
                   1497:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1498:                 $is_balancer = 1;
                   1499:                 $currtargets = $result->{'targets'};
                   1500:                 $currrules = $result->{'rules'};
                   1501:             }
                   1502:         } else {
                   1503:             foreach my $key (keys(%{$result})) {
                   1504:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1505:                     (ref($result->{$key}) eq 'HASH')) {
                   1506:                     $is_balancer = 1;
                   1507:                     $currrules = $result->{$key}{'rules'};
                   1508:                     $currtargets = $result->{$key}{'targets'};
                   1509:                     last;
                   1510:                 }
                   1511:             }
                   1512:         }
                   1513:     }
                   1514:     return ($is_balancer,$currtargets,$currrules);
                   1515: }
                   1516: 
1.1129    raeburn  1517: sub get_loadbalancer_targets {
                   1518:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1519:     my $offloadto;
1.1175    raeburn  1520:     if ($rule_in_effect eq 'none') {
                   1521:         return [$perlvar{'lonHostID'}];
                   1522:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1523:         $offloadto = $currtargets;
                   1524:     } else {
                   1525:         if ($rule_in_effect eq 'homeserver') {
                   1526:             my $homeserver = &homeserver($uname,$udom);
                   1527:             if ($homeserver ne 'no_host') {
                   1528:                 $offloadto = [$homeserver];
                   1529:             }
                   1530:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1531:             my %domconfig =
                   1532:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1533:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1534:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1535:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1536:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1537:                     }
                   1538:                 }
                   1539:             } else {
1.1178    raeburn  1540:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1541:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1542:                 if (&hostname($remotebalancer) ne '') {
                   1543:                     $offloadto = [$remotebalancer];
                   1544:                 }
                   1545:             }
                   1546:         } elsif (&hostname($rule_in_effect) ne '') {
                   1547:             $offloadto = [$rule_in_effect];
                   1548:         }
                   1549:     }
                   1550:     return $offloadto;
                   1551: }
                   1552: 
1.1127    raeburn  1553: sub internet_dom_servers {
                   1554:     my ($dom) = @_;
                   1555:     my (%uniqservers,%servers);
                   1556:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1557:     my @machinedoms = &machine_domains($primaryserver);
                   1558:     foreach my $mdom (@machinedoms) {
                   1559:         my %currservers = %servers;
                   1560:         my %server = &get_servers($mdom);
                   1561:         %servers = (%currservers,%server);
                   1562:     }
                   1563:     my %by_hostname;
                   1564:     foreach my $id (keys(%servers)) {
                   1565:         push(@{$by_hostname{$servers{$id}}},$id);
                   1566:     }
                   1567:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1568:         if (@{$by_hostname{$hostname}} > 1) {
                   1569:             my $match = 0;
                   1570:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1571:                 if (&host_domain($id) eq $dom) {
                   1572:                     $uniqservers{$id} = $hostname;
                   1573:                     $match = 1;
                   1574:                 }
                   1575:             }
                   1576:             unless ($match) {
                   1577:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1578:             }
                   1579:         } else {
                   1580:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1581:         }
                   1582:     }
                   1583:     return %uniqservers;
                   1584: }
                   1585: 
1.1       albertel 1586: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1587: 
1.599     albertel 1588: my %homecache;
1.1       albertel 1589: sub homeserver {
1.230     stredwic 1590:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1591:     my $index="$uname:$udom";
1.426     albertel 1592: 
1.599     albertel 1593:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1594: 
                   1595:     my %servers = &get_servers($udom,'library');
                   1596:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1597:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1598: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1599: 
                   1600: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1601: 	if ($answer eq 'found') {
                   1602: 	    delete($badServerCache{$tryserver}); 
                   1603: 	    return $homecache{$index}=$tryserver;
                   1604: 	} elsif ($answer eq 'no_host') {
                   1605: 	    $badServerCache{$tryserver}=1;
                   1606: 	}
1.1       albertel 1607:     }    
                   1608:     return 'no_host';
1.70      www      1609: }
                   1610: 
1.1300    raeburn  1611: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1612: 
                   1613: sub idget {
1.1300    raeburn  1614:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1615:     my %returnhash=();
1.1300    raeburn  1616:     my @ids=(); 
                   1617:     if (ref($idsref) eq 'ARRAY') {
                   1618:         @ids = @{$idsref};
                   1619:     } else {
                   1620:         return %returnhash; 
                   1621:     }
                   1622:     if ($namespace eq '') {
                   1623:         $namespace = 'ids';
                   1624:     }
1.70      www      1625:     
1.841     albertel 1626:     my %servers = &get_servers($udom,'library');
                   1627:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1628: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1629: 	if ($namespace eq 'ids') {
                   1630: 	    $idlist=~tr/A-Z/a-z/;
                   1631: 	}
                   1632: 	my $reply;
                   1633: 	if ($namespace eq 'ids') {
                   1634: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1635: 	} else {
                   1636: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1637: 	}
1.841     albertel 1638: 	my @answer=();
                   1639: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1640: 	    @answer=split(/\&/,$reply);
                   1641: 	}                    ;
                   1642: 	my $i;
                   1643: 	for ($i=0;$i<=$#ids;$i++) {
                   1644: 	    if ($answer[$i]) {
1.1299    raeburn  1645: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1646: 	    }
1.841     albertel 1647: 	}
1.1300    raeburn  1648:     }
1.70      www      1649:     return %returnhash;
                   1650: }
                   1651: 
                   1652: # ------------------------------------- Find the IDs behind a list of usernames
                   1653: 
                   1654: sub idrget {
                   1655:     my ($udom,@unames)=@_;
                   1656:     my %returnhash=();
1.800     albertel 1657:     foreach my $uname (@unames) {
                   1658:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1659:     }
1.70      www      1660:     return %returnhash;
                   1661: }
                   1662: 
1.1300    raeburn  1663: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1664: 
                   1665: sub idput {
1.1300    raeburn  1666:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1667:     my %servers=();
1.1300    raeburn  1668:     my %ids=();
                   1669:     my %byid = ();
                   1670:     if (ref($idsref) eq 'HASH') {
                   1671:         %ids=%{$idsref};
                   1672:     }
                   1673:     if ($namespace eq '') {
                   1674:         $namespace = 'ids'; 
                   1675:     }
1.800     albertel 1676:     foreach my $uname (keys(%ids)) {
                   1677: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1678:         if ($uhom eq '') {
                   1679:             $uhom=&homeserver($uname,$udom);
                   1680:         }
1.70      www      1681:         if ($uhom ne 'no_host') {
1.800     albertel 1682:             my $esc_unam=&escape($uname);
1.1300    raeburn  1683:             if ($namespace eq 'ids') {
                   1684:                 my $id=&escape($ids{$uname});
                   1685:                 $id=~tr/A-Z/a-z/;
                   1686:                 my $esc_unam=&escape($uname);
                   1687:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1688:             } else {
1.1300    raeburn  1689:                 my @currids = split(/,/,$ids{$uname});
                   1690:                 foreach my $id (@currids) {
                   1691:                     $byid{$uhom}{$id} .= $uname.',';
                   1692:                 }
                   1693:             }
                   1694:         }
                   1695:     }
                   1696:     if ($namespace eq 'clickers') {
                   1697:         foreach my $server (keys(%byid)) {
                   1698:             if (ref($byid{$server}) eq 'HASH') {
                   1699:                 foreach my $id (keys(%{$byid{$server}})) {
                   1700:                     $byid{$server} =~ s/,$//;
                   1701:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1702:                 }
1.70      www      1703:             }
                   1704:         }
1.191     harris41 1705:     }
1.800     albertel 1706:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1707:         $servers{$server} =~ s/\&$//;
                   1708:         if ($namespace eq 'ids') {     
                   1709:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1710:         } else {
                   1711:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1712:         }
1.191     harris41 1713:     }
1.344     www      1714: }
                   1715: 
1.1300    raeburn  1716: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1717: 
                   1718: sub iddel {
1.1300    raeburn  1719:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1720:     my %result=();
1.1300    raeburn  1721:     my %ids=();
                   1722:     my %byid = ();
                   1723:     if (ref($idshashref) eq 'HASH') {
                   1724:         %ids=%{$idshashref};
                   1725:     } else {
1.1231    raeburn  1726:         return %result;
                   1727:     }
1.1300    raeburn  1728:     if ($namespace eq '') {
                   1729:         $namespace = 'ids';
                   1730:     }
1.1231    raeburn  1731:     my %servers=();
1.1300    raeburn  1732:     while (my ($id,$unamestr) = each(%ids)) {
                   1733:         if ($namespace eq 'ids') {
                   1734:             my $uhom = $uhome;
                   1735:             if ($uhom eq '') { 
                   1736:                 $uhom=&homeserver($unamestr,$udom);
                   1737:             }
                   1738:             if ($uhom ne 'no_host') {
                   1739:                 $servers{$uhom}.='&'.&escape($id);
                   1740:             }
                   1741:          } else {
                   1742:             my @curritems = split(/,/,$ids{$id});
                   1743:             foreach my $uname (@curritems) {
                   1744:                 my $uhom = $uhome;
                   1745:                 if ($uhom eq '') {
                   1746:                     $uhom=&homeserver($uname,$udom);
                   1747:                 }
                   1748:                 if ($uhom ne 'no_host') { 
                   1749:                     $byid{$uhom}{$id} .= $uname.',';
                   1750:                 }
                   1751:             }
1.1231    raeburn  1752:         }
1.1300    raeburn  1753:     }
                   1754:     if ($namespace eq 'clickers') {
                   1755:         foreach my $server (keys(%byid)) {
                   1756:             if (ref($byid{$server}) eq 'HASH') {
                   1757:                 foreach my $id (keys(%{$byid{$server}})) {
                   1758:                     $byid{$server}{$id} =~ s/,$//;
                   1759:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1760:                 }
1.1231    raeburn  1761:             }
                   1762:         }
                   1763:     }
                   1764:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1765:         $servers{$server} =~ s/\&$//;
                   1766:         if ($namespace eq 'ids') {
                   1767:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1768:         } elsif ($namespace eq 'clickers') {
                   1769:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1770:         }
1.1231    raeburn  1771:     }
                   1772:     return %result;
                   1773: }
                   1774: 
1.1300    raeburn  1775: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1776: 
                   1777: sub updateclickers {
                   1778:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1779:     my %clickers;
                   1780:     if (ref($idshashref) eq 'HASH') {
                   1781:         %clickers=%{$idshashref};
                   1782:     } else {
                   1783:         return;
                   1784:     }
                   1785:     my $items='';
                   1786:     foreach my $item (keys(%clickers)) {
                   1787:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1788:     }
                   1789:     $items=~s/\&$//;
                   1790:     my $request = "updateclickers:$udom:$action:$items";
                   1791:     if ($critical) {
                   1792:         return &critical($request,$uhome);
                   1793:     } else {
                   1794:         return &reply($request,$uhome);
                   1795:     }
                   1796: }
                   1797: 
1.1023    raeburn  1798: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1799: sub dump_dom {
1.1165    droeschl 1800:     my ($namespace, $udom, $regexp) = @_;
                   1801: 
                   1802:     $udom ||= $env{'user.domain'};
                   1803: 
                   1804:     return () unless $udom;
                   1805: 
                   1806:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1807: }
                   1808: 
1.1023    raeburn  1809: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1810: 
                   1811: sub get_dom {
1.860     raeburn  1812:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1813:     return if ($udom eq 'public');
1.806     raeburn  1814:     my $items='';
                   1815:     foreach my $item (@$storearr) {
                   1816:         $items.=&escape($item).'&';
                   1817:     }
                   1818:     $items=~s/\&$//;
1.860     raeburn  1819:     if (!$udom) {
                   1820:         $udom=$env{'user.domain'};
1.1267    raeburn  1821:         return if ($udom eq 'public');
1.860     raeburn  1822:         if (defined(&domain($udom,'primary'))) {
                   1823:             $uhome=&domain($udom,'primary');
                   1824:         } else {
1.874     albertel 1825:             undef($uhome);
1.860     raeburn  1826:         }
                   1827:     } else {
                   1828:         if (!$uhome) {
                   1829:             if (defined(&domain($udom,'primary'))) {
                   1830:                 $uhome=&domain($udom,'primary');
                   1831:             }
                   1832:         }
                   1833:     }
                   1834:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1835:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1836:         my %returnhash;
1.875     albertel 1837:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1838:             return %returnhash;
                   1839:         }
1.806     raeburn  1840:         my @pairs=split(/\&/,$rep);
                   1841:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1842:             return @pairs;
                   1843:         }
                   1844:         my $i=0;
                   1845:         foreach my $item (@$storearr) {
                   1846:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1847:             $i++;
                   1848:         }
                   1849:         return %returnhash;
                   1850:     } else {
1.880     banghart 1851:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1852:     }
                   1853: }
                   1854: 
                   1855: # -------------------------------------------- put items in domain db files 
                   1856: 
                   1857: sub put_dom {
1.860     raeburn  1858:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1859:     if (!$udom) {
                   1860:         $udom=$env{'user.domain'};
                   1861:         if (defined(&domain($udom,'primary'))) {
                   1862:             $uhome=&domain($udom,'primary');
                   1863:         } else {
1.874     albertel 1864:             undef($uhome);
1.860     raeburn  1865:         }
                   1866:     } else {
                   1867:         if (!$uhome) {
                   1868:             if (defined(&domain($udom,'primary'))) {
                   1869:                 $uhome=&domain($udom,'primary');
                   1870:             }
                   1871:         }
                   1872:     } 
                   1873:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1874:         my $items='';
                   1875:         foreach my $item (keys(%$storehash)) {
                   1876:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1877:         }
                   1878:         $items=~s/\&$//;
                   1879:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1880:     } else {
1.860     raeburn  1881:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1882:     }
                   1883: }
                   1884: 
1.1023    raeburn  1885: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1886: sub newput_dom {
1.1023    raeburn  1887:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1888:     my $result;
                   1889:     if (!$udom) {
                   1890:         $udom=$env{'user.domain'};
                   1891:     }
1.1023    raeburn  1892:     if ($udom) {
                   1893:         my $uname = &get_domainconfiguser($udom);
                   1894:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1895:     }
                   1896:     return $result;
                   1897: }
                   1898: 
1.1023    raeburn  1899: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1900: sub del_dom {
1.1023    raeburn  1901:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1902:     if (ref($storearr) eq 'ARRAY') {
                   1903:         if (!$udom) {
                   1904:             $udom=$env{'user.domain'};
                   1905:         }
1.1023    raeburn  1906:         if ($udom) {
                   1907:             my $uname = &get_domainconfiguser($udom); 
                   1908:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1909:         }
                   1910:     }
                   1911: }
                   1912: 
1.1023    raeburn  1913: # ----------------------------------construct domainconfig user for a domain 
                   1914: sub get_domainconfiguser {
                   1915:     my ($udom) = @_;
                   1916:     return $udom.'-domainconfig';
                   1917: }
                   1918: 
1.837     raeburn  1919: sub retrieve_inst_usertypes {
                   1920:     my ($udom) = @_;
                   1921:     my (%returnhash,@order);
1.989     raeburn  1922:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1923:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1924:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1925:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1926:     } else {
                   1927:         if (defined(&domain($udom,'primary'))) {
                   1928:             my $uhome=&domain($udom,'primary');
                   1929:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1930:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1931:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1932:                 return (\%returnhash,\@order);
                   1933:             }
                   1934:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1935:             my @pairs=split(/\&/,$hashitems);
                   1936:             foreach my $item (@pairs) {
                   1937:                 my ($key,$value)=split(/=/,$item,2);
                   1938:                 $key = &unescape($key);
                   1939:                 next if ($key =~ /^error: 2 /);
                   1940:                 $returnhash{$key}=&thaw_unescape($value);
                   1941:             }
                   1942:             my @esc_order = split(/\&/,$orderitems);
                   1943:             foreach my $item (@esc_order) {
                   1944:                 push(@order,&unescape($item));
                   1945:             }
                   1946:         } else {
1.1256    raeburn  1947:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1948:         }
1.1256    raeburn  1949:         return (\%returnhash,\@order);
1.837     raeburn  1950:     }
                   1951: }
                   1952: 
1.868     raeburn  1953: sub is_domainimage {
                   1954:     my ($url) = @_;
1.1306    raeburn  1955:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1956:         if (&domain($1) ne '') {
                   1957:             return '1';
                   1958:         }
                   1959:     }
                   1960:     return;
                   1961: }
                   1962: 
1.899     raeburn  1963: sub inst_directory_query {
                   1964:     my ($srch) = @_;
                   1965:     my $udom = $srch->{'srchdomain'};
                   1966:     my %results;
                   1967:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1968:     my $outcome;
1.899     raeburn  1969:     if ($homeserver ne '') {
1.904     albertel 1970: 	my $queryid=&reply("querysend:instdirsearch:".
                   1971: 			   &escape($srch->{'srchby'}).':'.
                   1972: 			   &escape($srch->{'srchterm'}).':'.
                   1973: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1974: 	my $host=&hostname($homeserver);
                   1975: 	if ($queryid !~/^\Q$host\E\_/) {
                   1976: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1977: 	    return;
                   1978: 	}
                   1979: 	my $response = &get_query_reply($queryid);
                   1980: 	my $maxtries = 5;
                   1981: 	my $tries = 1;
                   1982: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1983: 	    $response = &get_query_reply($queryid);
                   1984: 	    $tries ++;
                   1985: 	}
                   1986: 
                   1987:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1988:             if ($response eq 'unavailable') {
                   1989:                 $outcome = $response;
                   1990:             } else {
                   1991:                 $outcome = 'ok';
                   1992:                 my @matches = split(/\n/,$response);
                   1993:                 foreach my $match (@matches) {
                   1994:                     my ($key,$value) = split(/=/,$match);
                   1995:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1996:                 }
1.899     raeburn  1997:             }
                   1998:         }
                   1999:     }
1.909     raeburn  2000:     return ($outcome,%results);
1.899     raeburn  2001: }
                   2002: 
                   2003: sub usersearch {
                   2004:     my ($srch) = @_;
                   2005:     my $dom = $srch->{'srchdomain'};
                   2006:     my %results;
                   2007:     my %libserv = &all_library();
                   2008:     my $query = 'usersearch';
                   2009:     foreach my $tryserver (keys(%libserv)) {
                   2010:         if (&host_domain($tryserver) eq $dom) {
                   2011:             my $host=&hostname($tryserver);
                   2012:             my $queryid=
1.911     raeburn  2013:                 &reply("querysend:".&escape($query).':'.
                   2014:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2015:                        &escape($srch->{'srchtype'}).':'.
                   2016:                        &escape($srch->{'srchterm'}),$tryserver);
                   2017:             if ($queryid !~/^\Q$host\E\_/) {
                   2018:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2019:                 next;
1.899     raeburn  2020:             }
                   2021:             my $reply = &get_query_reply($queryid);
                   2022:             my $maxtries = 1;
                   2023:             my $tries = 1;
                   2024:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2025:                 $reply = &get_query_reply($queryid);
                   2026:                 $tries ++;
                   2027:             }
                   2028:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2029:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2030:             } else {
1.911     raeburn  2031:                 my @matches;
                   2032:                 if ($reply =~ /\n/) {
                   2033:                     @matches = split(/\n/,$reply);
                   2034:                 } else {
                   2035:                     @matches = split(/\&/,$reply);
                   2036:                 }
1.899     raeburn  2037:                 foreach my $match (@matches) {
                   2038:                     my ($uname,$udom,%userhash);
1.911     raeburn  2039:                     foreach my $entry (split(/:/,$match)) {
                   2040:                         my ($key,$value) =
                   2041:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2042:                         $userhash{$key} = $value;
                   2043:                         if ($key eq 'username') {
                   2044:                             $uname = $value;
                   2045:                         } elsif ($key eq 'domain') {
                   2046:                             $udom = $value;
1.911     raeburn  2047:                         }
1.899     raeburn  2048:                     }
                   2049:                     $results{$uname.':'.$udom} = \%userhash;
                   2050:                 }
                   2051:             }
                   2052:         }
                   2053:     }
                   2054:     return %results;
                   2055: }
                   2056: 
1.912     raeburn  2057: sub get_instuser {
                   2058:     my ($udom,$uname,$id) = @_;
                   2059:     my $homeserver = &domain($udom,'primary');
                   2060:     my ($outcome,%results);
                   2061:     if ($homeserver ne '') {
                   2062:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2063:                            &escape($id).':'.&escape($udom),$homeserver);
                   2064:         my $host=&hostname($homeserver);
                   2065:         if ($queryid !~/^\Q$host\E\_/) {
                   2066:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2067:             return;
                   2068:         }
                   2069:         my $response = &get_query_reply($queryid);
                   2070:         my $maxtries = 5;
                   2071:         my $tries = 1;
                   2072:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2073:             $response = &get_query_reply($queryid);
                   2074:             $tries ++;
                   2075:         }
                   2076:         if (!&error($response) && $response ne 'refused') {
                   2077:             if ($response eq 'unavailable') {
                   2078:                 $outcome = $response;
                   2079:             } else {
                   2080:                 $outcome = 'ok';
                   2081:                 my @matches = split(/\n/,$response);
                   2082:                 foreach my $match (@matches) {
                   2083:                     my ($key,$value) = split(/=/,$match);
                   2084:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2085:                 }
                   2086:             }
                   2087:         }
                   2088:     }
                   2089:     my %userinfo;
                   2090:     if (ref($results{$uname}) eq 'HASH') {
                   2091:         %userinfo = %{$results{$uname}};
                   2092:     } 
                   2093:     return ($outcome,%userinfo);
                   2094: }
                   2095: 
1.1290    raeburn  2096: sub get_multiple_instusers {
                   2097:     my ($udom,$users,$caller) = @_;
                   2098:     my ($outcome,$results);
                   2099:     if (ref($users) eq 'HASH') {
                   2100:         my $count = keys(%{$users}); 
                   2101:         my $requested = &freeze_escape($users);
                   2102:         my $homeserver = &domain($udom,'primary');
                   2103:         if ($homeserver ne '') {
                   2104:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2105:             my $host=&hostname($homeserver);
                   2106:             if ($queryid !~/^\Q$host\E\_/) {
                   2107:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2108:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2109:                 return ($outcome,$results);
                   2110:             }
                   2111:             my $response = &get_query_reply($queryid);
                   2112:             my $maxtries = 5;
                   2113:             if ($count > 100) {
                   2114:                 $maxtries = 1+int($count/20);
                   2115:             }
                   2116:             my $tries = 1;
                   2117:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2118:                 $response = &get_query_reply($queryid);
                   2119:                 $tries ++;
                   2120:             }
                   2121:             if ($response eq '') {
                   2122:                 $results = {};
                   2123:                 foreach my $key (keys(%{$users})) {
                   2124:                     my ($uname,$id);
                   2125:                     if ($caller eq 'id') {
                   2126:                         $id = $key;
                   2127:                     } else {
                   2128:                         $uname = $key;
                   2129:                     }
                   2130:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2131:                     $outcome = $resp;
1.1290    raeburn  2132:                     if ($resp eq 'ok') {
                   2133:                         %{$results} = (%{$results}, %info);
                   2134:                     } else {
                   2135:                         last;
                   2136:                     }
                   2137:                 }
                   2138:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2139:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2140:                     $outcome = $response;
                   2141:                 } else {
1.1291    raeburn  2142:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2143:                     if ($outcome eq 'ok') {
                   2144:                         $results = &thaw_unescape($userdata); 
                   2145:                     }
                   2146:                 }
                   2147:             }
                   2148:         }
                   2149:     }
                   2150:     return ($outcome,$results);
                   2151: }
                   2152: 
1.912     raeburn  2153: sub inst_rulecheck {
1.923     raeburn  2154:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2155:     my %returnhash;
                   2156:     if ($udom ne '') {
                   2157:         if (ref($rules) eq 'ARRAY') {
                   2158:             @{$rules} = map {&escape($_);} (@{$rules});
                   2159:             my $rulestr = join(':',@{$rules});
                   2160:             my $homeserver=&domain($udom,'primary');
                   2161:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2162:                 my $response;
                   2163:                 if ($item eq 'username') {                
                   2164:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2165:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2166:                                               $homeserver));
1.923     raeburn  2167:                 } elsif ($item eq 'id') {
                   2168:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2169:                                               ':'.&escape($id).':'.$rulestr,
                   2170:                                               $homeserver));
1.945     raeburn  2171:                 } elsif ($item eq 'selfcreate') {
                   2172:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2173:                                                &escape($udom).':'.&escape($uname).
                   2174:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2175:                 }
1.912     raeburn  2176:                 if ($response ne 'refused') {
                   2177:                     my @pairs=split(/\&/,$response);
                   2178:                     foreach my $item (@pairs) {
                   2179:                         my ($key,$value)=split(/=/,$item,2);
                   2180:                         $key = &unescape($key);
                   2181:                         next if ($key =~ /^error: 2 /);
                   2182:                         $returnhash{$key}=&thaw_unescape($value);
                   2183:                     }
                   2184:                 }
                   2185:             }
                   2186:         }
                   2187:     }
                   2188:     return %returnhash;
                   2189: }
                   2190: 
                   2191: sub inst_userrules {
1.923     raeburn  2192:     my ($udom,$check) = @_;
1.912     raeburn  2193:     my (%ruleshash,@ruleorder);
                   2194:     if ($udom ne '') {
                   2195:         my $homeserver=&domain($udom,'primary');
                   2196:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2197:             my $response;
                   2198:             if ($check eq 'id') {
                   2199:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2200:                                  $homeserver);
1.943     raeburn  2201:             } elsif ($check eq 'email') {
                   2202:                 $response=&reply('instemailrules:'.&escape($udom),
                   2203:                                  $homeserver);
1.923     raeburn  2204:             } else {
                   2205:                 $response=&reply('instuserrules:'.&escape($udom),
                   2206:                                  $homeserver);
                   2207:             }
1.912     raeburn  2208:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2209:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2210:                 ($response ne 'no_such_host')) {
                   2211:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2212:                 my @pairs=split(/\&/,$hashitems);
                   2213:                 foreach my $item (@pairs) {
                   2214:                     my ($key,$value)=split(/=/,$item,2);
                   2215:                     $key = &unescape($key);
                   2216:                     next if ($key =~ /^error: 2 /);
                   2217:                     $ruleshash{$key}=&thaw_unescape($value);
                   2218:                 }
                   2219:                 my @esc_order = split(/\&/,$orderitems);
                   2220:                 foreach my $item (@esc_order) {
                   2221:                     push(@ruleorder,&unescape($item));
                   2222:                 }
                   2223:             }
                   2224:         }
                   2225:     }
                   2226:     return (\%ruleshash,\@ruleorder);
                   2227: }
                   2228: 
1.976     raeburn  2229: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2230: 
                   2231: sub get_domain_defaults {
1.1240    raeburn  2232:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2233:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2234:     my $cachetime = 60*60*24;
1.1240    raeburn  2235:     unless ($ignore_cache) {
                   2236:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2237:         if (defined($cached)) {
                   2238:             if (ref($result) eq 'HASH') {
                   2239:                 return %{$result};
                   2240:             }
1.943     raeburn  2241:         }
                   2242:     }
                   2243:     my %domdefaults;
                   2244:     my %domconfig =
1.989     raeburn  2245:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2246:                                   'requestcourses','inststatus',
1.1183    raeburn  2247:                                   'coursedefaults','usersessions',
1.1258    raeburn  2248:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2249:                                   'coursecategories','ssl','autoenroll',
1.1332  ! raeburn  2250:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2251:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2252:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2253:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2254:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2255:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2256:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2257:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2258:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  2259:     } else {
                   2260:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2261:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2262:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2263:     }
1.976     raeburn  2264:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2265:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2266:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2267:         } else {
                   2268:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2269:         }
1.1177    raeburn  2270:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2271:         foreach my $item (@usertools) {
                   2272:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2273:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2274:             }
                   2275:         }
1.1229    raeburn  2276:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2277:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2278:         }
1.976     raeburn  2279:     }
1.985     raeburn  2280:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2281:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2282:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2283:         }
                   2284:     }
1.1183    raeburn  2285:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2286:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2287:     }
1.989     raeburn  2288:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2289:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2290:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2291:         }
                   2292:     }
1.1047    raeburn  2293:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2294:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2295:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2296:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2297:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2298:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2299:         }
1.1254    raeburn  2300:         foreach my $type (@coursetypes) {
                   2301:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2302:                 unless ($type eq 'community') {
                   2303:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2304:                 }
                   2305:             }
                   2306:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2307:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2308:             }
1.1277    raeburn  2309:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2310:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2311:                     $domdefaults{$type.'postsubtimeout'} = 
                   2312:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2313:                 }
                   2314:             }
1.1230    raeburn  2315:         }
1.1286    raeburn  2316:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2317:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2318:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2319:                 if (@clonecodes) {
                   2320:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2321:                 }
                   2322:             }
                   2323:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2324:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2325:         }
1.1047    raeburn  2326:     }
1.1073    raeburn  2327:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2328:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2329:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2330:         }
                   2331:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2332:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2333:         }
1.1279    raeburn  2334:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2335:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2336:         }
1.1073    raeburn  2337:     }
1.1254    raeburn  2338:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2339:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2340:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2341:                             'approval','limit');
                   2342:             foreach my $type (@coursetypes) {
                   2343:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2344:                     my @mgrdc = ();
                   2345:                     foreach my $item (@settings) {
                   2346:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2347:                             push(@mgrdc,$item);
                   2348:                         }
                   2349:                     }
                   2350:                     if (@mgrdc) {
                   2351:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2352:                     }
                   2353:                 }
                   2354:             }
                   2355:         }
                   2356:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2357:             foreach my $type (@coursetypes) {
                   2358:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2359:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2360:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2361:                     }
                   2362:                 }
                   2363:             }
                   2364:         }
                   2365:     }
1.1258    raeburn  2366:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2367:         $domdefaults{'catauth'} = 'std';
                   2368:         $domdefaults{'catunauth'} = 'std';
                   2369:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2370:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2371:         }
                   2372:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2373:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2374:         }
                   2375:     }
1.1315    raeburn  2376:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2377:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2378:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2379:         }
                   2380:         if (ref($domconfig{'ssl'}{'connect'}) eq 'HASH') {
                   2381:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connect'};
                   2382:         }
                   2383:     }
1.1320    raeburn  2384:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2385:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2386:         foreach my $prefix (@prefixes) {
                   2387:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2388:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2389:             }
                   2390:         }
                   2391:     }
1.1314    raeburn  2392:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2393:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2394:     }
1.1332  ! raeburn  2395:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
        !          2396:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
        !          2397:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
        !          2398:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
        !          2399:         }
        !          2400:     }
1.1219    raeburn  2401:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2402:     return %domdefaults;
                   2403: }
                   2404: 
1.1311    raeburn  2405: sub course_portal_url {
                   2406:     my ($cnum,$cdom) = @_;
                   2407:     my $chome = &homeserver($cnum,$cdom);
                   2408:     my $hostname = &hostname($chome);
                   2409:     my $protocol = $protocol{$chome};
                   2410:     $protocol = 'http' if ($protocol ne 'https');
                   2411:     my %domdefaults = &get_domain_defaults($cdom);
                   2412:     my $firsturl;
                   2413:     if ($domdefaults{'portal_def'}) {
                   2414:         $firsturl = $domdefaults{'portal_def'};
                   2415:     } else {
                   2416:         $firsturl = $protocol.'://'.$hostname;
                   2417:     }
                   2418:     return $firsturl;
                   2419: }
                   2420: 
1.344     www      2421: # --------------------------------------------------- Assign a key to a student
                   2422: 
                   2423: sub assign_access_key {
1.364     www      2424: #
                   2425: # a valid key looks like uname:udom#comments
                   2426: # comments are being appended
                   2427: #
1.498     www      2428:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2429:     $kdom=
1.620     albertel 2430:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2431:     $knum=
1.620     albertel 2432:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2433:     $cdom=
1.620     albertel 2434:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2435:     $cnum=
1.620     albertel 2436:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2437:     $udom=$env{'user.name'} unless (defined($udom));
                   2438:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2439:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2440:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2441:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2442:                                                   # assigned to this person
                   2443:                                                   # - this should not happen,
1.345     www      2444:                                                   # unless something went wrong
                   2445:                                                   # the first time around
                   2446: # ready to assign
1.364     www      2447:         $logentry=$1.'; '.$logentry;
1.496     www      2448:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2449:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2450: # key now belongs to user
1.346     www      2451: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2452:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2453:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2454:                 return 'ok';
                   2455:             } else {
                   2456:                 return 
                   2457:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2458: 	    }
                   2459:         } else {
                   2460:             return 'error: Could not assign key, try again later.';
                   2461:         }
1.364     www      2462:     } elsif (!$existing{$ckey}) {
1.345     www      2463: # the key does not exist
                   2464: 	return 'error: The key does not exist';
                   2465:     } else {
                   2466: # the key is somebody else's
                   2467: 	return 'error: The key is already in use';
                   2468:     }
1.344     www      2469: }
                   2470: 
1.364     www      2471: # ------------------------------------------ put an additional comment on a key
                   2472: 
                   2473: sub comment_access_key {
                   2474: #
                   2475: # a valid key looks like uname:udom#comments
                   2476: # comments are being appended
                   2477: #
                   2478:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2479:     $cdom=
1.620     albertel 2480:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2481:     $cnum=
1.620     albertel 2482:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2483:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2484:     if ($existing{$ckey}) {
                   2485:         $existing{$ckey}.='; '.$logentry;
                   2486: # ready to assign
1.367     www      2487:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2488:                                                  $cdom,$cnum) eq 'ok') {
                   2489: 	    return 'ok';
                   2490:         } else {
                   2491: 	    return 'error: Count not store comment.';
                   2492:         }
                   2493:     } else {
                   2494: # the key does not exist
                   2495: 	return 'error: The key does not exist';
                   2496:     }
                   2497: }
                   2498: 
1.344     www      2499: # ------------------------------------------------------ Generate a set of keys
                   2500: 
                   2501: sub generate_access_keys {
1.364     www      2502:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2503:     $cdom=
1.620     albertel 2504:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2505:     $cnum=
1.620     albertel 2506:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2507:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2508:     unless (($cdom) && ($cnum)) { return 0; }
                   2509:     if ($number>10000) { return 0; }
                   2510:     sleep(2); # make sure don't get same seed twice
                   2511:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2512:     my $total=0;
                   2513:     for (my $i=1;$i<=$number;$i++) {
                   2514:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2515:                   sprintf("%lx",int(100000*rand)).'-'.
                   2516:                   sprintf("%lx",int(100000*rand));
                   2517:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2518:        $newkey=~s/0/h/g; # and also 0 and O
                   2519:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2520:        if ($existing{$newkey}) {
                   2521:            $i--;
                   2522:        } else {
1.364     www      2523: 	  if (&put('accesskeys',
                   2524:               { $newkey => '# generated '.localtime().
1.620     albertel 2525:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2526:                            '; '.$logentry },
                   2527: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2528:               $total++;
                   2529: 	  }
                   2530:        }
                   2531:     }
1.620     albertel 2532:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2533:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2534:     return $total;
                   2535: }
                   2536: 
                   2537: # ------------------------------------------------------- Validate an accesskey
                   2538: 
                   2539: sub validate_access_key {
                   2540:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2541:     $cdom=
1.620     albertel 2542:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2543:     $cnum=
1.620     albertel 2544:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2545:     $udom=$env{'user.domain'} unless (defined($udom));
                   2546:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2547:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2548:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2549: }
                   2550: 
                   2551: # ------------------------------------- Find the section of student in a course
1.652     albertel 2552: sub devalidate_getsection_cache {
                   2553:     my ($udom,$unam,$courseid)=@_;
                   2554:     my $hashid="$udom:$unam:$courseid";
                   2555:     &devalidate_cache_new('getsection',$hashid);
                   2556: }
1.298     matthew  2557: 
1.815     albertel 2558: sub courseid_to_courseurl {
                   2559:     my ($courseid) = @_;
                   2560:     #already url style courseid
                   2561:     return $courseid if ($courseid =~ m{^/});
                   2562: 
                   2563:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2564: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2565: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2566: 	return "/$cdom/$cnum";
                   2567:     }
                   2568: 
                   2569:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2570:     if (exists($courseinfo{'num'})) {
                   2571: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2572:     }
                   2573: 
                   2574:     return undef;
                   2575: }
                   2576: 
1.298     matthew  2577: sub getsection {
                   2578:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2579:     my $cachetime=1800;
1.551     albertel 2580: 
                   2581:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2582:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2583:     if (defined($cached)) { return $result; }
                   2584: 
1.298     matthew  2585:     my %Pending; 
                   2586:     my %Expired;
                   2587:     #
                   2588:     # Each role can either have not started yet (pending), be active, 
                   2589:     #    or have expired.
                   2590:     #
                   2591:     # If there is an active role, we are done.
                   2592:     #
                   2593:     # If there is more than one role which has not started yet, 
                   2594:     #     choose the one which will start sooner
                   2595:     # If there is one role which has not started yet, return it.
                   2596:     #
                   2597:     # If there is more than one expired role, choose the one which ended last.
                   2598:     # If there is a role which has expired, return it.
                   2599:     #
1.815     albertel 2600:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2601:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2602:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2603:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2604:         my $section=$1;
                   2605:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2606:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2607:         my $now=time;
1.548     albertel 2608:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2609:             $Expired{$end}=$section;
                   2610:             next;
                   2611:         }
1.548     albertel 2612:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2613:             $Pending{$start}=$section;
                   2614:             next;
                   2615:         }
1.599     albertel 2616:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2617:     }
                   2618:     #
                   2619:     # Presumedly there will be few matching roles from the above
                   2620:     # loop and the sorting time will be negligible.
                   2621:     if (scalar(keys(%Pending))) {
                   2622:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2623:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2624:     } 
                   2625:     if (scalar(keys(%Expired))) {
                   2626:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2627:         my $time = pop(@sorted);
1.599     albertel 2628:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2629:     }
1.599     albertel 2630:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2631: }
1.70      www      2632: 
1.599     albertel 2633: sub save_cache {
                   2634:     &purge_remembered();
1.722     albertel 2635:     #&Apache::loncommon::validate_page();
1.620     albertel 2636:     undef(%env);
1.780     albertel 2637:     undef($env_loaded);
1.599     albertel 2638: }
1.452     albertel 2639: 
1.599     albertel 2640: my $to_remember=-1;
                   2641: my %remembered;
                   2642: my %accessed;
                   2643: my $kicks=0;
                   2644: my $hits=0;
1.849     albertel 2645: sub make_key {
                   2646:     my ($name,$id) = @_;
1.872     albertel 2647:     if (length($id) > 65 
                   2648: 	&& length(&escape($id)) > 200) {
                   2649: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2650:     }
1.849     albertel 2651:     return &escape($name.':'.$id);
                   2652: }
                   2653: 
1.599     albertel 2654: sub devalidate_cache_new {
                   2655:     my ($name,$id,$debug) = @_;
                   2656:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2657:     my $remembered_id=$name.':'.$id;
1.849     albertel 2658:     $id=&make_key($name,$id);
1.599     albertel 2659:     $memcache->delete($id);
1.1319    damieng  2660:     delete($remembered{$remembered_id});
                   2661:     delete($accessed{$remembered_id});
1.599     albertel 2662: }
                   2663: 
                   2664: sub is_cached_new {
                   2665:     my ($name,$id,$debug) = @_;
1.1319    damieng  2666:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2667:     if (exists($remembered{$remembered_id})) {
                   2668: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2669: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2670: 	$hits++;
1.1319    damieng  2671: 	return ($remembered{$remembered_id},1);
1.599     albertel 2672:     }
1.1319    damieng  2673:     $id=&make_key($name,$id);
1.599     albertel 2674:     my $value = $memcache->get($id);
                   2675:     if (!(defined($value))) {
                   2676: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2677: 	return (undef,undef);
1.416     albertel 2678:     }
1.599     albertel 2679:     if ($value eq '__undef__') {
                   2680: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2681: 	$value=undef;
                   2682:     }
1.1319    damieng  2683:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2684:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2685:     return ($value,1);
                   2686: }
                   2687: 
                   2688: sub do_cache_new {
                   2689:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2690:     my $remembered_id=$name.':'.$id;
1.849     albertel 2691:     $id=&make_key($name,$id);
1.599     albertel 2692:     my $setvalue=$value;
                   2693:     if (!defined($setvalue)) {
                   2694: 	$setvalue='__undef__';
                   2695:     }
1.623     albertel 2696:     if (!defined($time) ) {
                   2697: 	$time=600;
                   2698:     }
1.599     albertel 2699:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2700:     my $result = $memcache->set($id,$setvalue,$time);
                   2701:     if (! $result) {
1.872     albertel 2702: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2703: 	$memcache->disconnect_all();
1.872     albertel 2704:     }
1.600     albertel 2705:     # need to make a copy of $value
1.1319    damieng  2706:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2707:     return $value;
                   2708: }
                   2709: 
                   2710: sub make_room {
1.1319    damieng  2711:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2712: 
1.1319    damieng  2713:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2714:                                     : $value;
1.599     albertel 2715:     if ($to_remember<0) { return; }
1.1319    damieng  2716:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2717:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2718:     my $to_kick;
                   2719:     my $max_time=0;
                   2720:     foreach my $other (keys(%accessed)) {
                   2721: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2722: 	    $to_kick=$other;
                   2723: 	    $max_time=&tv_interval($accessed{$other});
                   2724: 	}
                   2725:     }
                   2726:     delete($remembered{$to_kick});
                   2727:     delete($accessed{$to_kick});
                   2728:     $kicks++;
                   2729:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2730:     return;
                   2731: }
                   2732: 
1.599     albertel 2733: sub purge_remembered {
1.604     albertel 2734:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2735:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2736:     undef(%remembered);
                   2737:     undef(%accessed);
1.428     albertel 2738: }
1.70      www      2739: # ------------------------------------- Read an entry from a user's environment
                   2740: 
                   2741: sub userenvironment {
                   2742:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2743:     my $items;
                   2744:     foreach my $item (@what) {
                   2745:         $items.=&escape($item).'&';
                   2746:     }
                   2747:     $items=~s/\&$//;
1.70      www      2748:     my %returnhash=();
1.1009    raeburn  2749:     my $uhome = &homeserver($unam,$udom);
                   2750:     unless ($uhome eq 'no_host') {
                   2751:         my @answer=split(/\&/, 
                   2752:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2753:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2754:             return %returnhash;
                   2755:         }
1.1009    raeburn  2756:         my $i;
                   2757:         for ($i=0;$i<=$#what;$i++) {
                   2758: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2759:         }
1.70      www      2760:     }
                   2761:     return %returnhash;
1.1       albertel 2762: }
                   2763: 
1.617     albertel 2764: # ---------------------------------------------------------- Get a studentphoto
                   2765: sub studentphoto {
                   2766:     my ($udom,$unam,$ext) = @_;
                   2767:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2768:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2769:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2770:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2771:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2772:             } else {
                   2773:                 my ($result,$perm_reqd)=
1.707     albertel 2774: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2775:                 if ($result eq 'ok') {
                   2776:                     if (!($perm_reqd eq 'yes')) {
                   2777:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2778:                     }
                   2779:                 }
                   2780:             }
                   2781:         }
                   2782:     } else {
                   2783:         my ($result,$perm_reqd) = 
1.707     albertel 2784: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2785:         if ($result eq 'ok') {
                   2786:             if (!($perm_reqd eq 'yes')) {
                   2787:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2788:             }
                   2789:         }
                   2790:     }
                   2791:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2792: }
                   2793: 
                   2794: sub retrievestudentphoto {
                   2795:     my ($udom,$unam,$ext,$type) = @_;
                   2796:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2797:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2798:     if ($ret eq 'ok') {
                   2799:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2800:         if ($type eq 'thumbnail') {
                   2801:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2802:         }
                   2803:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2804:         return $tokenurl;
                   2805:     } else {
                   2806:         if ($type eq 'thumbnail') {
                   2807:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2808:         } else { 
                   2809:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2810:         }
1.617     albertel 2811:     }
                   2812: }
                   2813: 
1.263     www      2814: # -------------------------------------------------------------------- New chat
                   2815: 
                   2816: sub chatsend {
1.724     raeburn  2817:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2818:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2819:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2820:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2821:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2822: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2823: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2824: }
                   2825: 
                   2826: # ------------------------------------------ Find current version of a resource
                   2827: 
                   2828: sub getversion {
                   2829:     my $fname=&clutter(shift);
1.1189    raeburn  2830:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2831:     return &currentversion(&filelocation('',$fname));
                   2832: }
                   2833: 
                   2834: sub currentversion {
                   2835:     my $fname=shift;
                   2836:     my $author=$fname;
                   2837:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2838:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2839:     my $home=&homeserver($uname,$udom);
1.292     www      2840:     if ($home eq 'no_host') { 
                   2841:         return -1; 
                   2842:     }
1.1112    www      2843:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2844:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2845: 	return -1;
                   2846:     }
1.1112    www      2847:     return $answer;
1.263     www      2848: }
                   2849: 
1.1111    www      2850: #
                   2851: # Return special version number of resource if set by override, empty otherwise
                   2852: #
                   2853: sub usedversion {
                   2854:     my $fname=shift;
                   2855:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2856:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2857:     if ($urlversion) { return $urlversion; }
                   2858:     return '';
                   2859: }
                   2860: 
1.1       albertel 2861: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2862: 
1.1       albertel 2863: sub subscribe {
                   2864:     my $fname=shift;
1.761     raeburn  2865:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2866:     $fname=~s/[\n\r]//g;
1.1       albertel 2867:     my $author=$fname;
                   2868:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2869:     my ($udom,$uname)=split(/\//,$author);
                   2870:     my $home=homeserver($uname,$udom);
1.335     albertel 2871:     if ($home eq 'no_host') {
                   2872:         return 'not_found';
1.1       albertel 2873:     }
                   2874:     my $answer=reply("sub:$fname",$home);
1.64      www      2875:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2876: 	$answer.=' by '.$home;
                   2877:     }
1.1       albertel 2878:     return $answer;
                   2879: }
                   2880:     
1.8       www      2881: # -------------------------------------------------------------- Replicate file
                   2882: 
                   2883: sub repcopy {
                   2884:     my $filename=shift;
1.23      www      2885:     $filename=~s/\/+/\//g;
1.1142    raeburn  2886:     my $londocroot = $perlvar{'lonDocRoot'};
                   2887:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2888:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2889:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2890: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2891: 	return &repcopy_userfile($filename);
                   2892:     }
1.532     albertel 2893:     $filename=~s/[\n\r]//g;
1.8       www      2894:     my $transname="$filename.in.transfer";
1.828     www      2895: # FIXME: this should flock
1.607     raeburn  2896:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2897:     my $remoteurl=subscribe($filename);
1.64      www      2898:     if ($remoteurl =~ /^con_lost by/) {
                   2899: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2900:            return 'unavailable';
1.8       www      2901:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2902: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2903: 	   return 'not_found';
1.64      www      2904:     } elsif ($remoteurl =~ /^rejected by/) {
                   2905: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2906:            return 'forbidden';
1.20      www      2907:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2908:            return 'ok';
1.8       www      2909:     } else {
1.290     www      2910:         my $author=$filename;
                   2911:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2912:         my ($udom,$uname)=split(/\//,$author);
                   2913:         my $home=homeserver($uname,$udom);
                   2914:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2915:            my @parts=split(/\//,$filename);
                   2916:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2917:            if ($path ne "$londocroot/res") {
1.8       www      2918:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2919: 	       return 'bad_request';
1.8       www      2920:            }
                   2921:            my $count;
                   2922:            for ($count=5;$count<$#parts;$count++) {
                   2923:                $path.="/$parts[$count]";
                   2924:                if ((-e $path)!=1) {
                   2925: 		   mkdir($path,0777);
                   2926:                }
                   2927:            }
                   2928:            my $ua=new LWP::UserAgent;
                   2929:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2930:            my $response=$ua->request($request,$transname);
                   2931:            if ($response->is_error()) {
                   2932: 	       unlink($transname);
                   2933:                my $message=$response->status_line;
1.672     albertel 2934:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2935:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2936:                return 'unavailable';
1.8       www      2937:            } else {
1.16      www      2938: 	       if ($remoteurl!~/\.meta$/) {
                   2939:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2940:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2941:                   if ($mresponse->is_error()) {
                   2942: 		      unlink($filename.'.meta');
                   2943:                       &logthis(
1.672     albertel 2944:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2945:                   }
                   2946: 	       }
1.8       www      2947:                rename($transname,$filename);
1.607     raeburn  2948:                return 'ok';
1.8       www      2949:            }
1.290     www      2950:        }
1.8       www      2951:     }
1.330     www      2952: }
                   2953: 
                   2954: # ------------------------------------------------ Get server side include body
                   2955: sub ssi_body {
1.381     albertel 2956:     my ($filelink,%form)=@_;
1.606     matthew  2957:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2958:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2959:     }
1.953     www      2960:     my $output='';
                   2961:     my $response;
1.980     raeburn  2962:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2963:        ($output,$response)=&externalssi($filelink);
1.953     www      2964:     } else {
1.1004    droeschl 2965:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2966:        $filelink .= 'inhibitmenu=yes';
1.953     www      2967:        ($output,$response)=&ssi($filelink,%form);
                   2968:     }
1.778     albertel 2969:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2970:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2971:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2972:     if (wantarray) {
                   2973:         return ($output, $response);
                   2974:     } else {
                   2975:         return $output;
                   2976:     }
1.8       www      2977: }
                   2978: 
1.15      www      2979: # --------------------------------------------------------- Server Side Include
                   2980: 
1.782     albertel 2981: sub absolute_url {
                   2982:     my ($host_name) = @_;
                   2983:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2984:     if ($host_name eq '') {
                   2985: 	$host_name = $ENV{'SERVER_NAME'};
                   2986:     }
                   2987:     return $protocol.$host_name;
                   2988: }
                   2989: 
1.942     foxr     2990: #
                   2991: #   Server side include.
                   2992: # Parameters:
                   2993: #  fn     Possibly encrypted resource name/id.
                   2994: #  form   Hash that describes how the rendering should be done
                   2995: #         and other things.
1.944     foxr     2996: # Returns:
1.950     raeburn  2997: #   Scalar context: The content of the response.
                   2998: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2999: #     
1.15      www      3000: sub ssi {
                   3001: 
1.944     foxr     3002:     my ($fn,%form)=@_;
1.15      www      3003:     my $ua=new LWP::UserAgent;
1.23      www      3004:     my $request;
1.711     albertel 3005: 
                   3006:     $form{'no_update_last_known'}=1;
1.895     albertel 3007:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3008:     if (%form) {
1.782     albertel 3009:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3010:       $request->content(join('&',map { 
                   3011:             my $name = escape($_);
                   3012:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3013:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3014:             : &escape($form{$_}) );    
                   3015:         } keys(%form)));
1.23      www      3016:     } else {
1.782     albertel 3017:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3018:     }
                   3019: 
1.15      www      3020:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     3021:     my $response= $ua->request($request);
1.1182    foxr     3022:     my $content = $response->content;
                   3023: 
                   3024: 
1.944     foxr     3025:     if (wantarray) {
1.1173    foxr     3026: 	return ($content, $response);
1.944     foxr     3027:     } else {
1.1173    foxr     3028: 	return $content;
1.942     foxr     3029:     }
1.324     www      3030: }
                   3031: 
                   3032: sub externalssi {
                   3033:     my ($url)=@_;
                   3034:     my $ua=new LWP::UserAgent;
                   3035:     my $request=new HTTP::Request('GET',$url);
                   3036:     my $response=$ua->request($request);
1.954     raeburn  3037:     if (wantarray) {
                   3038:         return ($response->content, $response);
                   3039:     } else {
                   3040:         return $response->content;
                   3041:     }
1.15      www      3042: }
1.254     www      3043: 
1.492     albertel 3044: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3045: 
                   3046: sub allowuploaded {
                   3047:     my ($srcurl,$url)=@_;
                   3048:     $url=&clutter(&declutter($url));
                   3049:     my $dir=$url;
                   3050:     $dir=~s/\/[^\/]+$//;
                   3051:     my %httpref=();
                   3052:     my $httpurl=&hreflocation('',$url);
                   3053:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3054:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3055: }
1.477     raeburn  3056: 
1.1193    raeburn  3057: #
                   3058: # Determine if the current user should be able to edit a particular resource,
                   3059: # when viewing in course context.
                   3060: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3061: #     Functions.
                   3062: # (b) When displaying folder contents in course editor, used to determine if
                   3063: #     "Edit" link will be displayed alongside resource.
                   3064: #
1.1196    raeburn  3065: #  input: six args -- filename (decluttered), course number, course domain,
                   3066: #                   url, symb (if registered) and group (if this is a group
                   3067: #                   item -- e.g., bulletin board, group page etc.).
                   3068: #  output: array of five scalars -- 
1.1193    raeburn  3069: #          $cfile -- url for file editing if editable on current server
                   3070: #          $home -- homeserver of resource (i.e., for author if published,
                   3071: #                                           or course if uploaded.).
                   3072: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3073: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3074: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3075: #
                   3076: 
                   3077: sub can_edit_resource {
1.1194    raeburn  3078:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3079:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3080: #
                   3081: # For aboutme pages user can only edit his/her own.
                   3082: #
1.1199    raeburn  3083:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3084:         my ($sdom,$sname) = ($1,$2);
                   3085:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3086:             $home = $env{'user.home'};
                   3087:             $cfile = $resurl;
                   3088:             if ($env{'form.forceedit'}) {
                   3089:                 $forceview = 1;
                   3090:             } else {
                   3091:                 $forceedit = 1;
                   3092:             }
                   3093:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3094:         } else {
                   3095:             return;
                   3096:         }
                   3097:     }
                   3098: 
                   3099:     if ($env{'request.course.id'}) {
                   3100:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3101:         if ($group ne '') {
                   3102: # if this is a group homepage or group bulletin board, check group privs
                   3103:             my $allowed = 0;
1.1197    raeburn  3104:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3105:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3106:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3107:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3108:                     $allowed = 1;
                   3109:                 }
1.1197    raeburn  3110:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3111:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3112:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3113:                     $allowed = 1;
                   3114:                 }
                   3115:             }
                   3116:             if ($allowed) {
                   3117:                 $home=&homeserver($cnum,$cdom);
                   3118:                 if ($env{'form.forceedit'}) {
                   3119:                     $forceview = 1;
                   3120:                 } else {
                   3121:                     $forceedit = 1;
                   3122:                 }
                   3123:                 $cfile = $resurl;
                   3124:             } else {
                   3125:                 return;
                   3126:             }
                   3127:         } else {
1.1208    raeburn  3128:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3129:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3130:                     return;
                   3131:                 }
                   3132:             } elsif (!$crsedit) {
1.1194    raeburn  3133: #
                   3134: # No edit allowed where CC has switched to student role.
                   3135: #
                   3136:                 return;
                   3137:             }
                   3138:         }
                   3139:     }
                   3140: 
1.1193    raeburn  3141:     if ($file ne '') {
                   3142:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3143:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3144:                 $uploaded = 1;
                   3145:                 $incourse = 1;
1.1193    raeburn  3146:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3147:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3148:                     if ($env{'form.forceedit'}) {
                   3149:                         $forceview = 1;
                   3150:                     } else {
                   3151:                         $forceedit = 1;
                   3152:                     }
1.1194    raeburn  3153:                 }
                   3154:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3155:                 $incourse = 1;
                   3156:                 if ($env{'form.forceedit'}) {
                   3157:                     $forceview = 1;
                   3158:                 } else {
                   3159:                     $forceedit = 1;
                   3160:                 }
                   3161:                 $cfile = $resurl;
                   3162:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3163:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3164:                     $incourse = 1;
                   3165:                     if ($env{'form.forceedit'}) {
                   3166:                         $forceview = 1;
                   3167:                     } else {
                   3168:                         $forceedit = 1;
                   3169:                     }
                   3170:                     $cfile = $resurl;
1.1199    raeburn  3171:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3172:                     $incourse = 1;
                   3173:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3174:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3175:                     $incourse = 1;
1.1199    raeburn  3176:                     if ($env{'form.forceedit'}) {
                   3177:                         $forceview = 1;
                   3178:                     } else {
                   3179:                         $forceedit = 1;
                   3180:                     }
                   3181:                     $cfile = $resurl;
1.1298    raeburn  3182:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3183:                     $incourse = 1;
                   3184:                     if ($env{'form.forceedit'}) {
                   3185:                         $forceview = 1;
                   3186:                     } else {
                   3187:                         $forceedit = 1;
                   3188:                     }
                   3189:                     $cfile = $resurl;
1.1208    raeburn  3190:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3191:                     $incourse = 1;
                   3192:                     if ($env{'form.forceedit'}) {
                   3193:                         $forceview = 1;
                   3194:                     } else {
                   3195:                         $forceedit = 1;
                   3196:                     }
                   3197:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3198:                 }
                   3199:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3200:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3201:                 if (&is_on_map($template)) { 
                   3202:                     $incourse = 1;
                   3203:                     $forceview = 1;
                   3204:                     $cfile = $template;
1.1193    raeburn  3205:                 }
1.1199    raeburn  3206:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3207:                     $incourse = 1;
                   3208:                     if ($env{'form.forceedit'}) {
                   3209:                         $forceview = 1;
                   3210:                     } else {
                   3211:                         $forceedit = 1;
                   3212:                     }
                   3213:                     $cfile = $resurl;
1.1298    raeburn  3214:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/exttools?$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3215:                 $incourse = 1;
                   3216:                 if ($env{'form.forceedit'}) {
                   3217:                     $forceview = 1;
                   3218:                 } else {
                   3219:                     $forceedit = 1;
                   3220:                 }
                   3221:                 $cfile = $resurl;
1.1199    raeburn  3222:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3223:                 $incourse = 1;
                   3224:                 $forceview = 1;
                   3225:                 if ($symb) {
                   3226:                     my ($map,$id,$res)=&decode_symb($symb);
                   3227:                     $env{'request.symb'} = $symb;
                   3228:                     $cfile = &clutter($res);
                   3229:                 } else {
                   3230:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3231:                     my $escfile = &unescape($cfile);
                   3232:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/exttools?$}) {
                   3233:                         $cfile = '/adm/wrapper'.$escfile;
                   3234:                     } else {
                   3235:                         $escfile =~ s{^http://}{};
                   3236:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3237:                     }
1.1199    raeburn  3238:                 }
1.1234    raeburn  3239:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3240:                 if ($env{'form.forceedit'}) {
                   3241:                     $forceview = 1;
                   3242:                 } else {
                   3243:                     $forceedit = 1;
                   3244:                 }
                   3245:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3246:             }
                   3247:         }
1.1194    raeburn  3248:         if ($uploaded || $incourse) {
                   3249:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3250:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3251:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3252:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3253:             # Check that the user has permission to edit this resource
                   3254:             my $setpriv = 1;
                   3255:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3256:             if (defined($cfudom)) {
                   3257:                 $home=&homeserver($cfuname,$cfudom);
                   3258:                 $cfile=$file;
                   3259:             }
                   3260:         }
1.1194    raeburn  3261:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3262:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3263:             my @ids=&current_machine_ids();
                   3264:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3265:                 $switchserver=1;
                   3266:             }
                   3267:         }
                   3268:     }
1.1194    raeburn  3269:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3270: }
                   3271: 
                   3272: sub is_course_upload {
                   3273:     my ($file,$cnum,$cdom) = @_;
                   3274:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3275:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3276:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3277:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3278:         return 1;
                   3279:     }
                   3280:     return;
                   3281: }
                   3282: 
1.1194    raeburn  3283: sub in_course {
1.1195    raeburn  3284:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3285:     if ($hideprivileged) {
                   3286:         my $skipuser;
1.1219    raeburn  3287:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3288:         my @possdoms = ($cdom);  
                   3289:         if ($coursehash{'checkforpriv'}) { 
                   3290:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3291:         }
                   3292:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3293:             $skipuser = 1;
                   3294:             if ($coursehash{'nothideprivileged'}) {
                   3295:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3296:                     my $user;
                   3297:                     if ($item =~ /:/) {
                   3298:                         $user = $item;
                   3299:                     } else {
                   3300:                         $user = join(':',split(/[\@]/,$item));
                   3301:                     }
                   3302:                     if ($user eq $uname.':'.$udom) {
                   3303:                         undef($skipuser);
                   3304:                         last;
                   3305:                     }
                   3306:                 }
                   3307:             }
                   3308:             if ($skipuser) {
                   3309:                 return 0;
                   3310:             }
                   3311:         }
                   3312:     }
1.1194    raeburn  3313:     $type ||= 'any';
                   3314:     if (!defined($cdom) || !defined($cnum)) {
                   3315:         my $cid  = $env{'request.course.id'};
                   3316:         $cdom = $env{'course.'.$cid.'.domain'};
                   3317:         $cnum = $env{'course.'.$cid.'.num'};
                   3318:     }
                   3319:     my $typesref;
1.1195    raeburn  3320:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3321:         $typesref = ['active','previous','future'];
                   3322:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3323:         $typesref = [$type];
                   3324:     }
                   3325:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3326:                               $typesref,undef,[$cdom]);
                   3327:     my ($tmp) = keys(%roles);
                   3328:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3329:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3330:     if (@course_roles > 0) {
                   3331:         return 1;
                   3332:     }
                   3333:     return 0;
                   3334: }
                   3335: 
1.478     albertel 3336: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3337: # input: action, courseID, current domain, intended
1.637     raeburn  3338: #        path to file, source of file, instruction to parse file for objects,
                   3339: #        ref to hash for embedded objects,
                   3340: #        ref to hash for codebase of java objects.
1.1095    raeburn  3341: #        reference to scalar to accommodate mime type determined
                   3342: #          from File::MMagic if $parser = parse.
1.637     raeburn  3343: #
1.485     raeburn  3344: # output: url to file (if action was uploaddoc), 
                   3345: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3346: #
1.478     albertel 3347: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3348: # course.
1.477     raeburn  3349: #
1.478     albertel 3350: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3351: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3352: #          course's home server.
1.477     raeburn  3353: #
1.478     albertel 3354: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3355: #          be copied from $source (current location) to 
                   3356: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3357: #         and will then be copied to
                   3358: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3359: #         course's home server.
1.485     raeburn  3360: #
1.481     raeburn  3361: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3362: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3363: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3364: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3365: #         in course's home server.
1.637     raeburn  3366: #
1.477     raeburn  3367: 
                   3368: sub process_coursefile {
1.1095    raeburn  3369:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3370:         $mimetype)=@_;
1.477     raeburn  3371:     my $fetchresult;
1.638     albertel 3372:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3373:     if ($action eq 'propagate') {
1.638     albertel 3374:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3375: 			     $home);
1.481     raeburn  3376:     } else {
1.477     raeburn  3377:         my $fpath = '';
                   3378:         my $fname = $file;
1.478     albertel 3379:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3380:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3381:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3382:         if ($action eq 'copy') {
                   3383:             if ($source eq '') {
                   3384:                 $fetchresult = 'no source file';
                   3385:                 return $fetchresult;
                   3386:             } else {
                   3387:                 my $destination = $filepath.'/'.$fname;
                   3388:                 rename($source,$destination);
                   3389:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3390:                                  $home);
1.481     raeburn  3391:             }
                   3392:         } elsif ($action eq 'uploaddoc') {
                   3393:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3394:             print $fh $env{'form.'.$source};
1.481     raeburn  3395:             close($fh);
1.637     raeburn  3396:             if ($parser eq 'parse') {
1.1024    raeburn  3397:                 my $mm = new File::MMagic;
1.1095    raeburn  3398:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3399:                 if ($type eq 'text/html') {
1.1024    raeburn  3400:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3401:                     unless ($parse_result eq 'ok') {
                   3402:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3403:                     }
1.637     raeburn  3404:                 }
1.1095    raeburn  3405:                 if (ref($mimetype)) {
                   3406:                     $$mimetype = $type;
                   3407:                 } 
1.637     raeburn  3408:             }
1.477     raeburn  3409:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3410:                                  $home);
1.481     raeburn  3411:             if ($fetchresult eq 'ok') {
                   3412:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3413:             } else {
                   3414:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3415:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3416:                 return '/adm/notfound.html';
                   3417:             }
1.477     raeburn  3418:         }
                   3419:     }
1.485     raeburn  3420:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3421:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3422:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3423:     }
                   3424:     return $fetchresult;
                   3425: }
                   3426: 
1.637     raeburn  3427: sub build_filepath {
                   3428:     my ($fpath) = @_;
                   3429:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3430:     unless ($fpath eq '') {
                   3431:         my @parts=split('/',$fpath);
                   3432:         foreach my $part (@parts) {
                   3433:             $filepath.= '/'.$part;
                   3434:             if ((-e $filepath)!=1) {
                   3435:                 mkdir($filepath,0777);
                   3436:             }
                   3437:         }
                   3438:     }
                   3439:     return $filepath;
                   3440: }
                   3441: 
                   3442: sub store_edited_file {
1.638     albertel 3443:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3444:     my $file = $primary_url;
                   3445:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3446:     my $fpath = '';
                   3447:     my $fname = $file;
                   3448:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3449:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3450:     my $filepath = &build_filepath($fpath);
                   3451:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3452:     print $fh $content;
                   3453:     close($fh);
1.638     albertel 3454:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3455:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3456: 			  $home);
1.637     raeburn  3457:     if ($$fetchresult eq 'ok') {
                   3458:         return '/uploaded/'.$fpath.'/'.$fname;
                   3459:     } else {
1.638     albertel 3460:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3461: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3462:         return '/adm/notfound.html';
                   3463:     }
                   3464: }
                   3465: 
1.531     albertel 3466: sub clean_filename {
1.831     albertel 3467:     my ($fname,$args)=@_;
1.315     www      3468: # Replace Windows backslashes by forward slashes
1.257     www      3469:     $fname=~s/\\/\//g;
1.831     albertel 3470:     if (!$args->{'keep_path'}) {
                   3471:         # Get rid of everything but the actual filename
                   3472: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3473:     }
1.315     www      3474: # Replace spaces by underscores
                   3475:     $fname=~s/\s+/\_/g;
                   3476: # Replace all other weird characters by nothing
1.831     albertel 3477:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3478: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3479: # numbers
                   3480:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3481:     return $fname;
                   3482: }
1.1051    raeburn  3483: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3484: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3485: # image with the same aspect ratio as the original, but with dimensions which do 
                   3486: # not exceed $resizewidth and $resizeheight.
                   3487:  
1.984     neumanie 3488: sub resizeImage {
1.1051    raeburn  3489:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3490:     my $ima = Image::Magick->new;
                   3491:     my $resized;
                   3492:     if (-e $img_path) {
                   3493:         $ima->Read($img_path);
                   3494:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3495:             my $width = $ima->Get('width');
                   3496:             my $height = $ima->Get('height');
                   3497:             if ($width > $resizewidth) {
                   3498: 	        my $factor = $width/$resizewidth;
                   3499:                 my $newheight = $height/$factor;
                   3500:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3501:                 $resized = 1;
                   3502:             }
                   3503:         }
                   3504:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3505:             my $width = $ima->Get('width');
                   3506:             my $height = $ima->Get('height');
                   3507:             if ($height > $resizeheight) {
                   3508:                 my $factor = $height/$resizeheight;
                   3509:                 my $newwidth = $width/$factor;
                   3510:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3511:                 $resized = 1;
                   3512:             }
                   3513:         }
                   3514:         if ($resized) {
                   3515:             $ima->Write($img_path);
                   3516:         }
                   3517:     }
                   3518:     return;
1.977     amueller 3519: }
                   3520: 
1.608     albertel 3521: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3522: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3523: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3524: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3525: #                                    canceloverwrite, or ''. 
                   3526: #                   if 'coursedoc': upload to the current course
                   3527: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3528: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3529: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3530: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3531: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3532: #        $allfiles - reference to hash for embedded objects
                   3533: #        $codebase - reference to hash for codebase of java objects
                   3534: #        $desuname - username for permanent storage of uploaded file
                   3535: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3536: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3537: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3538: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3539: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3540: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3541: #                    from File::MMagic.
1.858     raeburn  3542: # 
1.686     albertel 3543: # output: url of file in userspace, or error: <message> 
                   3544: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3545: 
1.531     albertel 3546: sub userfileupload {
1.1090    raeburn  3547:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3548:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3549:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3550:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3551:     $fname=&clean_filename($fname);
1.1090    raeburn  3552:     # See if there is anything left
1.257     www      3553:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3554:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3555:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3556:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3557:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3558:         my $now = time;
1.1090    raeburn  3559:         my $filepath;
1.1095    raeburn  3560:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3561:              $filepath = 'tmp/helprequests/'.$now;
                   3562:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3563:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3564:                          '_'.$env{'user.domain'}.'/pending';
                   3565:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3566:             my ($docuname,$docudom);
                   3567:             if ($destudom) {
                   3568:                 $docudom = $destudom;
                   3569:             } else {
                   3570:                 $docudom = $env{'user.domain'};
                   3571:             }
                   3572:             if ($destuname) {
                   3573:                 $docuname = $destuname;
                   3574:             } else {
                   3575:                 $docuname = $env{'user.name'};
                   3576:             }
                   3577:             if (exists($env{'form.group'})) {
                   3578:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3579:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3580:             }
                   3581:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3582:             if ($context eq 'canceloverwrite') {
                   3583:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3584:                 if (-e  $tempfile) {
                   3585:                     my @info = stat($tempfile);
                   3586:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3587:                         unlink($tempfile);
                   3588:                     }
                   3589:                 }
                   3590:                 return;
1.523     raeburn  3591:             }
                   3592:         }
1.1090    raeburn  3593:         # Create the directory if not present
1.741     raeburn  3594:         my @parts=split(/\//,$filepath);
                   3595:         my $fullpath = $perlvar{'lonDaemons'};
                   3596:         for (my $i=0;$i<@parts;$i++) {
                   3597:             $fullpath .= '/'.$parts[$i];
                   3598:             if ((-e $fullpath)!=1) {
                   3599:                 mkdir($fullpath,0777);
                   3600:             }
                   3601:         }
                   3602:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3603:         print $fh $env{'form.'.$formname};
                   3604:         close($fh);
1.1090    raeburn  3605:         if ($context eq 'existingfile') {
                   3606:             my @info = stat($fullpath.'/'.$fname);
                   3607:             return ($fullpath.'/'.$fname,$info[9]);
                   3608:         } else {
                   3609:             return $fullpath.'/'.$fname;
                   3610:         }
1.523     raeburn  3611:     }
1.995     raeburn  3612:     if ($subdir eq 'scantron') {
                   3613:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3614:     } else {
1.995     raeburn  3615:         $fname="$subdir/$fname";
                   3616:     }
1.1090    raeburn  3617:     if ($context eq 'coursedoc') {
1.638     albertel 3618: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3619: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3620:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3621:             return &finishuserfileupload($docuname,$docudom,
                   3622: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3623: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3624:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3625:         } else {
1.1218    raeburn  3626:             if ($env{'form.folder'}) {
                   3627:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3628:             }
1.638     albertel 3629:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3630: 				       $fname,$formname,$parser,
1.1095    raeburn  3631: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3632:         }
1.719     banghart 3633:     } elsif (defined($destuname)) {
                   3634:         my $docuname=$destuname;
                   3635:         my $docudom=$destudom;
1.860     raeburn  3636: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3637: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3638:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3639:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3640:     } else {
1.638     albertel 3641:         my $docuname=$env{'user.name'};
                   3642:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3643:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3644:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3645:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3646:         }
1.860     raeburn  3647: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3648: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3649:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3650:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3651:     }
1.271     www      3652: }
                   3653: 
                   3654: sub finishuserfileupload {
1.860     raeburn  3655:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3656:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3657:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3658:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3659:   
1.860     raeburn  3660:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3661:     $file=$fname;
                   3662:     if ($fname=~m|/|) {
                   3663:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3664: 	$path.=$fnamepath.'/';
                   3665:     }
1.259     www      3666:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3667:     my $count;
                   3668:     for ($count=4;$count<=$#parts;$count++) {
                   3669:         $filepath.="/$parts[$count]";
                   3670:         if ((-e $filepath)!=1) {
                   3671: 	    mkdir($filepath,0777);
                   3672:         }
                   3673:     }
1.984     neumanie 3674: 
1.258     www      3675: # Save the file
                   3676:     {
1.701     albertel 3677: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3678: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3679: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3680: 	    return '/adm/notfound.html';
                   3681: 	}
1.1090    raeburn  3682:         if ($context eq 'overwrite') {
1.1117    foxr     3683:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3684:             my $target = $filepath.'/'.$file;
                   3685:             if (-e $source) {
                   3686:                 my @info = stat($source);
                   3687:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3688:                     unless (&File::Copy::move($source,$target)) {
                   3689:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3690:                         return "Moving from $source failed";
                   3691:                     }
                   3692:                 } else {
                   3693:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3694:                 }
                   3695:             } else {
                   3696:                 return "Temporary file: $source missing";
                   3697:             }
                   3698:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3699: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3700: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3701: 	    return '/adm/notfound.html';
                   3702: 	}
1.570     albertel 3703: 	close(FH);
1.1051    raeburn  3704:         if ($resizewidth && $resizeheight) {
                   3705:             my $mm = new File::MMagic;
                   3706:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3707:             if ($mime_type =~ m{^image/}) {
                   3708: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3709:             }  
1.977     amueller 3710: 	}
1.258     www      3711:     }
1.1152    raeburn  3712:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3713:         if (ref($mimetype)) {
                   3714:             if ($$mimetype eq '') {
                   3715:                 my $mm = new File::MMagic;
                   3716:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3717:                 $$mimetype = $type;
                   3718:             }
                   3719:         }
                   3720:     }
1.637     raeburn  3721:     if ($parser eq 'parse') {
1.1152    raeburn  3722:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3723:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3724:                                                        $allfiles,$codebase);
                   3725:             unless ($parse_result eq 'ok') {
                   3726:                 &logthis('Failed to parse '.$filepath.$file.
                   3727: 	   	         ' for embedded media: '.$parse_result); 
                   3728:             }
1.637     raeburn  3729:         }
                   3730:     }
1.860     raeburn  3731:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3732:         my $input = $filepath.'/'.$file;
                   3733:         my $output = $filepath.'/'.'tn-'.$file;
                   3734:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3735:         system("convert -sample $thumbsize $input $output");
                   3736:         if (-e $filepath.'/'.'tn-'.$file) {
                   3737:             $fetchthumb  = 1; 
                   3738:         }
                   3739:     }
1.858     raeburn  3740:  
1.259     www      3741: # Notify homeserver to grep it
                   3742: #
1.984     neumanie 3743:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3744:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3745:     if ($fetchresult eq 'ok') {
1.860     raeburn  3746:         if ($fetchthumb) {
                   3747:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3748:             if ($thumbresult ne 'ok') {
                   3749:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3750:                          $docuhome.': '.$thumbresult);
                   3751:             }
                   3752:         }
1.259     www      3753: #
1.258     www      3754: # Return the URL to it
1.494     albertel 3755:         return '/uploaded/'.$path.$file;
1.263     www      3756:     } else {
1.494     albertel 3757:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3758: 		 ': '.$fetchresult);
1.263     www      3759:         return '/adm/notfound.html';
1.858     raeburn  3760:     }
1.493     albertel 3761: }
                   3762: 
1.637     raeburn  3763: sub extract_embedded_items {
1.961     raeburn  3764:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3765:     my @state = ();
1.1164    raeburn  3766:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3767:     my %javafiles = (
                   3768:                       codebase => '',
                   3769:                       code => '',
                   3770:                       archive => ''
                   3771:                     );
                   3772:     my %mediafiles = (
                   3773:                       src => '',
                   3774:                       movie => '',
                   3775:                      );
1.648     raeburn  3776:     my $p;
                   3777:     if ($content) {
                   3778:         $p = HTML::LCParser->new($content);
                   3779:     } else {
1.961     raeburn  3780:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3781:     }
1.641     albertel 3782:     while (my $t=$p->get_token()) {
1.640     albertel 3783: 	if ($t->[0] eq 'S') {
                   3784: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3785: 	    push(@state, $tagname);
1.648     raeburn  3786:             if (lc($tagname) eq 'allow') {
                   3787:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3788:             }
1.640     albertel 3789: 	    if (lc($tagname) eq 'img') {
                   3790: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3791: 	    }
1.886     albertel 3792: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3793:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3794:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3795:                 }
1.886     albertel 3796: 	    }
1.645     raeburn  3797:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3798:                 my $src;
1.645     raeburn  3799:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3800:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3801:                 } else {
1.1164    raeburn  3802:                     if ($attr->{'src'} ne '') {
                   3803:                         $src = $attr->{'src'};
                   3804:                         &add_filetype($allfiles,$src,'src');
                   3805:                     }
                   3806:                 }
                   3807:                 my $text = $p->get_trimmed_text();
                   3808:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3809:                     my @swfargs = split(/,/,$1);
                   3810:                     foreach my $item (@swfargs) {
                   3811:                         $item =~ s/["']//g;
                   3812:                         $item =~ s/^\s+//;
                   3813:                         $item =~ s/\s+$//;
                   3814:                     }
                   3815:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3816:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3817:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3818:                         } else {
                   3819:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3820:                         }
                   3821:                     }
1.645     raeburn  3822:                 }
                   3823:             }
                   3824:             if (lc($tagname) eq 'link') {
                   3825:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3826:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3827:                 }
                   3828:             }
1.640     albertel 3829: 	    if (lc($tagname) eq 'object' ||
                   3830: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3831: 		foreach my $item (keys(%javafiles)) {
                   3832: 		    $javafiles{$item} = '';
                   3833: 		}
1.1164    raeburn  3834:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3835:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3836:                 }
1.640     albertel 3837: 	    }
                   3838: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3839: 		my $name = lc($attr->{'name'});
                   3840: 		foreach my $item (keys(%javafiles)) {
                   3841: 		    if ($name eq $item) {
                   3842: 			$javafiles{$item} = $attr->{'value'};
                   3843: 			last;
                   3844: 		    }
                   3845: 		}
1.1164    raeburn  3846:                 my $pathfrom;
1.640     albertel 3847: 		foreach my $item (keys(%mediafiles)) {
                   3848: 		    if ($name eq $item) {
1.1164    raeburn  3849:                         $pathfrom = $attr->{'value'};
                   3850:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3851: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3852: 			last;
                   3853: 		    }
                   3854: 		}
1.1164    raeburn  3855:                 if ($name eq 'flashvars') {
                   3856:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3857:                 }
                   3858:                 if ($pathfrom ne '') {
                   3859:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3860:                                          $pathfrom);
                   3861:                 }
1.640     albertel 3862: 	    }
                   3863: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3864: 		foreach my $item (keys(%javafiles)) {
                   3865: 		    if ($attr->{$item}) {
                   3866: 			$javafiles{$item} = $attr->{$item};
                   3867: 			last;
                   3868: 		    }
                   3869: 		}
                   3870: 		foreach my $item (keys(%mediafiles)) {
                   3871: 		    if ($attr->{$item}) {
                   3872: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3873: 			last;
                   3874: 		    }
                   3875: 		}
1.1164    raeburn  3876:                 if (lc($tagname) eq 'embed') {
                   3877:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3878:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3879:                                              $attr->{'src'});
                   3880:                     }
                   3881:                 }
1.640     albertel 3882: 	    }
1.1243    raeburn  3883:             if (lc($tagname) eq 'iframe') {
                   3884:                 my $src = $attr->{'src'} ;
                   3885:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3886:                     &add_filetype($allfiles,$src,'src');
                   3887:                 } elsif ($src =~ m{^/}) {
                   3888:                     if ($env{'request.course.id'}) {
                   3889:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3890:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3891:                         my $url = &hreflocation('',$fullpath);
                   3892:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3893:                             my $relpath = $1;
                   3894:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3895:                                 &add_filetype($allfiles,$1,'src');
                   3896:                             }
                   3897:                         }
                   3898:                     }
                   3899:                 }
                   3900:             }
1.1164    raeburn  3901:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3902:                 pop(@state);
1.1164    raeburn  3903:             }
1.640     albertel 3904: 	} elsif ($t->[0] eq 'E') {
                   3905: 	    my ($tagname) = ($t->[1]);
                   3906: 	    if ($javafiles{'codebase'} ne '') {
                   3907: 		$javafiles{'codebase'} .= '/';
                   3908: 	    }  
                   3909: 	    if (lc($tagname) eq 'applet' ||
                   3910: 		lc($tagname) eq 'object' ||
                   3911: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3912: 		) {
                   3913: 		foreach my $item (keys(%javafiles)) {
                   3914: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3915: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3916: 			&add_filetype($allfiles,$file,$item);
                   3917: 		    }
                   3918: 		}
                   3919: 	    } 
                   3920: 	    pop @state;
                   3921: 	}
                   3922:     }
1.1164    raeburn  3923:     foreach my $id (sort(keys(%flashvars))) {
                   3924:         if ($shockwave{$id} ne '') {
                   3925:             my @pairs = split(/\&/,$flashvars{$id});
                   3926:             foreach my $pair (@pairs) {
                   3927:                 my ($key,$value) = split(/\=/,$pair);
                   3928:                 if ($key eq 'thumb') {
                   3929:                     &add_filetype($allfiles,$value,$key);
                   3930:                 } elsif ($key eq 'content') {
                   3931:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3932:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3933:                     if ($ext ne '') {
                   3934:                         &add_filetype($allfiles,$path.$value,$ext);
                   3935:                     }
                   3936:                 }
                   3937:             }
                   3938:         }
                   3939:     }
1.637     raeburn  3940:     return 'ok';
                   3941: }
                   3942: 
1.639     albertel 3943: sub add_filetype {
                   3944:     my ($allfiles,$file,$type)=@_;
                   3945:     if (exists($allfiles->{$file})) {
                   3946: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3947: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3948: 	}
                   3949:     } else {
                   3950: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3951:     }
                   3952: }
                   3953: 
1.1164    raeburn  3954: sub embedded_dependency {
                   3955:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3956:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3957:         if (($identifier ne '') &&
                   3958:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3959:             ($pathfrom ne '')) {
                   3960:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3961:             foreach my $dep (@{$related->{$identifier}}) {
                   3962:                 &add_filetype($allfiles,$path.$dep,'object');
                   3963:             }
                   3964:         }
                   3965:     }
                   3966:     return;
                   3967: }
                   3968: 
1.493     albertel 3969: sub removeuploadedurl {
1.984     neumanie 3970:     my ($url)=@_;	
                   3971:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3972:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3973: }
                   3974: 
                   3975: sub removeuserfile {
                   3976:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3977:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3978:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3979:     if ($result eq 'ok') {	
1.798     raeburn  3980:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3981:             my $metafile = $fname.'.meta';
                   3982:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3983: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3984:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3985:             my $sqlresult = 
1.823     albertel 3986:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3987:                                         'portfolio_metadata',$group,
                   3988:                                         'delete');
1.798     raeburn  3989:         }
                   3990:     }
                   3991:     return $result;
1.257     www      3992: }
1.15      www      3993: 
1.530     albertel 3994: sub mkdiruserfile {
                   3995:     my ($docuname,$docudom,$dir)=@_;
                   3996:     my $home=&homeserver($docuname,$docudom);
                   3997:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3998: }
                   3999: 
1.531     albertel 4000: sub renameuserfile {
                   4001:     my ($docuname,$docudom,$old,$new)=@_;
                   4002:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4003:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4004:                         &escape("$old").':'.&escape("$new"),$home);
                   4005:     if ($result eq 'ok') {
                   4006:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4007:             my $oldmeta = $old.'.meta';
                   4008:             my $newmeta = $new.'.meta';
                   4009:             my $metaresult = 
                   4010:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4011: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4012:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4013:             my $sqlresult = 
1.823     albertel 4014:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4015:                                         'portfolio_metadata',$group,
                   4016:                                         'delete');
1.798     raeburn  4017:         }
                   4018:     }
                   4019:     return $result;
1.531     albertel 4020: }
                   4021: 
1.14      www      4022: # ------------------------------------------------------------------------- Log
                   4023: 
                   4024: sub log {
                   4025:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4026:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4027: }
                   4028: 
                   4029: # ------------------------------------------------------------------ Course Log
1.352     www      4030: #
                   4031: # This routine flushes several buffers of non-mission-critical nature
                   4032: #
1.157     www      4033: 
                   4034: sub flushcourselogs {
1.352     www      4035:     &logthis('Flushing log buffers');
                   4036: #
                   4037: # course logs
                   4038: # This is a log of all transactions in a course, which can be used
                   4039: # for data mining purposes
                   4040: #
                   4041: # It also collects the courseid database, which lists last transaction
                   4042: # times and course titles for all courseids
                   4043: #
                   4044:     my %courseidbuffer=();
1.921     raeburn  4045:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4046:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4047: 		          &escape($courselogs{$crsid}),
                   4048: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4049: 	    delete $courselogs{$crsid};
                   4050:         } else {
                   4051:             &logthis('Failed to flush log buffer for '.$crsid);
                   4052:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4053:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4054:                         " exceeded maximum size, deleting.</font>");
                   4055:                delete $courselogs{$crsid};
                   4056:             }
1.352     www      4057:         }
1.920     raeburn  4058:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4059:             'description' => $coursedescrbuf{$crsid},
                   4060:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4061:             'type'        => $coursetypebuf{$crsid},
                   4062:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4063:         };
1.191     harris41 4064:     }
1.352     www      4065: #
                   4066: # Write course id database (reverse lookup) to homeserver of courses 
                   4067: # Is used in pickcourse
                   4068: #
1.840     albertel 4069:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4070:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4071:                                     $courseidbuffer{$crs_home},
                   4072:                                     $crs_home,'timeonly');
1.352     www      4073:     }
                   4074: #
                   4075: # File accesses
                   4076: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4077: #
1.449     matthew  4078:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4079:         if ($entry =~ /___count$/) {
                   4080:             my ($dom,$name);
1.807     albertel 4081:             ($dom,$name,undef)=
1.811     albertel 4082: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4083:             if (! defined($dom) || $dom eq '' || 
                   4084:                 ! defined($name) || $name eq '') {
1.620     albertel 4085:                 my $cid = $env{'request.course.id'};
                   4086:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4087:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4088:             }
1.450     matthew  4089:             my $value = $accesshash{$entry};
                   4090:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4091:             my %temphash=($url => $value);
1.449     matthew  4092:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4093:             if ($result eq 'ok') {
                   4094:                 delete $accesshash{$entry};
                   4095:             }
                   4096:         } else {
1.811     albertel 4097:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4098:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4099:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4100:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4101:                 delete $accesshash{$entry};
                   4102:             }
1.185     www      4103:         }
1.191     harris41 4104:     }
1.352     www      4105: #
                   4106: # Roles
                   4107: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4108: #
1.800     albertel 4109:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4110:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4111: 	    split(/\:/,$entry);
                   4112:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4113:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4114:                 $rudom,$runame) eq 'ok') {
                   4115: 	    delete $userrolehash{$entry};
                   4116:         }
                   4117:     }
1.662     raeburn  4118: #
1.1327    raeburn  4119: # Reverse lookup of domain roles (dc, ad, li, sc, dh, au)
1.662     raeburn  4120: #
                   4121:     my %domrolebuffer = ();
1.1000    raeburn  4122:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4123:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4124:         if ($domrolebuffer{$rudom}) {
                   4125:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4126:                       '='.&escape($domainrolehash{$entry});
                   4127:         } else {
                   4128:             $domrolebuffer{$rudom}.=&escape($entry).
                   4129:                       '='.&escape($domainrolehash{$entry});
                   4130:         }
                   4131:         delete $domainrolehash{$entry};
                   4132:     }
                   4133:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4134: 	my %servers;
                   4135: 	if (defined(&domain($dom,'primary'))) {
                   4136: 	    my $primary=&domain($dom,'primary');
                   4137: 	    my $hostname=&hostname($primary);
                   4138: 	    $servers{$primary} = $hostname;
                   4139: 	} else { 
                   4140: 	    %servers = &get_servers($dom,'library');
                   4141: 	}
1.841     albertel 4142: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4143: 	    if (&reply('domroleput:'.$dom.':'.
                   4144: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4145: 		last;
                   4146: 	    } else {  
1.841     albertel 4147: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4148: 	    }
1.662     raeburn  4149:         }
                   4150:     }
1.186     www      4151:     $dumpcount++;
1.157     www      4152: }
                   4153: 
                   4154: sub courselog {
                   4155:     my $what=shift;
1.158     www      4156:     $what=time.':'.$what;
1.620     albertel 4157:     unless ($env{'request.course.id'}) { return ''; }
                   4158:     $coursedombuf{$env{'request.course.id'}}=
                   4159:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4160:     $coursenumbuf{$env{'request.course.id'}}=
                   4161:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4162:     $coursehombuf{$env{'request.course.id'}}=
                   4163:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4164:     $coursedescrbuf{$env{'request.course.id'}}=
                   4165:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4166:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4167:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4168:     $courseownerbuf{$env{'request.course.id'}}=
                   4169:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4170:     $coursetypebuf{$env{'request.course.id'}}=
                   4171:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4172:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4173: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4174:     } else {
1.620     albertel 4175: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4176:     }
1.620     albertel 4177:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4178: 	&flushcourselogs();
                   4179:     }
1.158     www      4180: }
                   4181: 
                   4182: sub courseacclog {
                   4183:     my $fnsymb=shift;
1.620     albertel 4184:     unless ($env{'request.course.id'}) { return ''; }
                   4185:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4186:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4187:         $what.=':POST';
1.583     matthew  4188:         # FIXME: Probably ought to escape things....
1.800     albertel 4189: 	foreach my $key (keys(%env)) {
                   4190:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4191:                 my $formitem = $1;
                   4192:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4193:                     $what.=':'.$formitem.'='.$env{$key};
                   4194:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4195:                     $what.=':'.$formitem.'='.$env{$key};
                   4196:                 }
1.158     www      4197:             }
1.191     harris41 4198:         }
1.583     matthew  4199:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4200:         # FIXME: We should not be depending on a form parameter that someone
                   4201:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4202:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4203:             $what.= ':POST';
                   4204:             # FIXME: Probably ought to escape things....
                   4205:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4206:                                  'crsdiscuss') {
1.620     albertel 4207:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4208:             }
                   4209:         }
1.158     www      4210:     }
                   4211:     &courselog($what);
1.149     www      4212: }
                   4213: 
1.185     www      4214: sub countacc {
                   4215:     my $url=&declutter(shift);
1.458     matthew  4216:     return if (! defined($url) || $url eq '');
1.620     albertel 4217:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4218: #
                   4219: # Mark that this url was used in this course
                   4220: #
1.620     albertel 4221:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4222: #
                   4223: # Increase the access count for this resource in this child process
                   4224: #
1.281     www      4225:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4226:     $accesshash{$key}++;
1.185     www      4227: }
1.349     www      4228: 
1.361     www      4229: sub linklog {
                   4230:     my ($from,$to)=@_;
                   4231:     $from=&declutter($from);
                   4232:     $to=&declutter($to);
                   4233:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4234:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4235: }
1.1160    www      4236: 
                   4237: sub statslog {
                   4238:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4239:     if ($users<2) { return; }
                   4240:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4241:             'course'       => $env{'request.course.id'},
                   4242:             'sections'     => '"all"',
                   4243:             'num_students' => $users,
                   4244:             'part'         => $part,
                   4245:             'symb'         => $symb,
                   4246:             'mean_tries'   => $av_attempts,
                   4247:             'deg_of_diff'  => $degdiff});
                   4248:     foreach my $key (keys(%dynstore)) {
                   4249:         $accesshash{$key}=$dynstore{$key};
                   4250:     }
                   4251: }
1.361     www      4252:   
1.349     www      4253: sub userrolelog {
                   4254:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4255:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4256:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4257:        $userrolehash
                   4258:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4259:                     =$tend.':'.$tstart;
1.662     raeburn  4260:     }
1.1169    droeschl 4261:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4262:        $userrolehash
                   4263:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4264:                     =$tend.':'.$tstart;
                   4265:     }
1.1327    raeburn  4266:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh)/ ) {
1.662     raeburn  4267:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4268:        $domainrolehash
                   4269:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4270:                     = $tend.':'.$tstart;
                   4271:     }
1.351     www      4272: }
                   4273: 
1.957     raeburn  4274: sub courserolelog {
                   4275:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4276:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4277:         my $cdom = $1;
                   4278:         my $cnum = $2;
                   4279:         my $sec = $3;
                   4280:         my $namespace = 'rolelog';
                   4281:         my %storehash = (
                   4282:                            role    => $trole,
                   4283:                            start   => $tstart,
                   4284:                            end     => $tend,
                   4285:                            selfenroll => $selfenroll,
                   4286:                            context    => $context,
                   4287:                         );
                   4288:         if ($trole eq 'gr') {
                   4289:             $namespace = 'groupslog';
                   4290:             $storehash{'group'} = $sec;
                   4291:         } else {
                   4292:             $storehash{'section'} = $sec;
                   4293:         }
1.1188    raeburn  4294:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4295:                    $domain,$cnum,$cdom);
1.1184    raeburn  4296:         if (($trole ne 'st') || ($sec ne '')) {
                   4297:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4298:         }
                   4299:     }
                   4300:     return;
                   4301: }
                   4302: 
1.1184    raeburn  4303: sub domainrolelog {
                   4304:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4305:     if ($area =~ m{^/($match_domain)/$}) {
                   4306:         my $cdom = $1;
                   4307:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4308:         my $namespace = 'rolelog';
                   4309:         my %storehash = (
                   4310:                            role    => $trole,
                   4311:                            start   => $tstart,
                   4312:                            end     => $tend,
                   4313:                            context => $context,
                   4314:                         );
1.1188    raeburn  4315:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4316:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4317:     }
                   4318:     return;
                   4319: 
                   4320: }
                   4321: 
                   4322: sub coauthorrolelog {
                   4323:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4324:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4325:         my $audom = $1;
                   4326:         my $auname = $2;
                   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('author',$namespace,\%storehash,$delflag,$username,
                   4335:                    $domain,$auname,$audom);
1.1184    raeburn  4336:     }
                   4337:     return;
                   4338: }
                   4339: 
1.351     www      4340: sub get_course_adv_roles {
1.948     raeburn  4341:     my ($cid,$codes) = @_;
1.620     albertel 4342:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4343:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4344:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4345:     my %nothide=();
1.800     albertel 4346:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4347:         if ($user !~ /:/) {
                   4348: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4349:         } else {
                   4350:             $nothide{$user}=1;
                   4351:         }
1.470     www      4352:     }
1.1219    raeburn  4353:     my @possdoms = ($coursehash{'domain'});
                   4354:     if ($coursehash{'checkforpriv'}) {
                   4355:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4356:     }
1.351     www      4357:     my %returnhash=();
                   4358:     my %dumphash=
                   4359:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4360:     my $now=time;
1.997     raeburn  4361:     my %privileged;
1.1000    raeburn  4362:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4363: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4364:         if (($tstart) && ($tstart<0)) { next; }
                   4365:         if (($tend) && ($tend<$now)) { next; }
                   4366:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4367:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4368: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4369:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4370:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4371: 	if ($role eq 'cr') { next; }
1.948     raeburn  4372:         if ($codes) {
                   4373:             if ($section) { $role .= ':'.$section; }
                   4374:             if ($returnhash{$role}) {
                   4375:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4376:             } else {
                   4377:                 $returnhash{$role}=$username.':'.$domain;
                   4378:             }
1.351     www      4379:         } else {
1.988     raeburn  4380:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4381:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4382:             if ($returnhash{$key}) {
                   4383: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4384:             } else {
                   4385:                 $returnhash{$key}=$username.':'.$domain;
                   4386:             }
1.351     www      4387:         }
1.948     raeburn  4388:     }
1.400     www      4389:     return %returnhash;
                   4390: }
                   4391: 
                   4392: sub get_my_roles {
1.937     raeburn  4393:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4394:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4395:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4396:     my (%dumphash,%nothide);
1.1086    raeburn  4397:     if ($context eq 'userroles') {
1.1166    raeburn  4398:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4399:     } else {
1.1219    raeburn  4400:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4401:         if ($hidepriv) {
                   4402:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4403:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4404:                 if ($user !~ /:/) {
                   4405:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4406:                 } else {
                   4407:                     $nothide{$user} = 1;
                   4408:                 }
                   4409:             }
                   4410:         }
1.858     raeburn  4411:     }
1.400     www      4412:     my %returnhash=();
                   4413:     my $now=time;
1.999     raeburn  4414:     my %privileged;
1.800     albertel 4415:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4416:         my ($role,$tend,$tstart);
                   4417:         if ($context eq 'userroles') {
1.1149    raeburn  4418:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4419: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4420:         } else {
                   4421:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4422:         }
1.400     www      4423:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4424:         my $status = 'active';
1.939     raeburn  4425:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4426:             $status = 'previous';
                   4427:         } 
                   4428:         if (($tstart) && ($now<$tstart)) {
                   4429:             $status = 'future';
                   4430:         }
                   4431:         if (ref($types) eq 'ARRAY') {
                   4432:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4433:                 next;
                   4434:             } 
                   4435:         } else {
                   4436:             if ($status ne 'active') {
                   4437:                 next;
                   4438:             }
                   4439:         }
1.867     raeburn  4440:         my ($rolecode,$username,$domain,$section,$area);
                   4441:         if ($context eq 'userroles') {
1.1186    raeburn  4442:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4443:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4444:         } else {
                   4445:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4446:         }
1.832     raeburn  4447:         if (ref($roledoms) eq 'ARRAY') {
                   4448:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4449:                 next;
                   4450:             }
                   4451:         }
                   4452:         if (ref($roles) eq 'ARRAY') {
                   4453:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4454:                 if ($role =~ /^cr\//) {
                   4455:                     if (!grep(/^cr$/,@{$roles})) {
                   4456:                         next;
                   4457:                     }
1.1104    raeburn  4458:                 } elsif ($role =~ /^gr\//) {
                   4459:                     if (!grep(/^gr$/,@{$roles})) {
                   4460:                         next;
                   4461:                     }
1.922     raeburn  4462:                 } else {
                   4463:                     next;
                   4464:                 }
1.832     raeburn  4465:             }
1.867     raeburn  4466:         }
1.937     raeburn  4467:         if ($hidepriv) {
1.1219    raeburn  4468:             my @privroles = ('dc','su');
1.999     raeburn  4469:             if ($context eq 'userroles') {
1.1219    raeburn  4470:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4471:             } else {
1.1219    raeburn  4472:                 my $possdoms = [$domain];
                   4473:                 if (ref($roledoms) eq 'ARRAY') {
                   4474:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4475:                 }
1.1219    raeburn  4476:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4477:                     if (!$nothide{$username.':'.$domain}) {
                   4478:                         next;
                   4479:                     }
                   4480:                 }
1.937     raeburn  4481:             }
                   4482:         }
1.933     raeburn  4483:         if ($withsec) {
                   4484:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4485:                 $tstart.':'.$tend;
                   4486:         } else {
                   4487:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4488:         }
1.832     raeburn  4489:     }
1.373     www      4490:     return %returnhash;
1.399     www      4491: }
                   4492: 
1.1332  ! raeburn  4493: sub get_my_adhocroles {
        !          4494:     my ($cid) = @_;
        !          4495:     my (@possroles,%description);
        !          4496:     if ($cid =~ /^($match_domain)_($match_courseid)$/) {
        !          4497:         my $cdom = $1;
        !          4498:         my $cnum = $2;
        !          4499:         if ($env{"user.role.dh./$cdom/"}) {
        !          4500:             my $then=$env{'user.login.time'};
        !          4501:             my $update=$env{'user.update.time'};
        !          4502:             my $liverole = 1;
        !          4503:             my ($tstart,$tend)=split(/\./,$env{'user.role.dh./'.$cdom});
        !          4504:             my $limit = $update;
        !          4505:             if ($env{'request.role'} eq 'dh./'.$cdom.'/') {
        !          4506:                 $limit = $then;
        !          4507:             }
        !          4508:             if ($tstart && $tstart>$limit) { $liverole = 0; }
        !          4509:             if ($tend   && $tend  <$limit) { $liverole = 0; }
        !          4510:             if ($liverole) {
        !          4511:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
        !          4512:                     my %domdefaults = &get_domain_defaults($cdom);
        !          4513:                     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
        !          4514:                         my $count = 0;
        !          4515:                         my %domcurrent = %{$domdefaults{'adhocroles'}};
        !          4516:                         my (%ordered,%access_in_dom);
        !          4517:                         foreach my $role (sort(keys(%domcurrent))) {
        !          4518:                             my ($order,$desc,$access_in_dom);
        !          4519:                             if (ref($domcurrent{$role}) eq 'HASH') {
        !          4520:                                 $order = $domcurrent{$role}{'order'};
        !          4521:                                 $desc = $domcurrent{$role}{'desc'};
        !          4522:                                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
        !          4523:                             }
        !          4524:                             if ($order eq '') {
        !          4525:                                 $order = $count;
        !          4526:                             }
        !          4527:                             $ordered{$order} = $role;
        !          4528:                             if ($desc ne '') {
        !          4529:                                 $description{$role} = $desc;
        !          4530:                             } else {
        !          4531:                                 $description{$role}= $role;
        !          4532:                             }
        !          4533:                             $count++;
        !          4534:                         }
        !          4535:                         my @roles_by_num = ();
        !          4536:                         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
        !          4537:                             push(@roles_by_num,$ordered{$item});
        !          4538:                         }
        !          4539:                         if (@roles_by_num) {
        !          4540:                             my %settings;
        !          4541:                             if ($env{'request.course.id'} eq $cid) {
        !          4542:                                 foreach my $envkey (keys(%env)) {
        !          4543:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
        !          4544:                                         $settings{$1} = $env{$envkey};
        !          4545:                                     }
        !          4546:                                 }
        !          4547:                             } else {
        !          4548:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
        !          4549:                             }
        !          4550:                             my %setincrs;
        !          4551:                             if ($settings{'internal.adhocaccess'}) {
        !          4552:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
        !          4553:                             }
        !          4554:                             my @statuses;
        !          4555:                             if ($env{'environment.inststatus'}) {
        !          4556:                                 @statuses = split(/,/,$env{'environment.inststatus'});
        !          4557:                             }
        !          4558:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
        !          4559:                             foreach my $role (@roles_by_num) {
        !          4560:                                 my ($curraccess,@okstatus,@personnel);
        !          4561:                                 if ($setincrs{$role}) {
        !          4562:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
        !          4563:                                     if ($curraccess eq 'status') {
        !          4564:                                         @okstatus = split(/\&/,$rest);
        !          4565:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
        !          4566:                                         @personnel = split(/\&/,$rest);
        !          4567:                                     }
        !          4568:                                 } else {
        !          4569:                                     $curraccess = $access_in_dom{$role};
        !          4570:                                     if ($curraccess eq 'status') {
        !          4571:                                         if (ref($domcurrent{$role}{$curraccess}) eq 'ARRAY') {
        !          4572:                                             @okstatus = @{$domcurrent{$role}{$curraccess}};
        !          4573:                                         }
        !          4574:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
        !          4575:                                         if (ref($domcurrent{$role}{$curraccess}) eq 'ARRAY') {
        !          4576:                                             @personnel = @{$domcurrent{$role}{$curraccess}};
        !          4577:                                         }
        !          4578:                                     }
        !          4579:                                 }
        !          4580:                                 if ($curraccess eq 'none') {
        !          4581:                                     next;
        !          4582:                                 } elsif ($curraccess eq 'all') {
        !          4583:                                     push(@possroles,$role);
        !          4584:                                 } elsif ($curraccess eq 'status') {
        !          4585:                                     if (@okstatus) {
        !          4586:                                         if (!@statuses) {
        !          4587:                                             if (grep(/^default$/,@okstatus)) {
        !          4588:                                                 push(@possroles,$role);
        !          4589:                                             }
        !          4590:                                         } else {
        !          4591:                                             foreach my $status (@okstatus) {
        !          4592:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
        !          4593:                                                     push(@possroles,$role);
        !          4594:                                                     last;
        !          4595:                                                 }
        !          4596:                                             }
        !          4597:                                         }
        !          4598:                                     }
        !          4599:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
        !          4600:                                     if (grep(/^\Q$user\E$/,@personnel)) {
        !          4601:                                         if ($curraccess eq 'exc') {
        !          4602:                                             push(@possroles,$role);
        !          4603:                                         }
        !          4604:                                     } elsif ($curraccess eq 'inc') {
        !          4605:                                         push(@possroles,$role);
        !          4606:                                     }
        !          4607:                                 }
        !          4608:                             }
        !          4609:                         }
        !          4610:                     }
        !          4611:                 }
        !          4612:             }
        !          4613:         }
        !          4614:     }
        !          4615:     return (\@possroles,\%description);
        !          4616: }
        !          4617: 
1.399     www      4618: # ----------------------------------------------------- Frontpage Announcements
                   4619: #
                   4620: #
                   4621: 
                   4622: sub postannounce {
                   4623:     my ($server,$text)=@_;
1.844     albertel 4624:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4625:     unless ($text=~/\w/) { $text=''; }
                   4626:     return &reply('setannounce:'.&escape($text),$server);
                   4627: }
                   4628: 
                   4629: sub getannounce {
1.448     albertel 4630: 
                   4631:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4632: 	my $announcement='';
1.800     albertel 4633: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4634: 	close($fh);
1.399     www      4635: 	if ($announcement=~/\w/) { 
                   4636: 	    return 
                   4637:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4638:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4639: 	} else {
                   4640: 	    return '';
                   4641: 	}
                   4642:     } else {
                   4643: 	return '';
                   4644:     }
1.351     www      4645: }
1.353     www      4646: 
                   4647: # ---------------------------------------------------------- Course ID routines
                   4648: # Deal with domain's nohist_courseid.db files
                   4649: #
                   4650: 
                   4651: sub courseidput {
1.921     raeburn  4652:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4653:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4654:     my $outcome;
                   4655:     if ($caller eq 'timeonly') {
                   4656:         my $cids = '';
                   4657:         foreach my $item (keys(%$storehash)) {
                   4658:             $cids.=&escape($item).'&';
                   4659:         }
                   4660:         $cids=~s/\&$//;
                   4661:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4662:                           $coursehome);       
                   4663:     } else {
                   4664:         my $items = '';
                   4665:         foreach my $item (keys(%$storehash)) {
                   4666:             $items.= &escape($item).'='.
                   4667:                      &freeze_escape($$storehash{$item}).'&';
                   4668:         }
                   4669:         $items=~s/\&$//;
                   4670:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4671:                           $coursehome);
1.918     raeburn  4672:     }
                   4673:     if ($outcome eq 'unknown_cmd') {
                   4674:         my $what;
                   4675:         foreach my $cid (keys(%$storehash)) {
                   4676:             $what .= &escape($cid).'=';
1.921     raeburn  4677:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4678:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4679:             }
                   4680:             $what =~ s/\:$/&/;
                   4681:         }
                   4682:         $what =~ s/\&$//;  
                   4683:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4684:     } else {
                   4685:         return $outcome;
                   4686:     }
1.353     www      4687: }
                   4688: 
                   4689: sub courseiddump {
1.921     raeburn  4690:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4691:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4692:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4693:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4694:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4695:     my $as_hash = 1;
                   4696:     my %returnhash;
                   4697:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4698:     my %libserv = &all_library();
                   4699:     foreach my $tryserver (keys(%libserv)) {
                   4700:         if ( (  $hostidflag == 1 
                   4701: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4702: 	     || (!defined($hostidflag)) ) {
                   4703: 
1.918     raeburn  4704: 	    if (($domfilter eq '') ||
                   4705: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4706:                 my $rep;
                   4707:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4708:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4709:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4710:                                 &escape($descfilter), &escape($instcodefilter), 
                   4711:                                 &escape($ownerfilter), &escape($coursefilter),
                   4712:                                 &escape($typefilter), &escape($regexp_ok), 
                   4713:                                 $as_hash, &escape($selfenrollonly), 
                   4714:                                 &escape($catfilter), $showhidden, $caller, 
                   4715:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4716:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4717:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4718:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4719:                 } else {
                   4720:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4721:                              $sincefilter.':'.&escape($descfilter).':'.
                   4722:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4723:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4724:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4725:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4726:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4727:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4728:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4729:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4730:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4731:                 }
                   4732:                      
1.918     raeburn  4733:                 my @pairs=split(/\&/,$rep);
                   4734:                 foreach my $item (@pairs) {
                   4735:                     my ($key,$value)=split(/\=/,$item,2);
                   4736:                     $key = &unescape($key);
                   4737:                     next if ($key =~ /^error: 2 /);
                   4738:                     my $result = &thaw_unescape($value);
                   4739:                     if (ref($result) eq 'HASH') {
                   4740:                         $returnhash{$key}=$result;
                   4741:                     } else {
1.921     raeburn  4742:                         my @responses = split(/:/,$value);
                   4743:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4744:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4745:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4746:                         }
1.1008    raeburn  4747:                     }
1.353     www      4748:                 }
                   4749:             }
                   4750:         }
                   4751:     }
                   4752:     return %returnhash;
                   4753: }
                   4754: 
1.1055    raeburn  4755: sub courselastaccess {
                   4756:     my ($cdom,$cnum,$hostidref) = @_;
                   4757:     my %returnhash;
                   4758:     if ($cdom && $cnum) {
                   4759:         my $chome = &homeserver($cnum,$cdom);
                   4760:         if ($chome ne 'no_host') {
                   4761:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4762:             &extract_lastaccess(\%returnhash,$rep);
                   4763:         }
                   4764:     } else {
                   4765:         if (!$cdom) { $cdom=''; }
                   4766:         my %libserv = &all_library();
                   4767:         foreach my $tryserver (keys(%libserv)) {
                   4768:             if (ref($hostidref) eq 'ARRAY') {
                   4769:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4770:             } 
                   4771:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4772:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4773:                 &extract_lastaccess(\%returnhash,$rep);
                   4774:             }
                   4775:         }
                   4776:     }
                   4777:     return %returnhash;
                   4778: }
                   4779: 
                   4780: sub extract_lastaccess {
                   4781:     my ($returnhash,$rep) = @_;
                   4782:     if (ref($returnhash) eq 'HASH') {
                   4783:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4784:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4785:                  $rep eq '') {
                   4786:             my @pairs=split(/\&/,$rep);
                   4787:             foreach my $item (@pairs) {
                   4788:                 my ($key,$value)=split(/\=/,$item,2);
                   4789:                 $key = &unescape($key);
                   4790:                 next if ($key =~ /^error: 2 /);
                   4791:                 $returnhash->{$key} = &thaw_unescape($value);
                   4792:             }
                   4793:         }
                   4794:     }
                   4795:     return;
                   4796: }
                   4797: 
1.658     raeburn  4798: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4799: 
                   4800: sub dcmailput {
1.685     raeburn  4801:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4802:     my $status = &Apache::lonnet::critical(
1.740     www      4803:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4804:        &escape($message),$server);
1.662     raeburn  4805:     return $status;
                   4806: }
                   4807: 
1.658     raeburn  4808: sub dcmaildump {
                   4809:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4810:     my %returnhash=();
1.846     albertel 4811: 
                   4812:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4813:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4814:                                                          &escape($enddate).':';
                   4815: 	my @esc_senders=map { &escape($_)} @$senders;
                   4816: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4817: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4818:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4819:             if (($key) && ($value)) {
                   4820:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4821:             }
                   4822:         }
                   4823:     }
                   4824:     return %returnhash;
                   4825: }
1.662     raeburn  4826: # ---------------------------------------------------------- Domain roles
                   4827: 
                   4828: sub get_domain_roles {
                   4829:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4830:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4831:         $startdate = '.';
                   4832:     }
1.1018    raeburn  4833:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4834:         $enddate = '.';
                   4835:     }
1.922     raeburn  4836:     my $rolelist;
                   4837:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4838:         $rolelist = join('&',@{$roles});
1.922     raeburn  4839:     }
1.662     raeburn  4840:     my %personnel = ();
1.841     albertel 4841: 
                   4842:     my %servers = &get_servers($dom,'library');
                   4843:     foreach my $tryserver (keys(%servers)) {
                   4844: 	%{$personnel{$tryserver}}=();
                   4845: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4846: 					    &escape($startdate).':'.
                   4847: 					    &escape($enddate).':'.
                   4848: 					    &escape($rolelist), $tryserver))) {
                   4849: 	    my ($key,$value) = split(/\=/,$line,2);
                   4850: 	    if (($key) && ($value)) {
                   4851: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4852: 	    }
                   4853: 	}
1.662     raeburn  4854:     }
                   4855:     return %personnel;
                   4856: }
1.658     raeburn  4857: 
1.1332  ! raeburn  4858: sub get_active_domroles {
        !          4859:     my ($dom,$roles) = @_;
        !          4860:     return () unless (ref($roles) eq 'ARRAY');
        !          4861:     my $now = time;
        !          4862:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
        !          4863:     my %domroles;
        !          4864:     foreach my $server (keys(%dompersonnel)) {
        !          4865:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
        !          4866:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
        !          4867:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
        !          4868:         }
        !          4869:     }
        !          4870:     return %domroles;
        !          4871: }
        !          4872: 
1.1057    www      4873: # ----------------------------------------------------------- Interval timing 
1.149     www      4874: 
1.1153    www      4875: {
                   4876: # Caches needed for speedup of navmaps
                   4877: # We don't want to cache this for very long at all (5 seconds at most)
                   4878: # 
                   4879: # The user for whom we cache
                   4880: my $cachedkey='';
                   4881: # The cached times for this user
                   4882: my %cachedtimes=();
                   4883: # When this was last done
1.1282    raeburn  4884: my $cachedtime='';
1.1153    www      4885: 
                   4886: sub load_all_first_access {
1.1308    raeburn  4887:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4888:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4889:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4890:         (!$ignorecache)) {
1.1154    raeburn  4891:         return;
                   4892:     }
                   4893:     $cachedtime=time;
                   4894:     $cachedkey=$uname.':'.$udom;
                   4895:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4896: }
                   4897: 
1.504     albertel 4898: sub get_first_access {
1.1308    raeburn  4899:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 4900:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4901:     if ($argsymb) { $symb=$argsymb; }
                   4902:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4903:     if ($argmap) { $map = $argmap; }
1.926     albertel 4904:     if ($type eq 'course') {
                   4905: 	$res='course';
                   4906:     } elsif ($type eq 'map') {
1.588     albertel 4907: 	$res=&symbread($map);
                   4908:     } else {
                   4909: 	$res=$symb;
                   4910:     }
1.1308    raeburn  4911:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      4912:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4913: }
                   4914: 
                   4915: sub set_first_access {
1.1162    raeburn  4916:     my ($type,$interval)=@_;
1.790     albertel 4917:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4918:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4919:     if ($type eq 'course') {
                   4920: 	$res='course';
                   4921:     } elsif ($type eq 'map') {
1.588     albertel 4922: 	$res=&symbread($map);
                   4923:     } else {
                   4924: 	$res=$symb;
                   4925:     }
1.1153    www      4926:     $cachedkey='';
1.1162    raeburn  4927:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4928:     if (!$firstaccess) {
1.1162    raeburn  4929:         my $start = time;
                   4930: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4931:                           $udom,$uname);
                   4932:         if ($putres eq 'ok') {
                   4933:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4934:                  $udom,$uname); 
                   4935:             &appenv(
                   4936:                      {
                   4937:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4938:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4939:                      }
                   4940:                   );
                   4941:         }
                   4942:         return $putres;
1.505     albertel 4943:     }
                   4944:     return 'already_set';
1.504     albertel 4945: }
1.1153    www      4946: }
1.1282    raeburn  4947: 
1.110     www      4948: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4949: 
                   4950: sub expirespread {
                   4951:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4952:     my $cid=$env{'request.course.id'}; 
1.110     www      4953:     if ($cid) {
                   4954:        my $now=time;
                   4955:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4956:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4957:                             $env{'course.'.$cid.'.num'}.
1.110     www      4958: 	        	    ':nohist_expirationdates:'.
                   4959:                             &escape($key).'='.$now,
1.620     albertel 4960:                             $env{'course.'.$cid.'.home'})
1.110     www      4961:     }
                   4962:     return 'ok';
1.14      www      4963: }
                   4964: 
1.109     www      4965: # ----------------------------------------------------- Devalidate Spreadsheets
                   4966: 
                   4967: sub devalidate {
1.325     www      4968:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4969:     my $cid=$env{'request.course.id'}; 
1.109     www      4970:     if ($cid) {
1.391     matthew  4971:         # delete the stored spreadsheets for
                   4972:         # - the student level sheet of this user in course's homespace
                   4973:         # - the assessment level sheet for this resource 
                   4974:         #   for this user in user's homespace
1.553     albertel 4975: 	# - current conditional state info
1.325     www      4976: 	my $key=$uname.':'.$udom.':';
1.109     www      4977:         my $status=
1.299     matthew  4978: 	    &del('nohist_calculatedsheets',
1.391     matthew  4979: 		 [$key.'studentcalc:'],
1.620     albertel 4980: 		 $env{'course.'.$cid.'.domain'},
                   4981: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4982: 		.' '.
                   4983: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4984: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4985:         unless ($status eq 'ok ok') {
                   4986:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4987:                     $uname.' at '.$udom.' for '.
1.109     www      4988: 		    $symb.': '.$status);
1.133     albertel 4989:         }
1.553     albertel 4990: 	&delenv('user.state.'.$cid);
1.109     www      4991:     }
                   4992: }
                   4993: 
1.265     albertel 4994: sub get_scalar {
                   4995:     my ($string,$end) = @_;
                   4996:     my $value;
                   4997:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4998: 	$value = $1;
                   4999:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5000: 	$value = $1;
                   5001:     }
                   5002:     return &unescape($value);
                   5003: }
                   5004: 
                   5005: sub array2str {
                   5006:   my (@array) = @_;
                   5007:   my $result=&arrayref2str(\@array);
                   5008:   $result=~s/^__ARRAY_REF__//;
                   5009:   $result=~s/__END_ARRAY_REF__$//;
                   5010:   return $result;
                   5011: }
                   5012: 
1.204     albertel 5013: sub arrayref2str {
                   5014:   my ($arrayref) = @_;
1.265     albertel 5015:   my $result='__ARRAY_REF__';
1.204     albertel 5016:   foreach my $elem (@$arrayref) {
1.265     albertel 5017:     if(ref($elem) eq 'ARRAY') {
                   5018:       $result.=&arrayref2str($elem).'&';
                   5019:     } elsif(ref($elem) eq 'HASH') {
                   5020:       $result.=&hashref2str($elem).'&';
                   5021:     } elsif(ref($elem)) {
                   5022:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5023:     } else {
                   5024:       $result.=&escape($elem).'&';
                   5025:     }
                   5026:   }
                   5027:   $result=~s/\&$//;
1.265     albertel 5028:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5029:   return $result;
                   5030: }
                   5031: 
1.168     albertel 5032: sub hash2str {
1.204     albertel 5033:   my (%hash) = @_;
                   5034:   my $result=&hashref2str(\%hash);
1.265     albertel 5035:   $result=~s/^__HASH_REF__//;
                   5036:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5037:   return $result;
                   5038: }
                   5039: 
                   5040: sub hashref2str {
                   5041:   my ($hashref)=@_;
1.265     albertel 5042:   my $result='__HASH_REF__';
1.800     albertel 5043:   foreach my $key (sort(keys(%$hashref))) {
                   5044:     if (ref($key) eq 'ARRAY') {
                   5045:       $result.=&arrayref2str($key).'=';
                   5046:     } elsif (ref($key) eq 'HASH') {
                   5047:       $result.=&hashref2str($key).'=';
                   5048:     } elsif (ref($key)) {
1.265     albertel 5049:       $result.='=';
1.800     albertel 5050:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5051:     } else {
1.1132    raeburn  5052: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5053:     }
                   5054: 
1.800     albertel 5055:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5056:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5057:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5058:       $result.=&hashref2str($hashref->{$key}).'&';
                   5059:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5060:        $result.='&';
1.800     albertel 5061:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5062:     } else {
1.800     albertel 5063:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5064:     }
                   5065:   }
1.168     albertel 5066:   $result=~s/\&$//;
1.265     albertel 5067:   $result .= '__END_HASH_REF__';
1.168     albertel 5068:   return $result;
                   5069: }
                   5070: 
                   5071: sub str2hash {
1.265     albertel 5072:     my ($string)=@_;
                   5073:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5074:     return %$hash;
                   5075: }
                   5076: 
                   5077: sub str2hashref {
1.168     albertel 5078:   my ($string) = @_;
1.265     albertel 5079: 
                   5080:   my %hash;
                   5081: 
                   5082:   if($string !~ /^__HASH_REF__/) {
                   5083:       if (! ($string eq '' || !defined($string))) {
                   5084: 	  $hash{'error'}='Not hash reference';
                   5085:       }
                   5086:       return (\%hash, $string);
                   5087:   }
                   5088: 
                   5089:   $string =~ s/^__HASH_REF__//;
                   5090: 
                   5091:   while($string !~ /^__END_HASH_REF__/) {
                   5092:       #key
                   5093:       my $key='';
                   5094:       if($string =~ /^__HASH_REF__/) {
                   5095:           ($key, $string)=&str2hashref($string);
                   5096:           if(defined($key->{'error'})) {
                   5097:               $hash{'error'}='Bad data';
                   5098:               return (\%hash, $string);
                   5099:           }
                   5100:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5101:           ($key, $string)=&str2arrayref($string);
                   5102:           if($key->[0] eq 'Array reference error') {
                   5103:               $hash{'error'}='Bad data';
                   5104:               return (\%hash, $string);
                   5105:           }
                   5106:       } else {
                   5107:           $string =~ s/^(.*?)=//;
1.267     albertel 5108: 	  $key=&unescape($1);
1.265     albertel 5109:       }
                   5110:       $string =~ s/^=//;
                   5111: 
                   5112:       #value
                   5113:       my $value='';
                   5114:       if($string =~ /^__HASH_REF__/) {
                   5115:           ($value, $string)=&str2hashref($string);
                   5116:           if(defined($value->{'error'})) {
                   5117:               $hash{'error'}='Bad data';
                   5118:               return (\%hash, $string);
                   5119:           }
                   5120:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5121:           ($value, $string)=&str2arrayref($string);
                   5122:           if($value->[0] eq 'Array reference error') {
                   5123:               $hash{'error'}='Bad data';
                   5124:               return (\%hash, $string);
                   5125:           }
                   5126:       } else {
                   5127: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5128:       }
                   5129:       $string =~ s/^&//;
                   5130: 
                   5131:       $hash{$key}=$value;
1.204     albertel 5132:   }
1.265     albertel 5133: 
                   5134:   $string =~ s/^__END_HASH_REF__//;
                   5135: 
                   5136:   return (\%hash, $string);
1.204     albertel 5137: }
                   5138: 
                   5139: sub str2array {
1.265     albertel 5140:     my ($string)=@_;
                   5141:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5142:     return @$array;
                   5143: }
                   5144: 
                   5145: sub str2arrayref {
1.204     albertel 5146:   my ($string) = @_;
1.265     albertel 5147:   my @array;
                   5148: 
                   5149:   if($string !~ /^__ARRAY_REF__/) {
                   5150:       if (! ($string eq '' || !defined($string))) {
                   5151: 	  $array[0]='Array reference error';
                   5152:       }
                   5153:       return (\@array, $string);
                   5154:   }
                   5155: 
                   5156:   $string =~ s/^__ARRAY_REF__//;
                   5157: 
                   5158:   while($string !~ /^__END_ARRAY_REF__/) {
                   5159:       my $value='';
                   5160:       if($string =~ /^__HASH_REF__/) {
                   5161:           ($value, $string)=&str2hashref($string);
                   5162:           if(defined($value->{'error'})) {
                   5163:               $array[0] ='Array reference error';
                   5164:               return (\@array, $string);
                   5165:           }
                   5166:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5167:           ($value, $string)=&str2arrayref($string);
                   5168:           if($value->[0] eq 'Array reference error') {
                   5169:               $array[0] ='Array reference error';
                   5170:               return (\@array, $string);
                   5171:           }
                   5172:       } else {
                   5173: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5174:       }
                   5175:       $string =~ s/^&//;
                   5176: 
                   5177:       push(@array, $value);
1.191     harris41 5178:   }
1.265     albertel 5179: 
                   5180:   $string =~ s/^__END_ARRAY_REF__//;
                   5181: 
                   5182:   return (\@array, $string);
1.168     albertel 5183: }
                   5184: 
1.167     albertel 5185: # -------------------------------------------------------------------Temp Store
                   5186: 
1.168     albertel 5187: sub tmpreset {
                   5188:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5189:   if (!$symb) {
                   5190:     $symb=&symbread();
1.620     albertel 5191:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5192:   }
                   5193:   $symb=escape($symb);
                   5194: 
1.620     albertel 5195:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5196:   $namespace=~s/\//\_/g;
                   5197:   $namespace=~s/\W//g;
                   5198: 
1.620     albertel 5199:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5200:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5201:   if ($domain eq 'public' && $stuname eq 'public') {
                   5202:       $stuname=$ENV{'REMOTE_ADDR'};
                   5203:   }
1.1117    foxr     5204:   my $path=LONCAPA::tempdir();
1.168     albertel 5205:   my %hash;
                   5206:   if (tie(%hash,'GDBM_File',
                   5207: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5208: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5209:     foreach my $key (keys(%hash)) {
1.180     albertel 5210:       if ($key=~ /:$symb/) {
1.168     albertel 5211: 	delete($hash{$key});
                   5212:       }
                   5213:     }
                   5214:   }
                   5215: }
                   5216: 
1.167     albertel 5217: sub tmpstore {
1.168     albertel 5218:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5219: 
                   5220:   if (!$symb) {
                   5221:     $symb=&symbread();
1.620     albertel 5222:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5223:   }
                   5224:   $symb=escape($symb);
                   5225: 
                   5226:   if (!$namespace) {
                   5227:     # I don't think we would ever want to store this for a course.
                   5228:     # it seems this will only be used if we don't have a course.
1.620     albertel 5229:     #$namespace=$env{'request.course.id'};
1.168     albertel 5230:     #if (!$namespace) {
1.620     albertel 5231:       $namespace=$env{'request.state'};
1.168     albertel 5232:     #}
                   5233:   }
                   5234:   $namespace=~s/\//\_/g;
                   5235:   $namespace=~s/\W//g;
1.620     albertel 5236:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5237:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5238:   if ($domain eq 'public' && $stuname eq 'public') {
                   5239:       $stuname=$ENV{'REMOTE_ADDR'};
                   5240:   }
1.168     albertel 5241:   my $now=time;
                   5242:   my %hash;
1.1117    foxr     5243:   my $path=LONCAPA::tempdir();
1.168     albertel 5244:   if (tie(%hash,'GDBM_File',
                   5245: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5246: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5247:     $hash{"version:$symb"}++;
                   5248:     my $version=$hash{"version:$symb"};
                   5249:     my $allkeys=''; 
                   5250:     foreach my $key (keys(%$storehash)) {
                   5251:       $allkeys.=$key.':';
1.591     albertel 5252:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5253:     }
                   5254:     $hash{"$version:$symb:timestamp"}=$now;
                   5255:     $allkeys.='timestamp';
                   5256:     $hash{"$version:keys:$symb"}=$allkeys;
                   5257:     if (untie(%hash)) {
                   5258:       return 'ok';
                   5259:     } else {
                   5260:       return "error:$!";
                   5261:     }
                   5262:   } else {
                   5263:     return "error:$!";
                   5264:   }
                   5265: }
1.167     albertel 5266: 
1.168     albertel 5267: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5268: 
1.168     albertel 5269: sub tmprestore {
                   5270:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5271: 
1.168     albertel 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.591     albertel 5279: 
1.620     albertel 5280:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5281:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5282:   if ($domain eq 'public' && $stuname eq 'public') {
                   5283:       $stuname=$ENV{'REMOTE_ADDR'};
                   5284:   }
1.168     albertel 5285:   my %returnhash;
                   5286:   $namespace=~s/\//\_/g;
                   5287:   $namespace=~s/\W//g;
                   5288:   my %hash;
1.1117    foxr     5289:   my $path=LONCAPA::tempdir();
1.168     albertel 5290:   if (tie(%hash,'GDBM_File',
                   5291: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5292: 	  &GDBM_READER(),0640)) {
1.168     albertel 5293:     my $version=$hash{"version:$symb"};
                   5294:     $returnhash{'version'}=$version;
                   5295:     my $scope;
                   5296:     for ($scope=1;$scope<=$version;$scope++) {
                   5297:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5298:       my @keys=split(/:/,$vkeys);
                   5299:       my $key;
                   5300:       $returnhash{"$scope:keys"}=$vkeys;
                   5301:       foreach $key (@keys) {
1.591     albertel 5302: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5303: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5304:       }
                   5305:     }
1.168     albertel 5306:     if (!(untie(%hash))) {
                   5307:       return "error:$!";
                   5308:     }
                   5309:   } else {
                   5310:     return "error:$!";
                   5311:   }
                   5312:   return %returnhash;
1.167     albertel 5313: }
                   5314: 
1.9       www      5315: # ----------------------------------------------------------------------- Store
                   5316: 
                   5317: sub store {
1.1269    raeburn  5318:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5319:     my $home='';
                   5320: 
1.168     albertel 5321:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5322: 
1.213     www      5323:     $symb=&symbclean($symb);
1.122     albertel 5324:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5325: 
1.620     albertel 5326:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5327:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5328: 
                   5329:     &devalidate($symb,$stuname,$domain);
1.109     www      5330: 
                   5331:     $symb=escape($symb);
1.187     www      5332:     if (!$namespace) { 
1.620     albertel 5333:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5334:           return ''; 
                   5335:        } 
                   5336:     }
1.620     albertel 5337:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5338: 
                   5339:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5340:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5341: 
1.12      www      5342:     my $namevalue='';
1.800     albertel 5343:     foreach my $key (keys(%$storehash)) {
                   5344:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5345:     }
1.12      www      5346:     $namevalue=~s/\&$//;
1.187     www      5347:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5348:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5349: }
                   5350: 
1.47      www      5351: # -------------------------------------------------------------- Critical Store
                   5352: 
                   5353: sub cstore {
1.1269    raeburn  5354:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5355:     my $home='';
                   5356: 
1.168     albertel 5357:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5358: 
1.213     www      5359:     $symb=&symbclean($symb);
1.122     albertel 5360:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5361: 
1.620     albertel 5362:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5363:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5364: 
                   5365:     &devalidate($symb,$stuname,$domain);
1.109     www      5366: 
                   5367:     $symb=escape($symb);
1.187     www      5368:     if (!$namespace) { 
1.620     albertel 5369:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5370:           return ''; 
                   5371:        } 
                   5372:     }
1.620     albertel 5373:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5374: 
                   5375:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5376:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5377: 
1.47      www      5378:     my $namevalue='';
1.800     albertel 5379:     foreach my $key (keys(%$storehash)) {
                   5380:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5381:     }
1.47      www      5382:     $namevalue=~s/\&$//;
1.187     www      5383:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5384:     return critical
1.1269    raeburn  5385:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5386: }
                   5387: 
1.9       www      5388: # --------------------------------------------------------------------- Restore
                   5389: 
                   5390: sub restore {
1.124     www      5391:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5392:     my $home='';
                   5393: 
1.168     albertel 5394:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5395: 
1.122     albertel 5396:     if (!$symb) {
1.1224    raeburn  5397:         return if ($namespace eq 'courserequests');
                   5398:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5399:     } else {
1.1224    raeburn  5400:         unless ($namespace eq 'courserequests') {
                   5401:             $symb=&escape(&symbclean($symb));
                   5402:         }
1.122     albertel 5403:     }
1.188     www      5404:     if (!$namespace) { 
1.620     albertel 5405:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5406:           return ''; 
                   5407:        } 
                   5408:     }
1.620     albertel 5409:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5410:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5411:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5412:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5413: 
1.12      www      5414:     my %returnhash=();
1.800     albertel 5415:     foreach my $line (split(/\&/,$answer)) {
                   5416: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5417:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5418:     }
1.75      www      5419:     my $version;
                   5420:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5421:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5422:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5423:        }
1.75      www      5424:     }
1.13      www      5425:     return %returnhash;
1.34      www      5426: }
                   5427: 
                   5428: # ---------------------------------------------------------- Course Description
1.1118    foxr     5429: #
                   5430: #  
1.34      www      5431: 
                   5432: sub coursedescription {
1.731     albertel 5433:     my ($courseid,$args)=@_;
1.34      www      5434:     $courseid=~s/^\///;
1.49      www      5435:     $courseid=~s/\_/\//g;
1.34      www      5436:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5437:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5438:     my $normalid=$cdomain.'_'.$cnum;
                   5439:     # need to always cache even if we get errors otherwise we keep 
                   5440:     # trying and trying and trying to get the course description.
                   5441:     my %envhash=();
                   5442:     my %returnhash=();
1.731     albertel 5443:     
                   5444:     my $expiretime=600;
                   5445:     if ($env{'request.course.id'} eq $normalid) {
                   5446: 	$expiretime=120;
                   5447:     }
                   5448: 
                   5449:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5450:     if (!$args->{'freshen_cache'}
                   5451: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5452: 	foreach my $key (keys(%env)) {
                   5453: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5454: 	    my ($setting) = $1;
                   5455: 	    $returnhash{$setting} = $env{$key};
                   5456: 	}
                   5457: 	return %returnhash;
                   5458:     }
                   5459: 
1.1118    foxr     5460:     # get the data again
                   5461: 
1.731     albertel 5462:     if (!$args->{'one_time'}) {
                   5463: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5464:     }
1.811     albertel 5465: 
1.34      www      5466:     if ($chome ne 'no_host') {
1.302     albertel 5467:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5468:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5469: 	   my $username = $env{'user.name'}; # Defult username
                   5470: 	   if(defined $args->{'user'}) {
                   5471: 	       $username = $args->{'user'};
                   5472: 	   }
1.129     albertel 5473:            $returnhash{'home'}= $chome;
                   5474: 	   $returnhash{'domain'} = $cdomain;
                   5475: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5476:            if (!defined($returnhash{'type'})) {
                   5477:                $returnhash{'type'} = 'Course';
                   5478:            }
1.130     albertel 5479:            while (my ($name,$value) = each %returnhash) {
1.53      www      5480:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5481:            }
1.270     www      5482:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5483:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5484: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5485:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5486:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5487:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5488:        }
                   5489:     }
1.731     albertel 5490:     if (!$args->{'one_time'}) {
1.949     raeburn  5491: 	&appenv(\%envhash);
1.731     albertel 5492:     }
1.302     albertel 5493:     return %returnhash;
1.461     www      5494: }
                   5495: 
1.1080    raeburn  5496: sub update_released_required {
                   5497:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5498:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5499:         $cid = $env{'request.course.id'};
                   5500:         $cdom = $env{'course.'.$cid.'.domain'};
                   5501:         $cnum = $env{'course.'.$cid.'.num'};
                   5502:         $chome = $env{'course.'.$cid.'.home'};
                   5503:     }
                   5504:     if ($needsrelease) {
                   5505:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5506:         my $needsupdate;
                   5507:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5508:             $needsupdate = 1;
                   5509:         } else {
                   5510:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5511:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5512:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5513:                 $needsupdate = 1;
                   5514:             }
                   5515:         }
                   5516:         if ($needsupdate) {
                   5517:             my %needshash = (
                   5518:                              'internal.releaserequired' => $needsrelease,
                   5519:                             );
                   5520:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5521:             if ($putresult eq 'ok') {
                   5522:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5523:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5524:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5525:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5526:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5527:                 }
                   5528:             }
                   5529:         }
                   5530:     }
                   5531:     return;
                   5532: }
                   5533: 
1.461     www      5534: # -------------------------------------------------See if a user is privileged
                   5535: 
                   5536: sub privileged {
1.1219    raeburn  5537:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5538:     my $now = time;
1.1219    raeburn  5539:     my $roles;
                   5540:     if (ref($possroles) eq 'ARRAY') {
                   5541:         $roles = $possroles; 
                   5542:     } else {
                   5543:         $roles = ['dc','su'];
                   5544:     }
                   5545:     if (ref($possdomains) eq 'ARRAY') {
                   5546:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5547:         foreach my $dom (@{$possdomains}) {
                   5548:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5549:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5550:                 foreach my $role (@{$roles}) {
                   5551:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5552:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5553:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5554:                             return 1 unless (($end && $end < $now) ||
                   5555:                                              ($start && $start > $now));
                   5556:                         }
                   5557:                     }
                   5558:                 }
                   5559:             }
                   5560:         }
                   5561:     } else {
                   5562:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5563:         my $now = time;
1.1170    droeschl 5564: 
1.1275    musolffc 5565:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5566:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5567:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5568:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5569:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5570:             }
1.1219    raeburn  5571:         }
                   5572:     }
                   5573:     return 0;
                   5574: }
1.1170    droeschl 5575: 
1.1219    raeburn  5576: sub privileged_by_domain {
                   5577:     my ($domains,$roles) = @_;
                   5578:     my %privileged = ();
                   5579:     my $cachetime = 60*60*24;
                   5580:     my $now = time;
                   5581:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5582:         return %privileged;
                   5583:     }
                   5584:     foreach my $dom (@{$domains}) {
                   5585:         next if (ref($privileged{$dom}) eq 'HASH');
                   5586:         my $needroles;
                   5587:         foreach my $role (@{$roles}) {
                   5588:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5589:             if (defined($cached)) {
                   5590:                 if (ref($result) eq 'HASH') {
                   5591:                     $privileged{$dom}{$role} = $result;
                   5592:                 }
                   5593:             } else {
                   5594:                 $needroles = 1;
                   5595:             }
                   5596:         }
                   5597:         if ($needroles) {
                   5598:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5599:             $privileged{$dom} = {};
                   5600:             foreach my $server (keys(%dompersonnel)) {
                   5601:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5602:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5603:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5604:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5605:                         next if ($end && $end < $now);
                   5606:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5607:                             $dompersonnel{$server}{$item};
                   5608:                     }
                   5609:                 }
                   5610:             }
                   5611:             if (ref($privileged{$dom}) eq 'HASH') {
                   5612:                 foreach my $role (@{$roles}) {
                   5613:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5614:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5615:                     } else {
                   5616:                         my %hash = ();
                   5617:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5618:                     }
                   5619:                 }
                   5620:             }
                   5621:         }
                   5622:     }
                   5623:     return %privileged;
1.9       www      5624: }
1.1       albertel 5625: 
1.103     harris41 5626: # -------------------------------------------------------- Get user privileges
1.11      www      5627: 
                   5628: sub rolesinit {
1.1169    droeschl 5629:     my ($domain, $username) = @_;
                   5630:     my %userroles = ('user.login.time' => time);
                   5631:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5632: 
                   5633:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5634:     # also, blocking can be triggered by an activating timer
                   5635:     # it's saved in the user's %env.
                   5636:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5637:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5638:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5639:         %timerintchk, %timerintenv);
                   5640: 
1.1162    raeburn  5641:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5642:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5643:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5644:     }
1.1169    droeschl 5645: 
1.1162    raeburn  5646:     foreach my $key (keys(%timerinterval)) {
                   5647:         my ($cid,$rest) = split(/\0/,$key);
                   5648:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5649:     }
1.1169    droeschl 5650: 
1.11      www      5651:     my %allroles=();
1.1162    raeburn  5652:     my %allgroups=();
1.11      www      5653: 
1.1274    raeburn  5654:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5655:         my $role = $rolesdump{$area};
                   5656:         $area =~ s/\_\w\w$//;
                   5657: 
                   5658:         my ($trole, $tend, $tstart, $group_privs);
                   5659: 
                   5660:         if ($role =~ /^cr/) {
                   5661:         # Custom role, defined by a user 
                   5662:         # e.g., user.role.cr/msu/smith/mynewrole
                   5663:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5664:                 $trole = $1;
                   5665:                 ($tend, $tstart) = split('_', $2);
                   5666:             } else {
                   5667:                 $trole = $role;
                   5668:             }
                   5669:         } elsif ($role =~ m|^gr/|) {
                   5670:         # Role of member in a group, defined within a course/community
                   5671:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5672:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5673:             next if $tstart eq '-1';
                   5674:             ($trole, $group_privs) = split(/\//, $trole);
                   5675:             $group_privs = &unescape($group_privs);
                   5676:         } else {
                   5677:         # Just a normal role, defined in roles.tab
                   5678:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5679:         }
                   5680: 
                   5681:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5682:                  $username);
                   5683:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5684: 
                   5685:         # role expired or not available yet?
                   5686:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5687:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5688: 
                   5689:         next if $area eq '' or $trole eq '';
                   5690: 
                   5691:         my $spec = "$trole.$area";
                   5692:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5693: 
                   5694:         if ($trole =~ /^cr\//) {
                   5695:         # Custom role, defined by a user
                   5696:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5697:         } elsif ($trole eq 'gr') {
                   5698:         # Role of a member in a group, defined within a course/community
                   5699:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5700:             next;
                   5701:         } else {
                   5702:         # Normal role, defined in roles.tab
                   5703:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5704:         }
                   5705: 
                   5706:         my $cid = $tdomain.'_'.$trest;
                   5707:         unless ($firstaccchk{$cid}) {
                   5708:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5709:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5710:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5711:                         $coursetimerstarts{$cid}{$item}; 
                   5712:                 }
                   5713:             }
                   5714:             $firstaccchk{$cid} = 1;
                   5715:         }
                   5716:         unless ($timerintchk{$cid}) {
                   5717:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5718:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5719:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5720:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5721:                 }
1.12      www      5722:             }
1.1169    droeschl 5723:             $timerintchk{$cid} = 1;
1.191     harris41 5724:         }
1.11      www      5725:     }
1.1169    droeschl 5726: 
                   5727:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   5728:         \%allroles, \%allgroups);
                   5729:     $env{'user.adv'} = $userroles{'user.adv'};
                   5730: 
1.1162    raeburn  5731:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5732: }
                   5733: 
1.567     raeburn  5734: sub set_arearole {
1.1215    raeburn  5735:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5736:     unless ($nolog) {
1.567     raeburn  5737: # log the associated role with the area
1.1215    raeburn  5738:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5739:     }
1.743     albertel 5740:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5741: }
                   5742: 
                   5743: sub custom_roleprivs {
                   5744:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5745:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5746:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5747:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5748:         my ($rdummy,$roledef)=
                   5749:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5750:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5751:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5752:             if (defined($syspriv)) {
1.1043    raeburn  5753:                 if ($trest =~ /^$match_community$/) {
                   5754:                     $syspriv =~ s/bre\&S//; 
                   5755:                 }
1.567     raeburn  5756:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5757:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5758:             }
                   5759:             if ($tdomain ne '') {
                   5760:                 if (defined($dompriv)) {
                   5761:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5762:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5763:                 }
                   5764:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332  ! raeburn  5765:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
        !          5766:                         my $rolename = $1;
        !          5767:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
        !          5768:                     }
1.567     raeburn  5769:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5770:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5771:                 }
                   5772:             }
                   5773:         }
                   5774:     }
                   5775: }
                   5776: 
1.1332  ! raeburn  5777: sub course_adhocrole_privs {
        !          5778:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
        !          5779:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
        !          5780:     if ($overrides{"internal.adhocpriv.$rolename"}) {
        !          5781:         my (%currprivs,%storeprivs);
        !          5782:         foreach my $item (split(/:/,$coursepriv)) {
        !          5783:             my ($priv,$restrict) = split(/\&/,$item);
        !          5784:             $currprivs{$priv} = $restrict;
        !          5785:         }
        !          5786:         my (%possadd,%possremove,%full);
        !          5787:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
        !          5788:             my ($priv,$restrict)=split(/\&/,$item);
        !          5789:             $full{$priv} = $restrict;
        !          5790:         }
        !          5791:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
        !          5792:              next if ($item eq '');
        !          5793:              my ($rule,$rest) = split(/=/,$item);
        !          5794:              next unless (($rule eq 'off') || ($rule eq 'on'));
        !          5795:              foreach my $priv (split(/:/,$rest)) {
        !          5796:                  if ($priv ne '') {
        !          5797:                      if ($rule eq 'off') {
        !          5798:                          $possremove{$priv} = 1;
        !          5799:                      } else {
        !          5800:                          $possadd{$priv} = 1;
        !          5801:                      }
        !          5802:                  }
        !          5803:              }
        !          5804:          }
        !          5805:          foreach my $priv (sort(keys(%full))) {
        !          5806:              if (exists($currprivs{$priv})) {
        !          5807:                  unless (exists($possremove{$priv})) {
        !          5808:                      $storeprivs{$priv} = $currprivs{$priv};
        !          5809:                  }
        !          5810:              } elsif (exists($possadd{$priv})) {
        !          5811:                  $storeprivs{$priv} = $full{$priv};
        !          5812:              }
        !          5813:          }
        !          5814:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
        !          5815:      }
        !          5816:      return $coursepriv;
        !          5817: }
        !          5818: 
1.678     raeburn  5819: sub group_roleprivs {
                   5820:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5821:     my $access = 1;
                   5822:     my $now = time;
                   5823:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5824:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5825:     if ($access) {
1.811     albertel 5826:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5827:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5828:     }
                   5829: }
1.567     raeburn  5830: 
                   5831: sub standard_roleprivs {
                   5832:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5833:     if (defined($pr{$trole.':s'})) {
                   5834:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5835:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5836:     }
                   5837:     if ($tdomain ne '') {
                   5838:         if (defined($pr{$trole.':d'})) {
                   5839:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5840:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5841:         }
                   5842:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5843:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5844:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5845:         }
                   5846:     }
                   5847: }
                   5848: 
                   5849: sub set_userprivs {
1.1064    raeburn  5850:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5851:     my $author=0;
                   5852:     my $adv=0;
1.678     raeburn  5853:     my %grouproles = ();
                   5854:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5855:         my @groupkeys; 
1.1000    raeburn  5856:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5857:             push(@groupkeys,$role);
                   5858:         }
                   5859:         if (ref($groups_roles) eq 'HASH') {
                   5860:             foreach my $key (keys(%{$groups_roles})) {
                   5861:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5862:                     push(@groupkeys,$key);
                   5863:                 }
                   5864:             }
                   5865:         }
                   5866:         if (@groupkeys > 0) {
                   5867:             foreach my $role (@groupkeys) {
                   5868:                 my ($trole,$area,$sec,$extendedarea);
                   5869:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5870:                     $trole = $1;
                   5871:                     $area = $2;
                   5872:                     $sec = $3;
                   5873:                     $extendedarea = $area.$sec;
                   5874:                     if (exists($$allgroups{$area})) {
                   5875:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5876:                             my $spec = $trole.'.'.$extendedarea;
                   5877:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5878:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5879:                         }
1.678     raeburn  5880:                     }
                   5881:                 }
                   5882:             }
                   5883:         }
                   5884:     }
1.800     albertel 5885:     foreach my $group (keys(%grouproles)) {
                   5886:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5887:     }
1.800     albertel 5888:     foreach my $role (keys(%{$allroles})) {
                   5889:         my %thesepriv;
1.941     raeburn  5890:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5891:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5892:             if ($item ne '') {
                   5893:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5894:                 if ($restrictions eq '') {
                   5895:                     $thesepriv{$privilege}='F';
                   5896:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5897:                     $thesepriv{$privilege}.=$restrictions;
                   5898:                 }
                   5899:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   5900:             }
                   5901:         }
                   5902:         my $thesestr='';
1.1104    raeburn  5903:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 5904: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   5905: 	}
                   5906:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  5907:     }
                   5908:     return ($author,$adv);
                   5909: }
                   5910: 
1.994     raeburn  5911: sub role_status {
1.1104    raeburn  5912:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  5913:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  5914:         my ($one,$two) = split(m{\./},$rolekey,2);
                   5915:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  5916:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  5917:             $$where = '/'.$two;
1.994     raeburn  5918:             $$trolecode=$$role.'.'.$$where;
                   5919:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   5920:             $$tstatus='is';
1.1104    raeburn  5921:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  5922:                 $$tstatus='future';
1.1034    raeburn  5923:                 if ($$tstart<$now) {
                   5924:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  5925:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  5926:                             my (%allroles,%allgroups,$group_privs,
                   5927:                                 %groups_roles,@rolecodes);
1.1002    raeburn  5928:                             my %userroles = (
                   5929:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   5930:                             );
1.1064    raeburn  5931:                             @rolecodes = ('cm'); 
1.1002    raeburn  5932:                             my $spec=$$role.'.'.$$where;
                   5933:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   5934:                             if ($$role =~ /^cr\//) {
                   5935:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  5936:                                 push(@rolecodes,'cr');
1.1002    raeburn  5937:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  5938:                                 push(@rolecodes,$$role);
1.1002    raeburn  5939:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   5940:                                                     $env{'user.name'});
1.1064    raeburn  5941:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  5942:                                 (undef,my $group_privs) = split(/\//,$trole);
                   5943:                                 $group_privs = &unescape($group_privs);
                   5944:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  5945:                                 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  5946:                                 &get_groups_roles($tdomain,$trest,
                   5947:                                                   \%course_roles,\@rolecodes,
                   5948:                                                   \%groups_roles);
1.1002    raeburn  5949:                             } else {
1.1064    raeburn  5950:                                 push(@rolecodes,$$role);
1.1002    raeburn  5951:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   5952:                             }
1.1064    raeburn  5953:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   5954:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  5955:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   5956:                         }
                   5957:                     }
1.1034    raeburn  5958:                     $$tstatus = 'is';
1.1002    raeburn  5959:                 }
1.994     raeburn  5960:             }
                   5961:             if ($$tend) {
1.1104    raeburn  5962:                 if ($$tend<$update) {
1.994     raeburn  5963:                     $$tstatus='expired';
                   5964:                 } elsif ($$tend<$now) {
                   5965:                     $$tstatus='will_not';
                   5966:                 }
                   5967:             }
                   5968:         }
                   5969:     }
                   5970: }
                   5971: 
1.1104    raeburn  5972: sub get_groups_roles {
                   5973:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   5974:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   5975:                   (ref($rolecodes) eq 'ARRAY') && 
                   5976:                   (ref($groups_roles) eq 'HASH')); 
                   5977:     if (keys(%{$cdom_courseroles}) > 0) {
                   5978:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   5979:         if ($cdom ne '' && $cnum ne '') {
                   5980:             foreach my $key (keys(%{$cdom_courseroles})) {
                   5981:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   5982:                     my $crsrole = $1;
                   5983:                     my $crssec = $2;
                   5984:                     if ($crsrole =~ /^cr/) {
                   5985:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   5986:                             push(@{$rolecodes},'cr');
                   5987:                         }
                   5988:                     } else {
                   5989:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   5990:                             push(@{$rolecodes},$crsrole);
                   5991:                         }
                   5992:                     }
                   5993:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   5994:                     if ($crssec ne '') {
                   5995:                         $rolekey .= "/$crssec";
                   5996:                     }
                   5997:                     $rolekey .= './';
                   5998:                     $groups_roles->{$rolekey} = $rolecodes;
                   5999:                 }
                   6000:             }
                   6001:         }
                   6002:     }
                   6003:     return;
                   6004: }
                   6005: 
                   6006: sub delete_env_groupprivs {
                   6007:     my ($where,$courseroles,$possroles) = @_;
                   6008:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6009:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6010:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6011:         %{$courseroles->{$udom}} =
                   6012:             &get_my_roles('','','userroles',['active'],
                   6013:                           $possroles,[$udom],1);
                   6014:     }
                   6015:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6016:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6017:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6018:             my $area = '/'.$cdom.'/'.$cnum;
                   6019:             my $privkey = "user.priv.$crsrole.$area";
                   6020:             if ($crssec ne '') {
                   6021:                 $privkey .= '/'.$crssec;
                   6022:             }
                   6023:             $privkey .= ".$area/$group";
                   6024:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6025:         }
                   6026:     }
                   6027:     return;
                   6028: }
                   6029: 
1.994     raeburn  6030: sub check_adhoc_privs {
1.1329    raeburn  6031:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6032:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6033:     if ($sec) {
                   6034:         $cckey .= '/'.$sec;
                   6035:     } 
1.1185    raeburn  6036:     my $setprivs;
1.994     raeburn  6037:     if ($env{$cckey}) {
                   6038:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6039:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6040:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6041:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6042:             $setprivs = 1;
1.994     raeburn  6043:         }
                   6044:     } else {
1.1330    raeburn  6045:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6046:         $setprivs = 1;
1.994     raeburn  6047:     }
1.1185    raeburn  6048:     return $setprivs;
1.994     raeburn  6049: }
                   6050: 
                   6051: sub set_adhoc_privileges {
1.1326    raeburn  6052: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6053:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6054:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6055:     if ($sec ne '') {
                   6056:         $area .= '/'.$sec;
                   6057:     }
1.994     raeburn  6058:     my $spec = $role.'.'.$area;
                   6059:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6060:                                   $env{'user.name'},1);
1.1326    raeburn  6061:     my %rolehash = ();
1.1332  ! raeburn  6062:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
        !          6063:         my $rolename = $1;
1.1326    raeburn  6064:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332  ! raeburn  6065:         my %domdef = &get_domain_defaults($dcdom);
        !          6066:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
        !          6067:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
        !          6068:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
        !          6069:             }
        !          6070:         }
1.1326    raeburn  6071:     } else {
                   6072:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6073:     }
                   6074:     my ($author,$adv)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6075:     &appenv(\%userroles,[$role,'cm']);
                   6076:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  6077:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6078:         &appenv( {'request.role'        => $spec,
                   6079:                   'request.role.domain' => $dcdom,
1.1332  ! raeburn  6080:                   'request.course.sec'  => $sec,
1.1088    raeburn  6081:                  }
                   6082:                );
                   6083:         my $tadv=0;
                   6084:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6085:         &appenv({'request.role.adv'    => $tadv});
                   6086:     }
1.994     raeburn  6087: }
                   6088: 
1.12      www      6089: # --------------------------------------------------------------- get interface
                   6090: 
                   6091: sub get {
1.131     albertel 6092:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6093:    my $items='';
1.800     albertel 6094:    foreach my $item (@$storearr) {
                   6095:        $items.=&escape($item).'&';
1.191     harris41 6096:    }
1.12      www      6097:    $items=~s/\&$//;
1.620     albertel 6098:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6099:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6100:    my $uhome=&homeserver($uname,$udomain);
                   6101: 
1.133     albertel 6102:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6103:    my @pairs=split(/\&/,$rep);
1.273     albertel 6104:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6105:      return @pairs;
                   6106:    }
1.15      www      6107:    my %returnhash=();
1.42      www      6108:    my $i=0;
1.800     albertel 6109:    foreach my $item (@$storearr) {
                   6110:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6111:       $i++;
1.191     harris41 6112:    }
1.15      www      6113:    return %returnhash;
1.27      www      6114: }
                   6115: 
                   6116: # --------------------------------------------------------------- del interface
                   6117: 
                   6118: sub del {
1.133     albertel 6119:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6120:    my $items='';
1.800     albertel 6121:    foreach my $item (@$storearr) {
                   6122:        $items.=&escape($item).'&';
1.191     harris41 6123:    }
1.984     neumanie 6124: 
1.27      www      6125:    $items=~s/\&$//;
1.620     albertel 6126:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6127:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6128:    my $uhome=&homeserver($uname,$udomain);
                   6129:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6130: }
                   6131: 
                   6132: # -------------------------------------------------------------- dump interface
                   6133: 
1.1180    droeschl 6134: sub unserialize {
                   6135:     my ($rep, $escapedkeys) = @_;
                   6136: 
                   6137:     return {} if $rep =~ /^error/;
                   6138: 
                   6139:     my %returnhash=();
1.1252    raeburn  6140: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6141: 	    my ($key, $value) = split(/=/, $item, 2);
                   6142: 	    $key = unescape($key) unless $escapedkeys;
                   6143: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6144: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6145: 	}
                   6146:     #return %returnhash;
                   6147:     return \%returnhash;
                   6148: }        
                   6149: 
                   6150: # see Lond::dump_with_regexp
                   6151: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6152: sub dump {
1.1180    droeschl 6153:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6154:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6155:     if (!$uname) { $uname=$env{'user.name'}; }
                   6156:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6157: 
1.1266    raeburn  6158:     if ($regexp) {
                   6159:         $regexp=&escape($regexp);
                   6160:     } else {
                   6161:         $regexp='.';
                   6162:     }
1.1180    droeschl 6163:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6164:         # user is hosted on this machine
1.1266    raeburn  6165:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6166:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6167:         return %{unserialize($reply, $escapedkeys)};
                   6168:     }
1.1166    raeburn  6169:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6170:     my @pairs=split(/\&/,$rep);
                   6171:     my %returnhash=();
1.1098    foxr     6172:     if (!($rep =~ /^error/ )) {
                   6173: 	foreach my $item (@pairs) {
                   6174: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6175:         $key = unescape($key) unless $escapedkeys;
                   6176:         #$key = &unescape($key);
1.1098    foxr     6177: 	    next if ($key =~ /^error: 2 /);
                   6178: 	    $returnhash{$key}=&thaw_unescape($value);
                   6179: 	}
1.755     albertel 6180:     }
                   6181:     return %returnhash;
1.407     www      6182: }
                   6183: 
1.1098    foxr     6184: 
1.717     albertel 6185: # --------------------------------------------------------- dumpstore interface
                   6186: 
                   6187: sub dumpstore {
                   6188:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6189:    # same as dump but keys must be escaped. They may contain colon separated
                   6190:    # lists of values that may themself contain colons (e.g. symbs).
                   6191:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6192: }
                   6193: 
1.407     www      6194: # -------------------------------------------------------------- keys interface
                   6195: 
                   6196: sub getkeys {
                   6197:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6198:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6199:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6200:    my $uhome=&homeserver($uname,$udomain);
                   6201:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6202:    my @keyarray=();
1.800     albertel 6203:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6204:       next if ($key =~ /^error: 2 /);
1.800     albertel 6205:       push(@keyarray,&unescape($key));
1.407     www      6206:    }
                   6207:    return @keyarray;
1.318     matthew  6208: }
                   6209: 
1.319     matthew  6210: # --------------------------------------------------------------- currentdump
                   6211: sub currentdump {
1.328     matthew  6212:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6213:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6214:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6215:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6216:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6217:    my $rep;
                   6218: 
                   6219:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6220:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6221:                    $courseid)));
                   6222:    } else {
                   6223:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6224:    }
                   6225: 
1.318     matthew  6226:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6227:    #
1.318     matthew  6228:    my %returnhash=();
1.319     matthew  6229:    #
                   6230:    if ($rep eq "unknown_cmd") { 
                   6231:        # an old lond will not know currentdump
                   6232:        # Do a dump and make it look like a currentdump
1.822     albertel 6233:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6234:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6235:        my %hash = @tmp;
                   6236:        @tmp=();
1.424     matthew  6237:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6238:    } else {
                   6239:        my @pairs=split(/\&/,$rep);
1.800     albertel 6240:        foreach my $pair (@pairs) {
                   6241:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6242:            my ($symb,$param) = split(/:/,$key);
                   6243:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6244:                                                         &thaw_unescape($value);
1.319     matthew  6245:        }
1.191     harris41 6246:    }
1.12      www      6247:    return %returnhash;
1.424     matthew  6248: }
                   6249: 
                   6250: sub convert_dump_to_currentdump{
                   6251:     my %hash = %{shift()};
                   6252:     my %returnhash;
                   6253:     # Code ripped from lond, essentially.  The only difference
                   6254:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6255:     # we might run in to problems with parameter names =~ /^v\./
                   6256:     while (my ($key,$value) = each(%hash)) {
                   6257:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6258: 	$symb  = &unescape($symb);
                   6259: 	$param = &unescape($param);
1.424     matthew  6260:         next if ($v eq 'version' || $symb eq 'keys');
                   6261:         next if (exists($returnhash{$symb}) &&
                   6262:                  exists($returnhash{$symb}->{$param}) &&
                   6263:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6264:         $returnhash{$symb}->{$param}=$value;
                   6265:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6266:     }
                   6267:     #
                   6268:     # Remove all of the keys in the hashes which keep track of
                   6269:     # the version of the parameter.
                   6270:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6271:         # use a foreach because we are going to delete from the hash.
                   6272:         foreach my $key (keys(%$param_hash)) {
                   6273:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6274:         }
                   6275:     }
                   6276:     return \%returnhash;
1.12      www      6277: }
                   6278: 
1.627     albertel 6279: # ------------------------------------------------------ critical inc interface
                   6280: 
                   6281: sub cinc {
                   6282:     return &inc(@_,'critical');
                   6283: }
                   6284: 
1.449     matthew  6285: # --------------------------------------------------------------- inc interface
                   6286: 
                   6287: sub inc {
1.627     albertel 6288:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6289:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6290:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6291:     my $uhome=&homeserver($uname,$udomain);
                   6292:     my $items='';
                   6293:     if (! ref($store)) {
                   6294:         # got a single value, so use that instead
                   6295:         $items = &escape($store).'=&';
                   6296:     } elsif (ref($store) eq 'SCALAR') {
                   6297:         $items = &escape($$store).'=&';        
                   6298:     } elsif (ref($store) eq 'ARRAY') {
                   6299:         $items = join('=&',map {&escape($_);} @{$store});
                   6300:     } elsif (ref($store) eq 'HASH') {
                   6301:         while (my($key,$value) = each(%{$store})) {
                   6302:             $items.= &escape($key).'='.&escape($value).'&';
                   6303:         }
                   6304:     }
                   6305:     $items=~s/\&$//;
1.627     albertel 6306:     if ($critical) {
                   6307: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6308:     } else {
                   6309: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6310:     }
1.449     matthew  6311: }
                   6312: 
1.12      www      6313: # --------------------------------------------------------------- put interface
                   6314: 
                   6315: sub put {
1.134     albertel 6316:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6317:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6318:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6319:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6320:    my $items='';
1.800     albertel 6321:    foreach my $item (keys(%$storehash)) {
                   6322:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6323:    }
1.12      www      6324:    $items=~s/\&$//;
1.134     albertel 6325:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6326: }
                   6327: 
1.631     albertel 6328: # ------------------------------------------------------------ newput interface
                   6329: 
                   6330: sub newput {
                   6331:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6332:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6333:    if (!$uname) { $uname=$env{'user.name'}; }
                   6334:    my $uhome=&homeserver($uname,$udomain);
                   6335:    my $items='';
                   6336:    foreach my $key (keys(%$storehash)) {
                   6337:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6338:    }
                   6339:    $items=~s/\&$//;
                   6340:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6341: }
                   6342: 
                   6343: # ---------------------------------------------------------  putstore interface
                   6344: 
1.524     raeburn  6345: sub putstore {
1.1269    raeburn  6346:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6347:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6348:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6349:    my $uhome=&homeserver($uname,$udomain);
                   6350:    my $items='';
1.715     albertel 6351:    foreach my $key (keys(%$storehash)) {
                   6352:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6353:    }
1.715     albertel 6354:    $items=~s/\&$//;
1.716     albertel 6355:    my $esc_symb=&escape($symb);
                   6356:    my $esc_v=&escape($version);
1.715     albertel 6357:    my $reply =
1.716     albertel 6358:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6359: 	      $uhome);
1.1269    raeburn  6360:    if (($tolog) && ($reply eq 'ok')) {
                   6361:        my $namevalue='';
                   6362:        foreach my $key (keys(%{$storehash})) {
                   6363:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6364:        }
                   6365:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6366:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6367:                      '&version='.$esc_v.
                   6368:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6369:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6370:    }
1.715     albertel 6371:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6372:        # gfall back to way things use to be done
1.715     albertel 6373:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6374: 			    $uname);
1.524     raeburn  6375:    }
1.715     albertel 6376:    return $reply;
                   6377: }
                   6378: 
                   6379: sub old_putstore {
1.716     albertel 6380:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6381:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6382:     if (!$uname) { $uname=$env{'user.name'}; }
                   6383:     my $uhome=&homeserver($uname,$udomain);
                   6384:     my %newstorehash;
1.800     albertel 6385:     foreach my $item (keys(%$storehash)) {
                   6386: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6387: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6388:     }
                   6389:     my $items='';
                   6390:     my %allitems = ();
1.800     albertel 6391:     foreach my $item (keys(%newstorehash)) {
                   6392: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6393: 	    my $key = $1.':keys:'.$2;
                   6394: 	    $allitems{$key} .= $3.':';
                   6395: 	}
1.800     albertel 6396: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6397:     }
1.800     albertel 6398:     foreach my $item (keys(%allitems)) {
                   6399: 	$allitems{$item} =~ s/\:$//;
                   6400: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6401:     }
                   6402:     $items=~s/\&$//;
                   6403:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6404: }
                   6405: 
1.47      www      6406: # ------------------------------------------------------ critical put interface
                   6407: 
                   6408: sub cput {
1.134     albertel 6409:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6410:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6411:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6412:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6413:    my $items='';
1.800     albertel 6414:    foreach my $item (keys(%$storehash)) {
                   6415:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6416:    }
1.47      www      6417:    $items=~s/\&$//;
1.134     albertel 6418:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6419: }
                   6420: 
                   6421: # -------------------------------------------------------------- eget interface
                   6422: 
                   6423: sub eget {
1.133     albertel 6424:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6425:    my $items='';
1.800     albertel 6426:    foreach my $item (@$storearr) {
                   6427:        $items.=&escape($item).'&';
1.191     harris41 6428:    }
1.12      www      6429:    $items=~s/\&$//;
1.620     albertel 6430:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6431:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6432:    my $uhome=&homeserver($uname,$udomain);
                   6433:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6434:    my @pairs=split(/\&/,$rep);
                   6435:    my %returnhash=();
1.42      www      6436:    my $i=0;
1.800     albertel 6437:    foreach my $item (@$storearr) {
                   6438:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6439:       $i++;
1.191     harris41 6440:    }
1.12      www      6441:    return %returnhash;
                   6442: }
                   6443: 
1.667     albertel 6444: # ------------------------------------------------------------ tmpput interface
                   6445: sub tmpput {
1.802     raeburn  6446:     my ($storehash,$server,$context)=@_;
1.667     albertel 6447:     my $items='';
1.800     albertel 6448:     foreach my $item (keys(%$storehash)) {
                   6449: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6450:     }
                   6451:     $items=~s/\&$//;
1.802     raeburn  6452:     if (defined($context)) {
                   6453:         $items .= ':'.&escape($context);
                   6454:     }
1.667     albertel 6455:     return &reply("tmpput:$items",$server);
                   6456: }
                   6457: 
                   6458: # ------------------------------------------------------------ tmpget interface
                   6459: sub tmpget {
1.688     albertel 6460:     my ($token,$server)=@_;
                   6461:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6462:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6463:     my %returnhash;
1.1328    raeburn  6464:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6465:         return %returnhash;
                   6466:     }
1.667     albertel 6467:     foreach my $item (split(/\&/,$rep)) {
                   6468: 	my ($key,$value)=split(/=/,$item);
                   6469: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6470:     }
                   6471:     return %returnhash;
                   6472: }
                   6473: 
1.1113    raeburn  6474: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6475: sub tmpdel {
                   6476:     my ($token,$server)=@_;
                   6477:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6478:     return &reply("tmpdel:$token",$server);
                   6479: }
                   6480: 
1.1198    raeburn  6481: # ------------------------------------------------------------ get_timebased_id 
                   6482: 
                   6483: sub get_timebased_id {
                   6484:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6485:         $maxtries) = @_;
                   6486:     my ($newid,$error,$dellock);
                   6487:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6488:         return ('','ok','invalid call to get suffix');
                   6489:     }
                   6490: 
                   6491: # set defaults for any optional args for which values were not supplied
                   6492:     if ($who eq '') {
                   6493:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6494:     }
                   6495:     if (!$locktries) {
                   6496:         $locktries = 3;
                   6497:     }
                   6498:     if (!$maxtries) {
                   6499:         $maxtries = 10;
                   6500:     }
                   6501:     
                   6502:     if (($cdom eq '') || ($cnum eq '')) {
                   6503:         if ($env{'request.course.id'}) {
                   6504:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6505:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6506:         }
                   6507:         if (($cdom eq '') || ($cnum eq '')) {
                   6508:             return ('','ok','call to get suffix not in course context');
                   6509:         }
                   6510:     }
                   6511: 
                   6512: # construct locking item
                   6513:     my $lockhash = {
                   6514:                       $prefix."\0".'locked_'.$keyid => $who,
                   6515:                    };
                   6516:     my $tries = 0;
                   6517: 
                   6518: # attempt to get lock on nohist_$namespace file
                   6519:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6520:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6521:         $tries ++;
                   6522:         sleep 1;
                   6523:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6524:     }
                   6525: 
                   6526: # attempt to get unique identifier, based on current timestamp
                   6527:     if ($gotlock eq 'ok') {
                   6528:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6529:         my $id = time;
                   6530:         $newid = $id;
1.1268    raeburn  6531:         if ($idtype eq 'addcode') {
                   6532:             $newid .= &sixnum_code();
                   6533:         }
1.1198    raeburn  6534:         my $idtries = 0;
                   6535:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6536:             if ($idtype eq 'concat') {
                   6537:                 $newid = $id.$idtries;
1.1268    raeburn  6538:             } elsif ($idtype eq 'addcode') {
                   6539:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6540:             } else {
                   6541:                 $newid ++;
                   6542:             }
                   6543:             $idtries ++;
                   6544:         }
                   6545:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6546:             my %new_item =  (
                   6547:                               $prefix."\0".$newid => $who,
                   6548:                             );
                   6549:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6550:                                                  $cdom,$cnum);
                   6551:             if ($putresult ne 'ok') {
                   6552:                 undef($newid);
                   6553:                 $error = 'error saving new item: '.$putresult;
                   6554:             }
                   6555:         } else {
1.1268    raeburn  6556:              undef($newid);
1.1198    raeburn  6557:              $error = ('error: no unique suffix available for the new item ');
                   6558:         }
                   6559: #  remove lock
                   6560:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6561:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6562:     } else {
                   6563:         $error = "error: could not obtain lockfile\n";
                   6564:         $dellock = 'ok';
1.1276    raeburn  6565:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6566:             $dellock = 'nolock';
                   6567:         }
1.1198    raeburn  6568:     }
                   6569:     return ($newid,$dellock,$error);
                   6570: }
                   6571: 
1.1268    raeburn  6572: sub sixnum_code {
                   6573:     my $code;
                   6574:     for (0..6) {
                   6575:         $code .= int( rand(9) );
                   6576:     }
                   6577:     return $code;
                   6578: }
                   6579: 
1.765     albertel 6580: # -------------------------------------------------- portfolio access checking
                   6581: 
                   6582: sub portfolio_access {
1.1270    raeburn  6583:     my ($requrl,$clientip) = @_;
1.765     albertel 6584:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6585:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6586:     if ($result) {
                   6587:         my %setters;
                   6588:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6589:             my ($startblock,$endblock) =
                   6590:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6591:             if ($startblock && $endblock) {
                   6592:                 return 'B';
                   6593:             }
                   6594:         } else {
                   6595:             my ($startblock,$endblock) =
                   6596:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6597:             if ($startblock && $endblock) {
                   6598:                 return 'B';
                   6599:             }
                   6600:         }
                   6601:     }
1.765     albertel 6602:     if ($result eq 'ok') {
1.766     albertel 6603:        return 'F';
1.765     albertel 6604:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6605:        return 'A';
1.765     albertel 6606:     }
1.766     albertel 6607:     return '';
1.765     albertel 6608: }
                   6609: 
                   6610: sub get_portfolio_access {
1.1270    raeburn  6611:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6612: 
                   6613:     if (!ref($access_hash)) {
                   6614: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6615: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6616: 						   $file_name);
                   6617: 	$access_hash = $access_controls{$file_name};
                   6618:     }
                   6619: 
1.1270    raeburn  6620:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6621:     my $now = time;
                   6622:     if (ref($access_hash) eq 'HASH') {
                   6623:         foreach my $key (keys(%{$access_hash})) {
                   6624:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6625:             if ($start > $now) {
                   6626:                 next;
                   6627:             }
                   6628:             if ($end && $end<$now) {
                   6629:                 next;
                   6630:             }
                   6631:             if ($scope eq 'public') {
                   6632:                 $public = $key;
                   6633:                 last;
                   6634:             } elsif ($scope eq 'guest') {
                   6635:                 $guest = $key;
                   6636:             } elsif ($scope eq 'domains') {
                   6637:                 push(@domains,$key);
                   6638:             } elsif ($scope eq 'users') {
                   6639:                 push(@users,$key);
                   6640:             } elsif ($scope eq 'course') {
                   6641:                 push(@courses,$key);
                   6642:             } elsif ($scope eq 'group') {
                   6643:                 push(@groups,$key);
1.1270    raeburn  6644:             } elsif ($scope eq 'ip') {
                   6645:                 push(@ips,$key);
1.765     albertel 6646:             }
                   6647:         }
                   6648:         if ($public) {
                   6649:             return 'ok';
1.1270    raeburn  6650:         } elsif (@ips > 0) {
                   6651:             my $allowed;
                   6652:             foreach my $ipkey (@ips) {
                   6653:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6654:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6655:                         $allowed = 1;
                   6656:                         last; 
                   6657:                     }
                   6658:                 }
                   6659:             }
                   6660:             if ($allowed) {
                   6661:                 return 'ok';
                   6662:             }
1.765     albertel 6663:         }
                   6664:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6665:             if ($guest) {
                   6666:                 return $guest;
                   6667:             }
                   6668:         } else {
                   6669:             if (@domains > 0) {
                   6670:                 foreach my $domkey (@domains) {
                   6671:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6672:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6673:                             return 'ok';
                   6674:                         }
                   6675:                     }
                   6676:                 }
                   6677:             }
                   6678:             if (@users > 0) {
                   6679:                 foreach my $userkey (@users) {
1.865     raeburn  6680:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6681:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6682:                             if (ref($item) eq 'HASH') {
                   6683:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6684:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6685:                                     return 'ok';
                   6686:                                 }
                   6687:                             }
                   6688:                         }
                   6689:                     } 
1.765     albertel 6690:                 }
                   6691:             }
                   6692:             my %roleshash;
                   6693:             my @courses_and_groups = @courses;
                   6694:             push(@courses_and_groups,@groups); 
                   6695:             if (@courses_and_groups > 0) {
                   6696:                 my (%allgroups,%allroles); 
                   6697:                 my ($start,$end,$role,$sec,$group);
                   6698:                 foreach my $envkey (%env) {
1.1060    raeburn  6699:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6700:                         my $cid = $2.'_'.$3; 
                   6701:                         if ($1 eq 'gr') {
                   6702:                             $group = $4;
                   6703:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6704:                         } else {
                   6705:                             if ($4 eq '') {
                   6706:                                 $sec = 'none';
                   6707:                             } else {
                   6708:                                 $sec = $4;
                   6709:                             }
                   6710:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6711:                         }
1.811     albertel 6712:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6713:                         my $cid = $2.'_'.$3;
                   6714:                         if ($4 eq '') {
                   6715:                             $sec = 'none';
                   6716:                         } else {
                   6717:                             $sec = $4;
                   6718:                         }
                   6719:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6720:                     }
                   6721:                 }
                   6722:                 if (keys(%allroles) == 0) {
                   6723:                     return;
                   6724:                 }
                   6725:                 foreach my $key (@courses_and_groups) {
                   6726:                     my %content = %{$$access_hash{$key}};
                   6727:                     my $cnum = $content{'number'};
                   6728:                     my $cdom = $content{'domain'};
                   6729:                     my $cid = $cdom.'_'.$cnum;
                   6730:                     if (!exists($allroles{$cid})) {
                   6731:                         next;
                   6732:                     }    
                   6733:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6734:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6735:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6736:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6737:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6738:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6739:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6740:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6741:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6742:                                         if (grep/^all$/,@sections) {
                   6743:                                             return 'ok';
                   6744:                                         } else {
                   6745:                                             if (grep/^$sec$/,@sections) {
                   6746:                                                 return 'ok';
                   6747:                                             }
                   6748:                                         }
                   6749:                                     }
                   6750:                                 }
                   6751:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6752:                                     if (grep/^none$/,@groups) {
                   6753:                                         return 'ok';
                   6754:                                     }
                   6755:                                 } else {
                   6756:                                     if (grep/^all$/,@groups) {
                   6757:                                         return 'ok';
                   6758:                                     } 
                   6759:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6760:                                         if (grep/^$group$/,@groups) {
                   6761:                                             return 'ok';
                   6762:                                         }
                   6763:                                     }
                   6764:                                 } 
                   6765:                             }
                   6766:                         }
                   6767:                     }
                   6768:                 }
                   6769:             }
                   6770:             if ($guest) {
                   6771:                 return $guest;
                   6772:             }
                   6773:         }
                   6774:     }
                   6775:     return;
                   6776: }
                   6777: 
                   6778: sub course_group_datechecker {
                   6779:     my ($dates,$now,$status) = @_;
                   6780:     my ($start,$end) = split(/\./,$dates);
                   6781:     if (!$start && !$end) {
                   6782:         return 'ok';
                   6783:     }
                   6784:     if (grep/^active$/,@{$status}) {
                   6785:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6786:             return 'ok';
                   6787:         }
                   6788:     }
                   6789:     if (grep/^previous$/,@{$status}) {
                   6790:         if ($end > $now ) {
                   6791:             return 'ok';
                   6792:         }
                   6793:     }
                   6794:     if (grep/^future$/,@{$status}) {
                   6795:         if ($start > $now) {
                   6796:             return 'ok';
                   6797:         }
                   6798:     }
                   6799:     return; 
                   6800: }
                   6801: 
                   6802: sub parse_portfolio_url {
                   6803:     my ($url) = @_;
                   6804: 
                   6805:     my ($type,$udom,$unum,$group,$file_name);
                   6806:     
1.823     albertel 6807:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6808: 	$type = 1;
                   6809:         $udom = $1;
                   6810:         $unum = $2;
                   6811:         $file_name = $3;
1.823     albertel 6812:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6813: 	$type = 2;
                   6814:         $udom = $1;
                   6815:         $unum = $2;
                   6816:         $group = $3;
                   6817:         $file_name = $3.'/'.$4;
                   6818:     }
                   6819:     if (wantarray) {
                   6820: 	return ($type,$udom,$unum,$file_name,$group);
                   6821:     }
                   6822:     return $type;
                   6823: }
                   6824: 
                   6825: sub is_portfolio_url {
                   6826:     my ($url) = @_;
                   6827:     return scalar(&parse_portfolio_url($url));
                   6828: }
                   6829: 
1.798     raeburn  6830: sub is_portfolio_file {
                   6831:     my ($file) = @_;
1.820     raeburn  6832:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6833:         return 1;
                   6834:     }
                   6835:     return;
                   6836: }
                   6837: 
1.976     raeburn  6838: sub usertools_access {
1.1084    raeburn  6839:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6840:     my ($access,%tools);
                   6841:     if ($context eq '') {
                   6842:         $context = 'tools';
                   6843:     }
                   6844:     if ($context eq 'requestcourses') {
                   6845:         %tools = (
                   6846:                       official   => 1,
                   6847:                       unofficial => 1,
1.1006    raeburn  6848:                       community  => 1,
1.1246    raeburn  6849:                       textbook   => 1,
1.1305    raeburn  6850:                       placement  => 1,
1.985     raeburn  6851:                  );
1.1183    raeburn  6852:     } elsif ($context eq 'requestauthor') {
                   6853:         %tools = (
                   6854:                       requestauthor => 1,
                   6855:                  );
1.985     raeburn  6856:     } else {
                   6857:         %tools = (
                   6858:                       aboutme   => 1,
                   6859:                       blog      => 1,
1.1177    raeburn  6860:                       webdav    => 1,
1.985     raeburn  6861:                       portfolio => 1,
                   6862:                  );
                   6863:     }
1.976     raeburn  6864:     return if (!defined($tools{$tool}));
                   6865: 
1.1242    raeburn  6866:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6867:         $udom = $env{'user.domain'};
                   6868:         $uname = $env{'user.name'};
                   6869:     }
                   6870: 
1.978     raeburn  6871:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6872:         if ($action ne 'reload') {
1.985     raeburn  6873:             if ($context eq 'requestcourses') {
                   6874:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6875:             } elsif ($context eq 'requestauthor') {
                   6876:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6877:             } else {
                   6878:                 return $env{'environment.availabletools.'.$tool};
                   6879:             }
                   6880:         }
1.976     raeburn  6881:     }
                   6882: 
1.1183    raeburn  6883:     my ($toolstatus,$inststatus,$envkey);
                   6884:     if ($context eq 'requestauthor') {
                   6885:         $envkey = $context; 
                   6886:     } else {
                   6887:         $envkey = $context.'.'.$tool;
                   6888:     }
1.976     raeburn  6889: 
1.985     raeburn  6890:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6891:          ($action ne 'reload')) {
1.1183    raeburn  6892:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6893:         $inststatus = $env{'environment.inststatus'};
                   6894:     } else {
1.1084    raeburn  6895:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  6896:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  6897:             $inststatus = $userenvref->{'inststatus'};
                   6898:         } else {
1.1183    raeburn  6899:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   6900:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  6901:             $inststatus = $userenv{'inststatus'};
                   6902:         }
1.976     raeburn  6903:     }
                   6904: 
                   6905:     if ($toolstatus ne '') {
                   6906:         if ($toolstatus) {
                   6907:             $access = 1;
                   6908:         } else {
                   6909:             $access = 0;
                   6910:         }
                   6911:         return $access;
                   6912:     }
                   6913: 
1.1084    raeburn  6914:     my ($is_adv,%domdef);
                   6915:     if (ref($is_advref) eq 'HASH') {
                   6916:         $is_adv = $is_advref->{'is_adv'};
                   6917:     } else {
                   6918:         $is_adv = &is_advanced_user($udom,$uname);
                   6919:     }
                   6920:     if (ref($domdefref) eq 'HASH') {
                   6921:         %domdef = %{$domdefref};
                   6922:     } else {
                   6923:         %domdef = &get_domain_defaults($udom);
                   6924:     }
1.976     raeburn  6925:     if (ref($domdef{$tool}) eq 'HASH') {
                   6926:         if ($is_adv) {
                   6927:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   6928:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   6929:                     $access = 1;
                   6930:                 } else {
                   6931:                     $access = 0;
                   6932:                 }
                   6933:                 return $access;
                   6934:             }
                   6935:         }
                   6936:         if ($inststatus ne '') {
                   6937:             my ($hasaccess,$hasnoaccess);
                   6938:             foreach my $affiliation (split(/:/,$inststatus)) {
                   6939:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   6940:                     if ($domdef{$tool}{$affiliation}) {
                   6941:                         $hasaccess = 1;
                   6942:                     } else {
                   6943:                         $hasnoaccess = 1;
                   6944:                     }
                   6945:                 }
                   6946:             }
                   6947:             if ($hasaccess || $hasnoaccess) {
                   6948:                 if ($hasaccess) {
                   6949:                     $access = 1;
                   6950:                 } elsif ($hasnoaccess) {
                   6951:                     $access = 0; 
                   6952:                 }
                   6953:                 return $access;
                   6954:             }
                   6955:         } else {
                   6956:             if ($domdef{$tool}{'default'} ne '') {
                   6957:                 if ($domdef{$tool}{'default'}) {
                   6958:                     $access = 1;
                   6959:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   6960:                     $access = 0;
                   6961:                 }
                   6962:                 return $access;
                   6963:             }
                   6964:         }
                   6965:     } else {
1.1177    raeburn  6966:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  6967:             $access = 1;
                   6968:         } else {
                   6969:             $access = 0;
                   6970:         }
1.976     raeburn  6971:         return $access;
                   6972:     }
                   6973: }
                   6974: 
1.1050    raeburn  6975: sub is_course_owner {
                   6976:     my ($cdom,$cnum,$udom,$uname) = @_;
                   6977:     if (($udom eq '') || ($uname eq '')) {
                   6978:         $udom = $env{'user.domain'};
                   6979:         $uname = $env{'user.name'};
                   6980:     }
                   6981:     unless (($udom eq '') || ($uname eq '')) {
                   6982:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   6983:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   6984:                 return 1;
                   6985:             } else {
                   6986:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   6987:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   6988:                     return 1;
                   6989:                 }
                   6990:             }
                   6991:         }
                   6992:     }
                   6993:     return;
                   6994: }
                   6995: 
1.976     raeburn  6996: sub is_advanced_user {
                   6997:     my ($udom,$uname) = @_;
1.1085    raeburn  6998:     if ($udom ne '' && $uname ne '') {
                   6999:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7000:             if (wantarray) {
                   7001:                 return ($env{'user.adv'},$env{'user.author'});
                   7002:             } else {
                   7003:                 return $env{'user.adv'};
                   7004:             }
1.1085    raeburn  7005:         }
                   7006:     }
1.976     raeburn  7007:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7008:     my %allroles;
1.1128    raeburn  7009:     my ($is_adv,$is_author);
1.976     raeburn  7010:     foreach my $role (keys(%roleshash)) {
                   7011:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7012:         my $area = '/'.$tdomain.'/'.$trest;
                   7013:         if ($sec ne '') {
                   7014:             $area .= '/'.$sec;
                   7015:         }
                   7016:         if (($area ne '') && ($trole ne '')) {
                   7017:             my $spec=$trole.'.'.$area;
                   7018:             if ($trole =~ /^cr\//) {
                   7019:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7020:             } elsif ($trole ne 'gr') {
                   7021:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7022:             }
1.1128    raeburn  7023:             if ($trole eq 'au') {
                   7024:                 $is_author = 1;
                   7025:             }
1.976     raeburn  7026:         }
                   7027:     }
                   7028:     foreach my $role (keys(%allroles)) {
                   7029:         last if ($is_adv);
                   7030:         foreach my $item (split(/:/,$allroles{$role})) {
                   7031:             if ($item ne '') {
                   7032:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7033:                 if ($privilege eq 'adv') {
                   7034:                     $is_adv = 1;
                   7035:                     last;
                   7036:                 }
                   7037:             }
                   7038:         }
                   7039:     }
1.1128    raeburn  7040:     if (wantarray) {
                   7041:         return ($is_adv,$is_author);
                   7042:     }
1.976     raeburn  7043:     return $is_adv;
                   7044: }
1.798     raeburn  7045: 
1.1035    raeburn  7046: sub check_can_request {
1.1036    raeburn  7047:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7048:     my $canreq = 0;
                   7049:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7050:     my @options = ('approval','validate','autolimit');
                   7051:     my $optregex = join('|',@options);
                   7052:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7053:         foreach my $type (@{$types}) {
                   7054:             if (&usertools_access($env{'user.name'},
                   7055:                                   $env{'user.domain'},
                   7056:                                   $type,undef,'requestcourses')) {
                   7057:                 $canreq ++;
1.1036    raeburn  7058:                 if (ref($request_domains) eq 'HASH') {
                   7059:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7060:                 }
1.1035    raeburn  7061:                 if ($dom eq $env{'user.domain'}) {
                   7062:                     $can_request->{$type} = 1;
                   7063:                 }
                   7064:             }
                   7065:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7066:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7067:                 if (@curr > 0) {
1.1036    raeburn  7068:                     foreach my $item (@curr) {
                   7069:                         if (ref($request_domains) eq 'HASH') {
                   7070:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7071:                             if ($otherdom ne '') {
                   7072:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7073:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7074:                                         push(@{$request_domains->{$type}},$otherdom);
                   7075:                                     }
                   7076:                                 } else {
                   7077:                                     push(@{$request_domains->{$type}},$otherdom);
                   7078:                                 }
                   7079:                             }
                   7080:                         }
                   7081:                     }
                   7082:                     unless($dom eq $env{'user.domain'}) {
                   7083:                         $canreq ++;
1.1035    raeburn  7084:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7085:                             $can_request->{$type} = 1;
                   7086:                         }
                   7087:                     }
                   7088:                 }
                   7089:             }
                   7090:         }
                   7091:     }
                   7092:     return $canreq;
                   7093: }
                   7094: 
1.341     www      7095: # ---------------------------------------------- Custom access rule evaluation
                   7096: 
                   7097: sub customaccess {
                   7098:     my ($priv,$uri)=@_;
1.807     albertel 7099:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7100:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7101:     $udom = &LONCAPA::clean_domain($udom);
                   7102:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7103:     my $access=0;
1.800     albertel 7104:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7105: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7106: 	if ($type eq 'user') {
                   7107: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7108: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7109: 		if ($tdom) {
                   7110: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7111: 		}
1.896     albertel 7112: 		if ($tuname) {
                   7113: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7114: 		}
                   7115: 		$access=($effect eq 'allow');
                   7116: 		last;
                   7117: 	    }
                   7118: 	} else {
                   7119: 	    if ($role) {
                   7120: 		if ($role ne $urole) { next; }
                   7121: 	    }
                   7122: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7123: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7124: 		if ($tdom) {
                   7125: 		    if ($tdom ne $udom) { next; }
                   7126: 		}
                   7127: 		if ($tcrs) {
                   7128: 		    if ($tcrs ne $ucrs) { next; }
                   7129: 		}
                   7130: 		if ($tsec) {
                   7131: 		    if ($tsec ne $usec) { next; }
                   7132: 		}
                   7133: 		$access=($effect eq 'allow');
                   7134: 		last;
                   7135: 	    }
                   7136: 	    if ($realm eq '' && $role eq '') {
                   7137: 		$access=($effect eq 'allow');
                   7138: 	    }
1.402     bowersj2 7139: 	}
1.341     www      7140:     }
                   7141:     return $access;
                   7142: }
                   7143: 
1.103     harris41 7144: # ------------------------------------------------- Check for a user privilege
1.12      www      7145: 
                   7146: sub allowed {
1.1281    raeburn  7147:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7148:     my $ver_orguri=$uri;
1.439     www      7149:     $uri=&deversion($uri);
1.152     www      7150:     my $orguri=$uri;
1.52      www      7151:     $uri=&declutter($uri);
1.809     raeburn  7152: 
1.810     raeburn  7153:     if ($priv eq 'evb') {
                   7154: # Evade communication block restrictions for specified role in a course
                   7155:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7156:             return $1;
                   7157:         } else {
                   7158:             return;
                   7159:         }
                   7160:     }
                   7161: 
1.620     albertel 7162:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7163: # Free bre access to adm and meta resources
1.775     albertel 7164:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 7165: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7166: 	&& ($priv eq 'bre')) {
1.14      www      7167: 	return 'F';
1.159     www      7168:     }
                   7169: 
1.545     banghart 7170: # Free bre access to user's own portfolio contents
1.714     raeburn  7171:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7172:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7173: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7174:         my %setters;
                   7175:         my ($startblock,$endblock) = 
                   7176:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7177:         if ($startblock && $endblock) {
                   7178:             return 'B';
                   7179:         } else {
                   7180:             return 'F';
                   7181:         }
1.545     banghart 7182:     }
                   7183: 
1.762     raeburn  7184: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7185:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7186:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7187:         if (exists($env{'request.course.id'})) {
                   7188:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7189:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7190:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7191:                 my $courseprivid=$env{'request.course.id'};
                   7192:                 $courseprivid=~s/\_/\//;
                   7193:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7194:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7195:                     return $1; 
1.762     raeburn  7196:                 } else {
                   7197:                     if ($env{'request.course.sec'}) {
                   7198:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7199:                     }
                   7200:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7201:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7202:                         return $2;
                   7203:                     }
1.714     raeburn  7204:                 }
                   7205:             }
                   7206:         }
                   7207:     }
                   7208: 
1.159     www      7209: # Free bre to public access
                   7210: 
                   7211:     if ($priv eq 'bre') {
1.238     www      7212:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7213: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7214:            return 'F'; 
                   7215:         }
1.238     www      7216:         if ($copyright eq 'priv') {
                   7217:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7218: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7219: 		return '';
                   7220:             }
                   7221:         }
                   7222:         if ($copyright eq 'domain') {
                   7223:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7224: 	    unless (($env{'user.domain'} eq $1) ||
                   7225:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7226: 		return '';
                   7227:             }
1.262     matthew  7228:         }
1.620     albertel 7229:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7230:             # Library role, so allow browsing of resources in this domain.
                   7231:             return 'F';
1.238     www      7232:         }
1.341     www      7233:         if ($copyright eq 'custom') {
                   7234: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7235:         }
1.14      www      7236:     }
1.264     matthew  7237:     # Domain coordinator is trying to create a course
1.620     albertel 7238:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7239:         # uri is the requested domain in this case.
                   7240:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7241:         # a role of dc for the domain in question.
1.620     albertel 7242:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7243:     }
1.29      www      7244: 
1.52      www      7245:     my $thisallowed='';
                   7246:     my $statecond=0;
                   7247:     my $courseprivid='';
                   7248: 
1.1039    raeburn  7249:     my $ownaccess;
1.1043    raeburn  7250:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7251:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7252:         if ($uri eq '') {
                   7253:             $ownaccess = 1;
                   7254:         } else {
                   7255:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7256:                 my $udom = $env{'user.domain'};
                   7257:                 my $uname = $env{'user.name'};
                   7258:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7259:                     $ownaccess = 1;
1.1040    raeburn  7260:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7261:                     unless ($uri =~ m{\.\./}) {
                   7262:                         $ownaccess = 1;
                   7263:                     }
                   7264:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7265:                     my $now = time;
                   7266:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7267:                         my $adom = $1;
                   7268:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7269:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7270:                                 my ($start,$end) = split('.',$env{$key});
                   7271:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7272:                                     $ownaccess = 1;
                   7273:                                     last;
                   7274:                                 }
                   7275:                             }
                   7276:                         }
                   7277:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7278:                         my $adom = $1;
                   7279:                         my $aname = $2;
1.1042    raeburn  7280:                         foreach my $role ('ca','aa') { 
                   7281:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7282:                                 my ($start,$end) =
                   7283:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7284:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7285:                                     $ownaccess = 1;
                   7286:                                     last;
                   7287:                                 }
1.1039    raeburn  7288:                             }
                   7289:                         }
                   7290:                     }
                   7291:                 }
                   7292:             }
                   7293:         }
                   7294:     }
                   7295: 
1.52      www      7296: # Course
                   7297: 
1.620     albertel 7298:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7299:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7300:             $thisallowed.=$1;
                   7301:         }
1.52      www      7302:     }
1.29      www      7303: 
1.52      www      7304: # Domain
                   7305: 
1.620     albertel 7306:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7307:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7308:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7309:             $thisallowed.=$1;
                   7310:         }
1.12      www      7311:     }
1.52      www      7312: 
1.1141    raeburn  7313: # User who is not author or co-author might still be able to edit
                   7314: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7315:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7316:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7317:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7318:             $thisallowed.=$1;
                   7319:         }
                   7320:     }
                   7321: 
1.52      www      7322: # Course: uri itself is a course
1.66      www      7323:     my $courseuri=$uri;
                   7324:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7325:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7326: 
1.620     albertel 7327:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7328:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7329:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7330:             $thisallowed.=$1;
                   7331:         }
1.12      www      7332:     }
1.29      www      7333: 
1.665     albertel 7334: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7335: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7336:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7337: 	$thisallowed='';
1.671     raeburn  7338:         my ($match)=&is_on_map($uri);
                   7339:         if ($match) {
                   7340:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7341:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7342:                 my $value = $1;
                   7343:                 if ($noblockcheck) {
                   7344:                     $thisallowed.=$value;
1.1162    raeburn  7345:                 } else {
1.1281    raeburn  7346:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7347:                     if (@blockers > 0) {
                   7348:                         $thisallowed = 'B';
                   7349:                     } else {
                   7350:                         $thisallowed.=$value;
                   7351:                     }
1.1162    raeburn  7352:                 }
1.671     raeburn  7353:             }
                   7354:         } else {
1.705     albertel 7355:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7356:             if ($refuri) {
                   7357:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7358:                     $thisallowed='F';
1.671     raeburn  7359:                 } else {
                   7360:                     $refuri=&declutter($refuri);
                   7361:                     my ($match) = &is_on_map($refuri);
                   7362:                     if ($match) {
1.1281    raeburn  7363:                         if ($noblockcheck) {
                   7364:                             $thisallowed='F';
1.1162    raeburn  7365:                         } else {
1.1281    raeburn  7366:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7367:                             if (@blockers > 0) {
                   7368:                                 $thisallowed = 'B';
                   7369:                             } else {
                   7370:                                 $thisallowed='F';
                   7371:                             }
1.1162    raeburn  7372:                         }
1.671     raeburn  7373:                     }
1.669     raeburn  7374:                 }
1.671     raeburn  7375:             }
                   7376:         }
1.314     www      7377:     }
1.492     albertel 7378: 
1.766     albertel 7379:     if ($priv eq 'bre'
                   7380: 	&& $thisallowed ne 'F' 
                   7381: 	&& $thisallowed ne '2'
                   7382: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7383: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7384:     }
1.1250    raeburn  7385: 
1.52      www      7386: # Full access at system, domain or course-wide level? Exit.
1.29      www      7387:     if ($thisallowed=~/F/) {
                   7388: 	return 'F';
                   7389:     }
                   7390: 
1.52      www      7391: # If this is generating or modifying users, exit with special codes
1.29      www      7392: 
1.643     www      7393:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7394: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7395: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7396: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7397: 	    unless ($auname) { return $thisallowed; }
                   7398: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7399: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7400: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7401: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7402: 	}
1.52      www      7403: 	return $thisallowed;
                   7404:     }
                   7405: #
1.103     harris41 7406: # Gathered so far: system, domain and course wide privileges
1.52      www      7407: #
                   7408: # Course: See if uri or referer is an individual resource that is part of 
                   7409: # the course
                   7410: 
1.620     albertel 7411:     if ($env{'request.course.id'}) {
1.232     www      7412: 
1.620     albertel 7413:        $courseprivid=$env{'request.course.id'};
                   7414:        if ($env{'request.course.sec'}) {
                   7415:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7416:        }
                   7417:        $courseprivid=~s/\_/\//;
                   7418:        my $checkreferer=1;
1.232     www      7419:        my ($match,$cond)=&is_on_map($uri);
                   7420:        if ($match) {
                   7421:            $statecond=$cond;
1.620     albertel 7422:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7423:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7424:                my $value = $1;
                   7425:                if ($priv eq 'bre') {
1.1281    raeburn  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:                    }
                   7436:                } else {
                   7437:                    $thisallowed.=$value;
                   7438:                }
1.52      www      7439:                $checkreferer=0;
                   7440:            }
1.29      www      7441:        }
1.83      www      7442:        
1.148     www      7443:        if ($checkreferer) {
1.620     albertel 7444: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7445:             unless ($refuri) {
1.800     albertel 7446:                 foreach my $key (keys(%env)) {
                   7447: 		    if ($key=~/^httpref\..*\*/) {
                   7448: 			my $pattern=$key;
1.156     www      7449:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7450:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7451:                         $pattern=~s/\//\\\//g;
1.152     www      7452:                         if ($orguri=~/$pattern/) {
1.800     albertel 7453: 			    $refuri=$env{$key};
1.148     www      7454:                         }
                   7455:                     }
1.191     harris41 7456:                 }
1.148     www      7457:             }
1.232     www      7458: 
1.148     www      7459:          if ($refuri) { 
1.152     www      7460: 	  $refuri=&declutter($refuri);
1.232     www      7461:           my ($match,$cond)=&is_on_map($refuri);
                   7462:             if ($match) {
                   7463:               my $refstatecond=$cond;
1.620     albertel 7464:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7465:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7466:                   my $value = $1;
                   7467:                   if ($priv eq 'bre') {
1.1281    raeburn  7468:                       if ($noblockcheck) {
                   7469:                           $thisallowed.=$value;
1.1162    raeburn  7470:                       } else {
1.1281    raeburn  7471:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7472:                           if (@blockers > 0) {
                   7473:                               $thisallowed = 'B';
                   7474:                           } else {
                   7475:                               $thisallowed.=$value;
                   7476:                           }
1.1162    raeburn  7477:                       }
                   7478:                   } else {
                   7479:                       $thisallowed.=$value;
                   7480:                   }
1.53      www      7481:                   $uri=$refuri;
                   7482:                   $statecond=$refstatecond;
1.52      www      7483:               }
                   7484:           }
1.148     www      7485:         }
1.29      www      7486:        }
1.52      www      7487:    }
1.29      www      7488: 
1.52      www      7489: #
1.103     harris41 7490: # Gathered now: all privileges that could apply, and condition number
1.52      www      7491: # 
                   7492: #
                   7493: # Full or no access?
                   7494: #
1.29      www      7495: 
1.52      www      7496:     if ($thisallowed=~/F/) {
                   7497: 	return 'F';
                   7498:     }
1.29      www      7499: 
1.52      www      7500:     unless ($thisallowed) {
                   7501:         return '';
                   7502:     }
1.29      www      7503: 
1.52      www      7504: # Restrictions exist, deal with them
                   7505: #
                   7506: #   C:according to course preferences
                   7507: #   R:according to resource settings
                   7508: #   L:unless locked
                   7509: #   X:according to user session state
                   7510: #
                   7511: 
                   7512: # Possibly locked functionality, check all courses
1.54      www      7513: # Locks might take effect only after 10 minutes cache expiration for other
                   7514: # courses, and 2 minutes for current course
1.52      www      7515: 
                   7516:     my $envkey;
                   7517:     if ($thisallowed=~/L/) {
1.1000    raeburn  7518:         foreach $envkey (keys(%env)) {
1.54      www      7519:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7520:                my $courseid=$2;
                   7521:                my $roleid=$1.'.'.$2;
1.92      www      7522:                $courseid=~s/^\///;
1.54      www      7523:                my $expiretime=600;
1.620     albertel 7524:                if ($env{'request.role'} eq $roleid) {
1.54      www      7525: 		  $expiretime=120;
                   7526:                }
                   7527: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7528:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7529:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7530: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7531:                }
1.620     albertel 7532:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7533:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7534: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7535:                        &log($env{'user.domain'},$env{'user.name'},
                   7536:                             $env{'user.home'},
1.57      www      7537:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7538:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7539:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7540: 		       return '';
                   7541:                    }
                   7542:                }
1.620     albertel 7543:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7544:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7545: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7546:                        &log($env{'user.domain'},$env{'user.name'},
                   7547:                             $env{'user.home'},
1.57      www      7548:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7549:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7550:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7551: 		       return '';
                   7552:                    }
                   7553:                }
                   7554: 	   }
1.29      www      7555:        }
1.52      www      7556:     }
                   7557:    
                   7558: #
                   7559: # Rest of the restrictions depend on selected course
                   7560: #
                   7561: 
1.620     albertel 7562:     unless ($env{'request.course.id'}) {
1.766     albertel 7563: 	if ($thisallowed eq 'A') {
                   7564: 	    return 'A';
1.814     raeburn  7565:         } elsif ($thisallowed eq 'B') {
                   7566:             return 'B';
1.766     albertel 7567: 	} else {
                   7568: 	    return '1';
                   7569: 	}
1.52      www      7570:     }
1.29      www      7571: 
1.52      www      7572: #
                   7573: # Now user is definitely in a course
                   7574: #
1.53      www      7575: 
                   7576: 
                   7577: # Course preferences
                   7578: 
                   7579:    if ($thisallowed=~/C/) {
1.620     albertel 7580:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7581:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7582:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7583: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7584: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7585: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7586: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7587: 			$env{'request.course.id'});
                   7588: 	   }
1.237     www      7589:            return '';
                   7590:        }
                   7591: 
1.620     albertel 7592:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7593: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7594: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7595: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7596: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7597: 			$env{'request.course.id'});
                   7598: 	   }
1.54      www      7599:            return '';
                   7600:        }
1.53      www      7601:    }
                   7602: 
                   7603: # Resource preferences
                   7604: 
                   7605:    if ($thisallowed=~/R/) {
1.620     albertel 7606:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7607:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7608: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7609: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7610: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7611: 	   }
                   7612: 	   return '';
1.54      www      7613:        }
1.53      www      7614:    }
1.30      www      7615: 
1.246     www      7616: # Restricted by state or randomout?
1.30      www      7617: 
1.52      www      7618:    if ($thisallowed=~/X/) {
1.620     albertel 7619:       if ($env{'acc.randomout'}) {
1.579     albertel 7620: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7621:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7622:             return ''; 
                   7623:          }
1.247     www      7624:       }
                   7625:       if (&condval($statecond)) {
1.52      www      7626: 	 return '2';
                   7627:       } else {
                   7628:          return '';
                   7629:       }
                   7630:    }
1.30      www      7631: 
1.766     albertel 7632:     if ($thisallowed eq 'A') {
                   7633: 	return 'A';
1.814     raeburn  7634:     } elsif ($thisallowed eq 'B') {
                   7635:         return 'B';
1.766     albertel 7636:     }
1.52      www      7637:    return 'F';
1.232     www      7638: }
1.1162    raeburn  7639: 
1.1192    raeburn  7640: # ------------------------------------------- Check construction space access
                   7641: 
                   7642: sub constructaccess {
                   7643:     my ($url,$setpriv)=@_;
                   7644: 
                   7645: # We do not allow editing of previous versions of files
                   7646:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7647: 
                   7648: # Get username and domain from URL
                   7649:     my ($ownername,$ownerdomain,$ownerhome);
                   7650: 
                   7651:     ($ownerdomain,$ownername) =
1.1325    raeburn  7652:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7653: 
                   7654: # The URL does not really point to any authorspace, forget it
                   7655:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7656: 
                   7657: # Now we need to see if the user has access to the authorspace of
                   7658: # $ownername at $ownerdomain
                   7659: 
                   7660:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7661: # Real author for this?
                   7662:        $ownerhome = $env{'user.home'};
                   7663:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7664:           return ($ownername,$ownerdomain,$ownerhome);
                   7665:        }
                   7666:     } else {
                   7667: # Co-author for this?
                   7668:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7669:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7670:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7671:             return ($ownername,$ownerdomain,$ownerhome);
                   7672:         }
1.1312    raeburn  7673:         if ($env{'request.course.id'}) {
                   7674:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7675:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7676:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7677:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7678:                     return ($ownername,$ownerdomain,$ownerhome);
                   7679:                 }
                   7680:             }
                   7681:         }
1.1192    raeburn  7682:     }
                   7683: 
                   7684: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7685: # we might as well leave
                   7686:    unless ($setpriv) { return ''; }
                   7687: 
                   7688: # Backdoor access?
                   7689:     my $allowed=&allowed('eco',$ownerdomain);
                   7690: # Nope
                   7691:     unless ($allowed) { return ''; }
                   7692: # Looks like we may have access, but could be locked by the owner of the construction space
                   7693:     if ($allowed eq 'U') {
                   7694:         my %blocked=&get('environment',['domcoord.author'],
                   7695:                          $ownerdomain,$ownername);
                   7696: # Is blocked by owner
                   7697:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7698:     }
                   7699:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7700: # Grant temporary access
                   7701:         my $then=$env{'user.login.time'};
1.1209    raeburn  7702:         my $update=$env{'user.update.time'};
1.1192    raeburn  7703:         if (!$update) { $update = $then; }
                   7704:         my $refresh=$env{'user.refresh.time'};
                   7705:         if (!$refresh) { $refresh = $update; }
                   7706:         my $now = time;
                   7707:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7708:                            $now,'ca','constructaccess');
                   7709:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7710:         return($ownername,$ownerdomain,$ownerhome);
                   7711:     }
                   7712: # No business here
                   7713:     return '';
                   7714: }
                   7715: 
1.1282    raeburn  7716: # ----------------------------------------------------------- Content Blocking
                   7717: 
                   7718: {
                   7719: # Caches for faster Course Contents display where content blocking
                   7720: # is in operation (i.e., interval param set) for timed quiz.
                   7721: #
                   7722: # User for whom data are being temporarily cached.
                   7723: my $cacheduser='';
                   7724: # Cached blockers for this user (a hash of blocking items). 
                   7725: my %cachedblockers=();
                   7726: # When the data were last cached.
                   7727: my $cachedlast='';
                   7728: 
                   7729: sub load_all_blockers {
                   7730:     my ($uname,$udom,$blocks)=@_;
                   7731:     if (($uname ne '') && ($udom ne '')) { 
                   7732:         if (($cacheduser eq $uname.':'.$udom) &&
                   7733:             (abs($cachedlast-time)<5)) {
                   7734:             return;
                   7735:         }
                   7736:     }
                   7737:     $cachedlast=time;
                   7738:     $cacheduser=$uname.':'.$udom;
                   7739:     %cachedblockers = &get_commblock_resources($blocks);
                   7740: }
                   7741: 
1.1162    raeburn  7742: sub get_comm_blocks {
                   7743:     my ($cdom,$cnum) = @_;
                   7744:     if ($cdom eq '' || $cnum eq '') {
                   7745:         return unless ($env{'request.course.id'});
                   7746:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7747:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7748:     }
                   7749:     my %commblocks;
                   7750:     my $hashid=$cdom.'_'.$cnum;
                   7751:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7752:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7753:         %commblocks = %{$blocksref};
                   7754:     } else {
                   7755:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7756:         my $cachetime = 600;
                   7757:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7758:     }
                   7759:     return %commblocks;
                   7760: }
                   7761: 
1.1282    raeburn  7762: sub get_commblock_resources {
                   7763:     my ($blocks) = @_;
                   7764:     my %blockers = ();
                   7765:     return %blockers unless ($env{'request.course.id'});
                   7766:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7767:     my %commblocks;
                   7768:     if (ref($blocks) eq 'HASH') {
                   7769:         %commblocks = %{$blocks};
                   7770:     } else {
                   7771:         %commblocks = &get_comm_blocks();
                   7772:     }
1.1282    raeburn  7773:     return %blockers unless (keys(%commblocks) > 0); 
                   7774:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7775:     return %blockers unless (ref($navmap));
1.1162    raeburn  7776:     my $now = time;
                   7777:     foreach my $block (keys(%commblocks)) {
                   7778:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7779:             my ($start,$end) = ($1,$2);
                   7780:             if ($start <= $now && $end >= $now) {
                   7781:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7782:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7783:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7784:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7785:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7786:                             }
                   7787:                         }
                   7788:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7789:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7790:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7791:                             }
                   7792:                         }
                   7793:                     }
                   7794:                 }
                   7795:             }
                   7796:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7797:             my $item = $1;
1.1163    raeburn  7798:             my @to_test;
1.1162    raeburn  7799:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7800:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7801:                     my @interval;
                   7802:                     my $type = 'map';
                   7803:                     if ($item eq 'course') {
                   7804:                         $type = 'course';
                   7805:                         @interval=&EXT("resource.0.interval");
                   7806:                     } else {
                   7807:                         if ($item =~ /___\d+___/) {
                   7808:                             $type = 'resource';
                   7809:                             @interval=&EXT("resource.0.interval",$item);
                   7810:                             if (ref($navmap)) {                        
                   7811:                                 my $res = $navmap->getBySymb($item); 
                   7812:                                 push(@to_test,$res);
                   7813:                             }
1.1162    raeburn  7814:                         } else {
1.1282    raeburn  7815:                             my $mapsymb = &symbread($item,1);
                   7816:                             if ($mapsymb) {
                   7817:                                 if (ref($navmap)) {
                   7818:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7819:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7820:                                     foreach my $res (@to_test) {
                   7821:                                         my $symb = $res->symb();
                   7822:                                         next if ($symb eq $mapsymb);
                   7823:                                         if ($symb ne '') {
                   7824:                                             @interval=&EXT("resource.0.interval",$symb);
                   7825:                                             if ($interval[1] eq 'map') {
                   7826:                                                 last;
1.1162    raeburn  7827:                                             }
                   7828:                                         }
                   7829:                                     }
                   7830:                                 }
                   7831:                             }
                   7832:                         }
1.1282    raeburn  7833:                     }
1.1310    raeburn  7834:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7835:                         my $timelimit = $1; 
1.1282    raeburn  7836:                         my $first_access;
                   7837:                         if ($type eq 'resource') {
                   7838:                             $first_access=&get_first_access($interval[1],$item);
                   7839:                         } elsif ($type eq 'map') {
                   7840:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7841:                         } else {
                   7842:                             $first_access=&get_first_access($interval[1]);
                   7843:                         }
                   7844:                         if ($first_access) {
1.1292    raeburn  7845:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7846:                             if ($timesup > $now) {
                   7847:                                 my $activeblock;
                   7848:                                 foreach my $res (@to_test) {
1.1283    raeburn  7849:                                     if ($res->answerable()) {
1.1282    raeburn  7850:                                         $activeblock = 1;
                   7851:                                         last;
                   7852:                                     }
                   7853:                                 }
                   7854:                                 if ($activeblock) {
                   7855:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7856:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7857:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7858:                                          }
                   7859:                                     }
                   7860:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7861:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7862:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7863:                                         }
1.1162    raeburn  7864:                                     }
                   7865:                                 }
                   7866:                             }
                   7867:                         }
                   7868:                     }
                   7869:                 }
                   7870:             }
                   7871:         }
                   7872:     }
1.1282    raeburn  7873:     return %blockers;
1.1162    raeburn  7874: }
                   7875: 
1.1282    raeburn  7876: sub has_comm_blocking {
                   7877:     my ($priv,$symb,$uri,$blocks) = @_;
                   7878:     my @blockers;
                   7879:     return unless ($env{'request.course.id'});
                   7880:     return unless ($priv eq 'bre');
                   7881:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7882:     return if ($env{'request.state'} eq 'construct');
                   7883:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7884:     return unless (keys(%cachedblockers) > 0);
                   7885:     my (%possibles,@symbs);
                   7886:     if (!$symb) {
                   7887:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7888:     }
1.1282    raeburn  7889:     if ($symb) {
                   7890:         @symbs = ($symb);
                   7891:     } elsif (keys(%possibles)) { 
                   7892:         @symbs = keys(%possibles);
                   7893:     }
                   7894:     my $noblock;
                   7895:     foreach my $symb (@symbs) {
                   7896:         last if ($noblock);
                   7897:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   7898:         foreach my $block (keys(%cachedblockers)) {
                   7899:             if ($block =~ /^firstaccess____(.+)$/) {
                   7900:                 my $item = $1;
                   7901:                 if (($item eq $map) || ($item eq $symb)) {
                   7902:                     $noblock = 1;
                   7903:                     last;
                   7904:                 }
                   7905:             }
                   7906:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   7907:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   7908:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   7909:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   7910:                             push(@blockers,$block);
                   7911:                         }
                   7912:                     }
                   7913:                 }
1.1162    raeburn  7914:             }
1.1282    raeburn  7915:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   7916:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   7917:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   7918:                         push(@blockers,$block);
                   7919:                     }
                   7920:                 }
1.1162    raeburn  7921:             }
                   7922:         }
                   7923:     }
1.1282    raeburn  7924:     return if ($noblock);
                   7925:     return @blockers;
                   7926: }
1.1162    raeburn  7927: }
                   7928: 
1.1282    raeburn  7929: # -------------------------------- Deversion and split uri into path an filename   
                   7930: 
1.1133    foxr     7931: #
1.1282    raeburn  7932: #   Removes the version from a URI and
1.1133    foxr     7933: #   splits it in to its filename and path to the filename.
                   7934: #   Seems like File::Basename could have done this more clearly.
                   7935: #   Parameters:
                   7936: #      $uri   - input URI
                   7937: #   Returns:
                   7938: #     Two element list consisting of 
                   7939: #     $pathname  - the URI up to and excluding the trailing /
                   7940: #     $filename  - The part of the URI following the last /
                   7941: #  NOTE:
                   7942: #    Another realization of this is simply:
                   7943: #    use File::Basename;
                   7944: #    ...
                   7945: #    $uri = shift;
                   7946: #    $filename = basename($uri);
                   7947: #    $path     = dirname($uri);
                   7948: #    return ($filename, $path);
                   7949: #
                   7950: #     The implementation below is probably faster however.
                   7951: #
1.710     albertel 7952: sub split_uri_for_cond {
                   7953:     my $uri=&deversion(&declutter(shift));
                   7954:     my @uriparts=split(/\//,$uri);
                   7955:     my $filename=pop(@uriparts);
                   7956:     my $pathname=join('/',@uriparts);
                   7957:     return ($pathname,$filename);
                   7958: }
1.232     www      7959: # --------------------------------------------------- Is a resource on the map?
                   7960: 
                   7961: sub is_on_map {
1.710     albertel 7962:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 7963:     #Trying to find the conditional for the file
1.620     albertel 7964:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 7965: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      7966:     if ($match) {
1.289     bowersj2 7967: 	return (1,$1);
                   7968:     } else {
1.434     www      7969: 	return (0,0);
1.289     bowersj2 7970:     }
1.12      www      7971: }
                   7972: 
1.427     www      7973: # --------------------------------------------------------- Get symb from alias
                   7974: 
                   7975: sub get_symb_from_alias {
                   7976:     my $symb=shift;
                   7977:     my ($map,$resid,$url)=&decode_symb($symb);
                   7978: # Already is a symb
                   7979:     if ($url) { return $symb; }
                   7980: # Must be an alias
                   7981:     my $aliassymb='';
                   7982:     my %bighash;
1.620     albertel 7983:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      7984:                             &GDBM_READER(),0640)) {
                   7985:         my $rid=$bighash{'mapalias_'.$symb};
                   7986: 	if ($rid) {
                   7987: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 7988: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   7989: 				    $resid,$bighash{'src_'.$rid});
1.427     www      7990: 	}
                   7991:         untie %bighash;
                   7992:     }
                   7993:     return $aliassymb;
                   7994: }
                   7995: 
1.12      www      7996: # ----------------------------------------------------------------- Define Role
                   7997: 
                   7998: sub definerole {
                   7999:   if (allowed('mcr','/')) {
1.1326    raeburn  8000:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8001:     foreach my $role (split(':',$sysrole)) {
                   8002: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8003:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8004:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8005: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8006:                return "refused:s:$crole&$cqual"; 
                   8007:             }
                   8008:         }
1.191     harris41 8009:     }
1.800     albertel 8010:     foreach my $role (split(':',$domrole)) {
                   8011: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8012:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8013:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8014: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8015:                return "refused:d:$crole&$cqual"; 
                   8016:             }
                   8017:         }
1.191     harris41 8018:     }
1.800     albertel 8019:     foreach my $role (split(':',$courole)) {
                   8020: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8021:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8022:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8023: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8024:                return "refused:c:$crole&$cqual"; 
                   8025:             }
                   8026:         }
1.191     harris41 8027:     }
1.1326    raeburn  8028:     my $uhome;
                   8029:     if (($uname ne '') && ($udom ne '')) {
                   8030:         $uhome = &homeserver($uname,$udom);
                   8031:         return $uhome if ($uhome eq 'no_host');
                   8032:     } else {
                   8033:         $uname = $env{'user.name'};
                   8034:         $udom = $env{'user.domain'};
                   8035:         $uhome = $env{'user.home'};
                   8036:     }
1.620     albertel 8037:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8038:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8039:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8040:     return reply($command,$uhome);
1.12      www      8041:   } else {
                   8042:     return 'refused';
                   8043:   }
1.105     harris41 8044: }
                   8045: 
                   8046: # ---------------- Make a metadata query against the network of library servers
                   8047: 
                   8048: sub metadata_query {
1.1237    raeburn  8049:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8050:     my %rhash;
1.845     albertel 8051:     my %libserv = &all_library();
1.244     matthew  8052:     my @server_list = (defined($server_array) ? @$server_array
                   8053:                                               : keys(%libserv) );
                   8054:     for my $server (@server_list) {
1.1237    raeburn  8055:         my $domains = ''; 
                   8056:         if (ref($domains_hash) eq 'HASH') {
                   8057:             $domains = $domains_hash->{$server}; 
                   8058:         }
1.118     harris41 8059: 	unless ($custom or $customshow) {
1.1237    raeburn  8060: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8061: 	    $rhash{$server}=$reply;
                   8062: 	}
                   8063: 	else {
                   8064: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8065: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8066: 			     $server);
                   8067: 	    $rhash{$server}=$reply;
                   8068: 	}
1.112     harris41 8069:     }
1.118     harris41 8070:     return \%rhash;
1.240     www      8071: }
                   8072: 
                   8073: # ----------------------------------------- Send log queries and wait for reply
                   8074: 
                   8075: sub log_query {
                   8076:     my ($uname,$udom,$query,%filters)=@_;
                   8077:     my $uhome=&homeserver($uname,$udom);
                   8078:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8079:     my $uhost=&hostname($uhome);
1.800     albertel 8080:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8081:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8082:                        $uhome);
1.479     albertel 8083:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8084:     return get_query_reply($queryid);
                   8085: }
                   8086: 
1.818     raeburn  8087: # -------------------------- Update MySQL table for portfolio file
                   8088: 
                   8089: sub update_portfolio_table {
1.821     raeburn  8090:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8091:     if ($group ne '') {
                   8092:         $file_name =~s /^\Q$group\E//;
                   8093:     }
1.818     raeburn  8094:     my $homeserver = &homeserver($uname,$udom);
                   8095:     my $queryid=
1.821     raeburn  8096:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8097:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8098:     my $reply = &get_query_reply($queryid);
                   8099:     return $reply;
                   8100: }
                   8101: 
1.899     raeburn  8102: # -------------------------- Update MySQL allusers table
                   8103: 
                   8104: sub update_allusers_table {
                   8105:     my ($uname,$udom,$names) = @_;
                   8106:     my $homeserver = &homeserver($uname,$udom);
                   8107:     my $queryid=
                   8108:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8109:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8110:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8111:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8112:                'generation='.&escape($names->{'generation'}).'%%'.
                   8113:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8114:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8115:     return;
1.899     raeburn  8116: }
                   8117: 
1.508     raeburn  8118: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8119: 
                   8120: sub fetch_enrollment_query {
1.511     raeburn  8121:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8122:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8123:     my $maxtries = 1;
1.508     raeburn  8124:     if ($context eq 'automated') {
                   8125:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8126:         $sleep = 2;
                   8127:         $loopmax = 100;
1.547     raeburn  8128:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8129:     } else {
                   8130:         $homeserver = &homeserver($cnum,$dom);
                   8131:     }
1.838     albertel 8132:     my $host=&hostname($homeserver);
1.506     raeburn  8133:     my $cmd = '';
1.1000    raeburn  8134:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8135:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8136:     }
                   8137:     $cmd =~ s/%%$//;
                   8138:     $cmd = &escape($cmd);
                   8139:     my $query = 'fetchenrollment';
1.620     albertel 8140:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8141:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8142:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8143:         return 'error: '.$queryid;
                   8144:     }
1.1317    raeburn  8145:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8146:     my $tries = 1;
                   8147:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8148:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8149:         $tries ++;
                   8150:     }
1.526     raeburn  8151:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8152:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8153:     } else {
1.901     albertel 8154:         my @responses = split(/:/,$reply);
1.1322    raeburn  8155:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8156:             foreach my $line (@responses) {
                   8157:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8158:                 $$replyref{$key} = $value;
                   8159:             }
                   8160:         } else {
1.1117    foxr     8161:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8162:             foreach my $line (@responses) {
                   8163:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8164:                 $$replyref{$key} = $value;
                   8165:                 if ($value > 0) {
1.800     albertel 8166:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8167:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8168:                         my $destname = $pathname.'/'.$filename;
                   8169:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8170:                         if ($xml_classlist =~ /^error/) {
                   8171:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8172:                         } else {
1.506     raeburn  8173:                             if ( open(FILE,">$destname") ) {
                   8174:                                 print FILE &unescape($xml_classlist);
                   8175:                                 close(FILE);
1.526     raeburn  8176:                             } else {
                   8177:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8178:                             }
                   8179:                         }
                   8180:                     }
                   8181:                 }
                   8182:             }
                   8183:         }
                   8184:         return 'ok';
                   8185:     }
                   8186:     return 'error';
                   8187: }
                   8188: 
1.242     www      8189: sub get_query_reply {
1.1317    raeburn  8190:     my ($queryid,$sleep,$loopmax) = @_;;
                   8191:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8192:         $sleep = 0.2;
                   8193:     }
                   8194:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8195:         $loopmax = 100;
                   8196:     }
1.1117    foxr     8197:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8198:     my $reply='';
1.1317    raeburn  8199:     for (1..$loopmax) {
                   8200: 	sleep($sleep);
1.240     www      8201:         if (-e $replyfile.'.end') {
1.448     albertel 8202: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 8203: 		$reply = join('',<$fh>);
                   8204: 		close($fh);
1.240     www      8205: 	   } else { return 'error: reply_file_error'; }
1.242     www      8206:            return &unescape($reply);
                   8207: 	}
1.240     www      8208:     }
1.242     www      8209:     return 'timeout:'.$queryid;
1.240     www      8210: }
                   8211: 
                   8212: sub courselog_query {
1.241     www      8213: #
                   8214: # possible filters:
                   8215: # url: url or symb
                   8216: # username
                   8217: # domain
                   8218: # action: view, submit, grade
                   8219: # start: timestamp
                   8220: # end: timestamp
                   8221: #
1.240     www      8222:     my (%filters)=@_;
1.620     albertel 8223:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8224:     if ($filters{'url'}) {
                   8225: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8226:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8227:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8228:     }
1.620     albertel 8229:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8230:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8231:     return &log_query($cname,$cdom,'courselog',%filters);
                   8232: }
                   8233: 
                   8234: sub userlog_query {
1.858     raeburn  8235: #
                   8236: # possible filters:
                   8237: # action: log check role
                   8238: # start: timestamp
                   8239: # end: timestamp
                   8240: #
1.240     www      8241:     my ($uname,$udom,%filters)=@_;
                   8242:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8243: }
                   8244: 
1.506     raeburn  8245: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8246: 
                   8247: sub auto_run {
1.508     raeburn  8248:     my ($cnum,$cdom) = @_;
1.876     raeburn  8249:     my $response = 0;
                   8250:     my $settings;
                   8251:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8252:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8253:         $settings = $domconfig{'autoenroll'};
                   8254:         if ($settings->{'run'} eq '1') {
                   8255:             $response = 1;
                   8256:         }
                   8257:     } else {
1.934     raeburn  8258:         my $homeserver;
                   8259:         if (&is_course($cdom,$cnum)) {
                   8260:             $homeserver = &homeserver($cnum,$cdom);
                   8261:         } else {
                   8262:             $homeserver = &domain($cdom,'primary');
                   8263:         }
                   8264:         if ($homeserver ne 'no_host') {
                   8265:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8266:         }
1.876     raeburn  8267:     }
1.506     raeburn  8268:     return $response;
                   8269: }
1.776     albertel 8270: 
1.506     raeburn  8271: sub auto_get_sections {
1.508     raeburn  8272:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8273:     my $homeserver;
                   8274:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8275:         $homeserver = &homeserver($cnum,$cdom);
                   8276:     }
                   8277:     if (!defined($homeserver)) { 
                   8278:         if ($cdom =~ /^$match_domain$/) {
                   8279:             $homeserver = &domain($cdom,'primary');
                   8280:         }
                   8281:     }
                   8282:     my @secs;
                   8283:     if (defined($homeserver)) {
                   8284:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8285:         unless ($response eq 'refused') {
                   8286:             @secs = split(/:/,$response);
                   8287:         }
1.506     raeburn  8288:     }
                   8289:     return @secs;
                   8290: }
1.776     albertel 8291: 
1.506     raeburn  8292: sub auto_new_course {
1.1099    raeburn  8293:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8294:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8295:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8296:     return $response;
                   8297: }
1.776     albertel 8298: 
1.506     raeburn  8299: sub auto_validate_courseID {
1.508     raeburn  8300:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8301:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8302:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8303:     return $response;
                   8304: }
1.776     albertel 8305: 
1.1007    raeburn  8306: sub auto_validate_instcode {
1.1020    raeburn  8307:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8308:     my ($homeserver,$response);
                   8309:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8310:         $homeserver = &homeserver($cnum,$cdom);
                   8311:     }
                   8312:     if (!defined($homeserver)) {
                   8313:         if ($cdom =~ /^$match_domain$/) {
                   8314:             $homeserver = &domain($cdom,'primary');
                   8315:         }
                   8316:     }
1.1065    raeburn  8317:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8318:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8319:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8320:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8321: }
                   8322: 
1.506     raeburn  8323: sub auto_create_password {
1.873     raeburn  8324:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8325:     my ($homeserver,$response);
1.506     raeburn  8326:     my $create_passwd = 0;
                   8327:     my $authchk = '';
1.873     raeburn  8328:     if ($udom =~ /^$match_domain$/) {
                   8329:         $homeserver = &domain($udom,'primary');
                   8330:     }
                   8331:     if ($homeserver eq '') {
                   8332:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8333:             $homeserver = &homeserver($cnum,$cdom);
                   8334:         }
                   8335:     }
                   8336:     if ($homeserver eq '') {
                   8337:         $authchk = 'nodomain';
1.506     raeburn  8338:     } else {
1.873     raeburn  8339:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8340:         if ($response eq 'refused') {
                   8341:             $authchk = 'refused';
                   8342:         } else {
1.901     albertel 8343:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8344:         }
1.506     raeburn  8345:     }
                   8346:     return ($authparam,$create_passwd,$authchk);
                   8347: }
                   8348: 
1.706     raeburn  8349: sub auto_photo_permission {
                   8350:     my ($cnum,$cdom,$students) = @_;
                   8351:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8352:     my ($outcome,$perm_reqd,$conditions) = 
                   8353: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8354:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8355: 	return (undef,undef);
                   8356:     }
1.706     raeburn  8357:     return ($outcome,$perm_reqd,$conditions);
                   8358: }
                   8359: 
                   8360: sub auto_checkphotos {
                   8361:     my ($uname,$udom,$pid) = @_;
                   8362:     my $homeserver = &homeserver($uname,$udom);
                   8363:     my ($result,$resulttype);
                   8364:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8365: 				   &escape($uname).':'.&escape($pid),
                   8366: 				   $homeserver));
1.709     albertel 8367:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8368: 	return (undef,undef);
                   8369:     }
1.706     raeburn  8370:     if ($outcome) {
                   8371:         ($result,$resulttype) = split(/:/,$outcome);
                   8372:     } 
                   8373:     return ($result,$resulttype);
                   8374: }
                   8375: 
                   8376: sub auto_photochoice {
                   8377:     my ($cnum,$cdom) = @_;
                   8378:     my $homeserver = &homeserver($cnum,$cdom);
                   8379:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8380: 						       &escape($cdom),
                   8381: 						       $homeserver)));
1.709     albertel 8382:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8383: 	return (undef,undef);
                   8384:     }
1.706     raeburn  8385:     return ($update,$comment);
                   8386: }
                   8387: 
                   8388: sub auto_photoupdate {
                   8389:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8390:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8391:     my $host=&hostname($homeserver);
1.706     raeburn  8392:     my $cmd = '';
                   8393:     my $maxtries = 1;
1.800     albertel 8394:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8395:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8396:     }
                   8397:     $cmd =~ s/%%$//;
                   8398:     $cmd = &escape($cmd);
                   8399:     my $query = 'institutionalphotos';
                   8400:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8401:     unless ($queryid=~/^\Q$host\E\_/) {
                   8402:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8403:         return 'error: '.$queryid;
                   8404:     }
                   8405:     my $reply = &get_query_reply($queryid);
                   8406:     my $tries = 1;
                   8407:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8408:         $reply = &get_query_reply($queryid);
                   8409:         $tries ++;
                   8410:     }
                   8411:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8412:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8413:     } else {
                   8414:         my @responses = split(/:/,$reply);
                   8415:         my $outcome = shift(@responses); 
                   8416:         foreach my $item (@responses) {
                   8417:             my ($key,$value) = split(/=/,$item);
                   8418:             $$photo{$key} = $value;
                   8419:         }
                   8420:         return $outcome;
                   8421:     }
                   8422:     return 'error';
                   8423: }
                   8424: 
1.521     raeburn  8425: sub auto_instcode_format {
1.793     albertel 8426:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8427: 	$cat_order) = @_;
1.521     raeburn  8428:     my $courses = '';
1.772     raeburn  8429:     my @homeservers;
1.521     raeburn  8430:     if ($caller eq 'global') {
1.841     albertel 8431: 	my %servers = &get_servers($codedom,'library');
                   8432: 	foreach my $tryserver (keys(%servers)) {
                   8433: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8434: 		push(@homeservers,$tryserver);
                   8435: 	    }
1.584     raeburn  8436:         }
1.1022    raeburn  8437:     } elsif ($caller eq 'requests') {
                   8438:         if ($codedom =~ /^$match_domain$/) {
                   8439:             my $chome = &domain($codedom,'primary');
                   8440:             unless ($chome eq 'no_host') {
                   8441:                 push(@homeservers,$chome);
                   8442:             }
                   8443:         }
1.521     raeburn  8444:     } else {
1.772     raeburn  8445:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8446:     }
1.793     albertel 8447:     foreach my $code (keys(%{$instcodes})) {
                   8448:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8449:     }
                   8450:     chop($courses);
1.772     raeburn  8451:     my $ok_response = 0;
                   8452:     my $response;
                   8453:     while (@homeservers > 0 && $ok_response == 0) {
                   8454:         my $server = shift(@homeservers); 
                   8455:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8456:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8457:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8458: 		split(/:/,$response);
1.772     raeburn  8459:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8460:             push(@{$codetitles},&str2array($codetitles_str));
                   8461:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8462:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8463:             $ok_response = 1;
                   8464:         }
                   8465:     }
                   8466:     if ($ok_response) {
1.521     raeburn  8467:         return 'ok';
1.772     raeburn  8468:     } else {
                   8469:         return $response;
1.521     raeburn  8470:     }
                   8471: }
                   8472: 
1.792     raeburn  8473: sub auto_instcode_defaults {
                   8474:     my ($domain,$returnhash,$code_order) = @_;
                   8475:     my @homeservers;
1.841     albertel 8476: 
                   8477:     my %servers = &get_servers($domain,'library');
                   8478:     foreach my $tryserver (keys(%servers)) {
                   8479: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8480: 	    push(@homeservers,$tryserver);
                   8481: 	}
1.792     raeburn  8482:     }
1.841     albertel 8483: 
1.792     raeburn  8484:     my $response;
1.841     albertel 8485:     foreach my $server (@homeservers) {
1.792     raeburn  8486:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8487:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8488: 	
                   8489: 	foreach my $pair (split(/\&/,$response)) {
                   8490: 	    my ($name,$value)=split(/\=/,$pair);
                   8491: 	    if ($name eq 'code_order') {
                   8492: 		@{$code_order} = split(/\&/,&unescape($value));
                   8493: 	    } else {
                   8494: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8495: 	    }
                   8496: 	}
                   8497: 	return 'ok';
1.792     raeburn  8498:     }
1.841     albertel 8499: 
                   8500:     return $response;
1.1003    raeburn  8501: }
                   8502: 
                   8503: sub auto_possible_instcodes {
1.1007    raeburn  8504:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8505:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8506:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8507:         return;
                   8508:     }
1.1003    raeburn  8509:     my (@homeservers,$uhome);
                   8510:     if (defined(&domain($domain,'primary'))) {
                   8511:         $uhome=&domain($domain,'primary');
                   8512:         push(@homeservers,&domain($domain,'primary'));
                   8513:     } else {
                   8514:         my %servers = &get_servers($domain,'library');
                   8515:         foreach my $tryserver (keys(%servers)) {
                   8516:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8517:                 push(@homeservers,$tryserver);
                   8518:             }
                   8519:         }
                   8520:     }
                   8521:     my $response;
                   8522:     foreach my $server (@homeservers) {
                   8523:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8524:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8525:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8526:             split(':',$response);
                   8527:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8528:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8529:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8530:             my ($name,$value)=split('=',$item);
                   8531:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8532:         }
                   8533:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8534:             my ($name,$value)=split('=',$item);
                   8535:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8536:         }
                   8537:         return 'ok';
                   8538:     }
                   8539:     return $response;
                   8540: }
1.792     raeburn  8541: 
1.1010    raeburn  8542: sub auto_courserequest_checks {
                   8543:     my ($dom) = @_;
1.1020    raeburn  8544:     my ($homeserver,%validations);
                   8545:     if ($dom =~ /^$match_domain$/) {
                   8546:         $homeserver = &domain($dom,'primary');
                   8547:     }
                   8548:     unless ($homeserver eq 'no_host') {
                   8549:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8550:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8551:             my @items = split(/&/,$response);
                   8552:             foreach my $item (@items) {
                   8553:                 my ($key,$value) = split('=',$item);
                   8554:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8555:             }
                   8556:         }
                   8557:     }
1.1010    raeburn  8558:     return %validations; 
                   8559: }
                   8560: 
1.1020    raeburn  8561: sub auto_courserequest_validation {
1.1255    raeburn  8562:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8563:     my ($homeserver,$response);
                   8564:     if ($dom =~ /^$match_domain$/) {
                   8565:         $homeserver = &domain($dom,'primary');
                   8566:     }
1.1255    raeburn  8567:     unless ($homeserver eq 'no_host') {
                   8568:         my $customdata;
                   8569:         if (ref($custominfo) eq 'HASH') {
                   8570:             $customdata = &freeze_escape($custominfo);
                   8571:         }
1.1020    raeburn  8572:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8573:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8574:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8575:                                     $customdata,$homeserver));
1.1020    raeburn  8576:     }
                   8577:     return $response;
                   8578: }
                   8579: 
1.777     albertel 8580: sub auto_validate_class_sec {
1.918     raeburn  8581:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8582:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8583:     my $ownerlist;
                   8584:     if (ref($owners) eq 'ARRAY') {
                   8585:         $ownerlist = join(',',@{$owners});
                   8586:     } else {
                   8587:         $ownerlist = $owners;
                   8588:     }
1.773     raeburn  8589:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8590:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8591:     return $response;
                   8592: }
                   8593: 
1.1248    raeburn  8594: sub auto_crsreq_update {
                   8595:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8596:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8597:     my ($homeserver,%crsreqresponse);
                   8598:     if ($cdom =~ /^$match_domain$/) {
                   8599:         $homeserver = &domain($cdom,'primary');
                   8600:     }
                   8601:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8602:         my $info;
                   8603:         if (ref($inbound) eq 'HASH') {
                   8604:             $info = &freeze_escape($inbound);
                   8605:         }
                   8606:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8607:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8608:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8609:                             &escape($title).':'.&escape($code).':'.
                   8610:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8611:                             $homeserver);
1.1248    raeburn  8612:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8613:             my @items = split(/&/,$response);
                   8614:             foreach my $item (@items) {
                   8615:                 my ($key,$value) = split('=',$item);
                   8616:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8617:             }
                   8618:         }
                   8619:     }
                   8620:     return \%crsreqresponse;
                   8621: }
                   8622: 
1.1305    raeburn  8623: sub auto_export_grades {
1.1309    raeburn  8624:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8625:     my ($homeserver,%exportresponse);
                   8626:     if ($cdom =~ /^$match_domain$/) {
                   8627:         $homeserver = &domain($cdom,'primary');
                   8628:     }
                   8629:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8630:         my $info;
                   8631:         if (ref($inforef) eq 'HASH') {
                   8632:             $info = &freeze_escape($inforef);
                   8633:         }
                   8634:         if (ref($gradesref) eq 'HASH') {
                   8635:             my $grades = &freeze_escape($gradesref);
                   8636:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8637:                                 $info.':'.$grades,$homeserver);
                   8638:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8639:                 my @items = split(/&/,$response);
                   8640:                 foreach my $item (@items) {
                   8641:                     my ($key,$value) = split('=',$item);
                   8642:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8643:                 }
                   8644:             }
                   8645:         }
                   8646:     }
                   8647:     return \%exportresponse;
1.1305    raeburn  8648: }
                   8649: 
1.1287    raeburn  8650: sub check_instcode_cloning {
                   8651:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8652:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8653:         return;
                   8654:     }
                   8655:     my $canclone;
                   8656:     if (@{$code_order} > 0) {
                   8657:         my $instcoderegexp ='^';
                   8658:         my @clonecodes = split(/\&/,$cloner);
                   8659:         foreach my $item (@{$code_order}) {
                   8660:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8661:                 foreach my $pair (@clonecodes) {
                   8662:                     my ($key,$val) = split(/\=/,$pair,2);
                   8663:                     $val = &unescape($val);
                   8664:                     if ($key eq $item) {
                   8665:                         $instcoderegexp .= '('.$val.')';
                   8666:                         last;
                   8667:                     }
                   8668:                 }
                   8669:             } else {
                   8670:                 $instcoderegexp .= $codedefaults->{$item};
                   8671:             }
                   8672:         }
                   8673:         $instcoderegexp .= '$';
                   8674:         my (@from,@to);
                   8675:         eval {
                   8676:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8677:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8678:         };
                   8679:         if ((@from > 0) && (@to > 0)) {
                   8680:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8681:             if (!@diffs) {
                   8682:                 $canclone = 1;
                   8683:             }
                   8684:         }
                   8685:     }
                   8686:     return $canclone;
                   8687: }
                   8688: 
                   8689: sub default_instcode_cloning {
                   8690:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8691:     my (%codedefaults,@code_order,$canclone);
                   8692:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8693:         %codedefaults = %{$codedefaultsref};
                   8694:         @code_order = @{$codeorderref};
                   8695:     } elsif ($clonedom) {
                   8696:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8697:     }
                   8698:     if (($domdefclone) && (@code_order)) {
                   8699:         my @clonecodes = split(/\+/,$domdefclone);
                   8700:         my $instcoderegexp ='^';
                   8701:         foreach my $item (@code_order) {
                   8702:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8703:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8704:             } else {
                   8705:                 $instcoderegexp .= $codedefaults{$item};
                   8706:             }
                   8707:         }
                   8708:         $instcoderegexp .= '$';
                   8709:         my (@from,@to);
                   8710:         eval {
                   8711:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8712:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8713:         };
                   8714:         if ((@from > 0) && (@to > 0)) {
                   8715:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8716:             if (!@diffs) {
                   8717:                 $canclone = 1;
                   8718:             }
                   8719:         }
                   8720:     }
                   8721:     return $canclone;
                   8722: }
                   8723: 
1.679     raeburn  8724: # ------------------------------------------------------- Course Group routines
                   8725: 
                   8726: sub get_coursegroups {
1.809     raeburn  8727:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8728:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8729: }
                   8730: 
1.679     raeburn  8731: sub modify_coursegroup {
                   8732:     my ($cdom,$cnum,$groupsettings) = @_;
                   8733:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8734: }
                   8735: 
1.809     raeburn  8736: sub toggle_coursegroup_status {
                   8737:     my ($cdom,$cnum,$group,$action) = @_;
                   8738:     my ($from_namespace,$to_namespace);
                   8739:     if ($action eq 'delete') {
                   8740:         $from_namespace = 'coursegroups';
                   8741:         $to_namespace = 'deleted_groups';
                   8742:     } else {
                   8743:         $from_namespace = 'deleted_groups';
                   8744:         $to_namespace = 'coursegroups';
                   8745:     }
                   8746:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8747:     if (my $tmp = &error(%curr_group)) {
                   8748:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8749:         return ('read error',$tmp);
                   8750:     } else {
                   8751:         my %savedsettings = %curr_group; 
1.809     raeburn  8752:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8753:         my $deloutcome;
                   8754:         if ($result eq 'ok') {
1.809     raeburn  8755:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8756:         } else {
                   8757:             return ('write error',$result);
                   8758:         }
                   8759:         if ($deloutcome eq 'ok') {
                   8760:             return 'ok';
                   8761:         } else {
                   8762:             return ('delete error',$deloutcome);
                   8763:         }
                   8764:     }
                   8765: }
                   8766: 
1.679     raeburn  8767: sub modify_group_roles {
1.957     raeburn  8768:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8769:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8770:     my $role = 'gr/'.&escape($userprivs);
                   8771:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8772:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8773:     if ($result eq 'ok') {
                   8774:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8775:     }
1.679     raeburn  8776:     return $result;
                   8777: }
                   8778: 
                   8779: sub modify_coursegroup_membership {
                   8780:     my ($cdom,$cnum,$membership) = @_;
                   8781:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8782:     return $result;
                   8783: }
                   8784: 
1.682     raeburn  8785: sub get_active_groups {
                   8786:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8787:     my $now = time;
                   8788:     my %groups = ();
                   8789:     foreach my $key (keys(%env)) {
1.811     albertel 8790:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8791:             my ($start,$end) = split(/\./,$env{$key});
                   8792:             if (($end!=0) && ($end<$now)) { next; }
                   8793:             if (($start!=0) && ($start>$now)) { next; }
                   8794:             if ($1 eq $cdom && $2 eq $cnum) {
                   8795:                 $groups{$3} = $env{$key} ;
                   8796:             }
                   8797:         }
                   8798:     }
                   8799:     return %groups;
                   8800: }
                   8801: 
1.683     raeburn  8802: sub get_group_membership {
                   8803:     my ($cdom,$cnum,$group) = @_;
                   8804:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8805: }
                   8806: 
                   8807: sub get_users_groups {
                   8808:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8809:     my @usersgroups;
1.683     raeburn  8810:     my $cachetime=1800;
                   8811: 
                   8812:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8813:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8814:     if (defined($cached)) {
1.734     albertel 8815:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8816:     } else {  
                   8817:         $grouplist = '';
1.816     raeburn  8818:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8819:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8820:         my $access_end = $env{'course.'.$courseid.
                   8821:                               '.default_enrollment_end_date'};
                   8822:         my $now = time;
                   8823:         foreach my $key (keys(%roleshash)) {
                   8824:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8825:                 my $group = $1;
                   8826:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8827:                     my $start = $2;
                   8828:                     my $end = $1;
                   8829:                     if ($start == -1) { next; } # deleted from group
                   8830:                     if (($start!=0) && ($start>$now)) { next; }
                   8831:                     if (($end!=0) && ($end<$now)) {
                   8832:                         if ($access_end && $access_end < $now) {
                   8833:                             if ($access_end - $end < 86400) {
                   8834:                                 push(@usersgroups,$group);
1.733     raeburn  8835:                             }
                   8836:                         }
1.817     raeburn  8837:                         next;
1.733     raeburn  8838:                     }
1.817     raeburn  8839:                     push(@usersgroups,$group);
1.683     raeburn  8840:                 }
                   8841:             }
                   8842:         }
1.817     raeburn  8843:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8844:         $grouplist = join(':',@usersgroups);
                   8845:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8846:     }
1.733     raeburn  8847:     return @usersgroups;
1.683     raeburn  8848: }
                   8849: 
                   8850: sub devalidate_getgroups_cache {
                   8851:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8852:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8853: 
1.683     raeburn  8854:     my $hashid="$udom:$uname:$courseid";
                   8855:     &devalidate_cache_new('getgroups',$hashid);
                   8856: }
                   8857: 
1.12      www      8858: # ------------------------------------------------------------------ Plain Text
                   8859: 
                   8860: sub plaintext {
1.988     raeburn  8861:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8862:     if ($short =~ m{^cr/}) {
1.758     albertel 8863: 	return (split('/',$short))[-1];
                   8864:     }
1.742     raeburn  8865:     if (!defined($cid)) {
                   8866:         $cid = $env{'request.course.id'};
                   8867:     }
                   8868:     my %rolenames = (
1.1008    raeburn  8869:                       Course    => 'std',
                   8870:                       Community => 'alt1',
1.1305    raeburn  8871:                       Placement => 'std',
1.742     raeburn  8872:                     );
1.1037    raeburn  8873:     if ($cid ne '') {
                   8874:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8875:             unless ($forcedefault) {
                   8876:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8877:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8878:                 return &Apache::lonlocal::mt($roletext);
                   8879:             }
                   8880:         }
                   8881:     }
                   8882:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8883:         (defined($rolenames{$type})) && 
                   8884:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8885:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8886:     } elsif ($cid ne '') {
                   8887:         my $crstype = $env{'course.'.$cid.'.type'};
                   8888:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8889:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8890:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8891:         }
1.742     raeburn  8892:     }
1.1037    raeburn  8893:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8894: }
                   8895: 
                   8896: # ----------------------------------------------------------------- Assign Role
                   8897: 
                   8898: sub assignrole {
1.957     raeburn  8899:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   8900:         $context)=@_;
1.21      www      8901:     my $mrole;
                   8902:     if ($role =~ /^cr\//) {
1.393     www      8903:         my $cwosec=$url;
1.811     albertel 8904:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      8905: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  8906:            my $refused = 1;
                   8907:            if ($context eq 'requestcourses') {
                   8908:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   8909:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   8910:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   8911:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8912:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8913:                            if ($crsenv{'internal.courseowner'} eq
                   8914:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   8915:                                $refused = '';
                   8916:                            }
                   8917:                        }
                   8918:                    }
                   8919:                }
                   8920:            }
                   8921:            if ($refused) {
                   8922:                &logthis('Refused custom assignrole: '.
                   8923:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   8924:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   8925:                return 'refused';
                   8926:            }
1.104     www      8927:         }
1.21      www      8928:         $mrole='cr';
1.678     raeburn  8929:     } elsif ($role =~ /^gr\//) {
                   8930:         my $cwogrp=$url;
1.811     albertel 8931:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  8932:         unless (&allowed('mdg',$cwogrp)) {
                   8933:             &logthis('Refused group assignrole: '.
                   8934:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   8935:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   8936:             return 'refused';
                   8937:         }
                   8938:         $mrole='gr';
1.21      www      8939:     } else {
1.82      www      8940:         my $cwosec=$url;
1.811     albertel 8941:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  8942:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   8943:             my $refused;
                   8944:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   8945:                 if (!(&allowed('c'.$role,$url))) {
                   8946:                     $refused = 1;
                   8947:                 }
                   8948:             } else {
                   8949:                 $refused = 1;
                   8950:             }
1.947     raeburn  8951:             if ($refused) {
1.1045    raeburn  8952:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   8953:                 if (!$selfenroll && $context eq 'course') {
                   8954:                     my %crsenv;
                   8955:                     if ($role eq 'cc' || $role eq 'co') {
                   8956:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8957:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   8958:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   8959:                                 if ($crsenv{'internal.courseowner'} eq 
                   8960:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8961:                                     $refused = '';
                   8962:                                 }
                   8963:                             }
                   8964:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   8965:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   8966:                                 if ($crsenv{'internal.courseowner'} eq 
                   8967:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   8968:                                     $refused = '';
                   8969:                                 }
                   8970:                             }
                   8971:                         }
                   8972:                     }
                   8973:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  8974:                     $refused = '';
1.1017    raeburn  8975:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  8976:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  8977:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  8978:                         my $wrongcc;
                   8979:                         if ($cnum =~ /^$match_community$/) {
                   8980:                             $wrongcc = 1 if ($role eq 'cc');
                   8981:                         } else {
                   8982:                             $wrongcc = 1 if ($role eq 'co');
                   8983:                         }
                   8984:                         unless ($wrongcc) {
                   8985:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   8986:                             if ($crsenv{'internal.courseowner'} eq 
                   8987:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   8988:                                 $refused = '';
                   8989:                             }
1.1017    raeburn  8990:                         }
                   8991:                     }
1.1183    raeburn  8992:                 } elsif ($context eq 'requestauthor') {
                   8993:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   8994:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   8995:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   8996:                             $refused = '';
                   8997:                         } else {
                   8998:                             my %domdefaults = &get_domain_defaults($udom);
                   8999:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9000:                                 my $checkbystatus;
                   9001:                                 if ($env{'user.adv'}) { 
                   9002:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9003:                                     if ($disposition eq 'automatic') {
                   9004:                                         $refused = '';
                   9005:                                     } elsif ($disposition eq '') {
                   9006:                                         $checkbystatus = 1;
                   9007:                                     } 
                   9008:                                 } else {
                   9009:                                     $checkbystatus = 1;
                   9010:                                 }
                   9011:                                 if ($checkbystatus) {
                   9012:                                     if ($env{'environment.inststatus'}) {
                   9013:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9014:                                         foreach my $type (@inststatuses) {
                   9015:                                             if (($type ne '') &&
                   9016:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9017:                                                 $refused = '';
                   9018:                                             }
                   9019:                                         }
                   9020:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9021:                                         $refused = '';
                   9022:                                     }
                   9023:                                 }
                   9024:                             }
                   9025:                         }
                   9026:                     }
1.1017    raeburn  9027:                 }
                   9028:                 if ($refused) {
1.947     raeburn  9029:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9030:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9031: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9032:                     return 'refused';
                   9033:                 }
1.932     raeburn  9034:             }
1.1131    raeburn  9035:         } elsif ($role eq 'au') {
                   9036:             if ($url ne '/'.$udom.'/') {
                   9037:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9038:                          ' to assign author role for '.$uname.':'.$udom.
                   9039:                          ' in domain: '.$url.' refused (wrong domain).');
                   9040:                 return 'refused';
                   9041:             }
1.104     www      9042:         }
1.21      www      9043:         $mrole=$role;
                   9044:     }
1.620     albertel 9045:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9046:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9047:     if ($end) { $command.='_'.$end; }
1.21      www      9048:     if ($start) {
                   9049: 	if ($end) { 
1.81      www      9050:            $command.='_'.$start; 
1.21      www      9051:         } else {
1.81      www      9052:            $command.='_0_'.$start;
1.21      www      9053:         }
                   9054:     }
1.739     raeburn  9055:     my $origstart = $start;
                   9056:     my $origend = $end;
1.957     raeburn  9057:     my $delflag;
1.357     www      9058: # actually delete
                   9059:     if ($deleteflag) {
1.373     www      9060: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9061: # modify command to delete the role
1.620     albertel 9062:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9063:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9064: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9065: # set start and finish to negative values for userrolelog
                   9066:            $start=-1;
                   9067:            $end=-1;
1.957     raeburn  9068:            $delflag = 1;
1.357     www      9069:         }
                   9070:     }
                   9071: # send command
1.349     www      9072:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9073: # log new user role if status is ok
1.349     www      9074:     if ($answer eq 'ok') {
1.663     raeburn  9075: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9076:         if (($role eq 'cc') || ($role eq 'in') ||
                   9077:             ($role eq 'ep') || ($role eq 'ad') ||
                   9078:             ($role eq 'ta') || ($role eq 'st') ||
                   9079:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9080:             ($role eq 'co')) {
1.1200    raeburn  9081: # for course roles, perform group memberships changes triggered by role change.
                   9082:             unless ($role =~ /^gr/) {
                   9083:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9084:                                                  $origstart,$selfenroll,$context);
                   9085:             }
1.1184    raeburn  9086:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9087:                            $selfenroll,$context);
                   9088:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1327    raeburn  9089:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh')) {
1.1184    raeburn  9090:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9091:                            $context);
                   9092:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9093:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9094:                              $context); 
                   9095:         }
1.1053    raeburn  9096:         if ($role eq 'cc') {
                   9097:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9098:         }
1.349     www      9099:     }
                   9100:     return $answer;
1.169     harris41 9101: }
                   9102: 
1.1053    raeburn  9103: sub autoupdate_coowners {
                   9104:     my ($url,$end,$start,$uname,$udom) = @_;
                   9105:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9106:     if (($cdom ne '') && ($cnum ne '')) {
                   9107:         my $now = time;
                   9108:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9109:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9110:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9111:             my $instcode = $coursehash{'internal.coursecode'};
                   9112:             if ($instcode ne '') {
1.1056    raeburn  9113:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9114:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9115:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9116:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9117:                         if ($result eq 'valid') {
                   9118:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9119:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9120:                                     push(@newcoowners,$coowner);
                   9121:                                 }
                   9122:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9123:                                     push(@newcoowners,$uname.':'.$udom);
                   9124:                                 }
                   9125:                                 @newcoowners = sort(@newcoowners);
                   9126:                             } else {
                   9127:                                 push(@newcoowners,$uname.':'.$udom);
                   9128:                             }
                   9129:                         } else {
                   9130:                             if ($coursehash{'internal.co-owners'}) {
                   9131:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9132:                                     unless ($coowner eq $uname.':'.$udom) {
                   9133:                                         push(@newcoowners,$coowner);
                   9134:                                     }
                   9135:                                 }
                   9136:                                 unless (@newcoowners > 0) {
                   9137:                                     $delcoowners = 1;
                   9138:                                     $coowners = '';
                   9139:                                 }
                   9140:                             }
                   9141:                         }
                   9142:                         if (@newcoowners || $delcoowners) {
                   9143:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9144:                                             $delcoowners,@newcoowners);
                   9145:                         }
                   9146:                     }
                   9147:                 }
                   9148:             }
                   9149:         }
                   9150:     }
                   9151: }
                   9152: 
                   9153: sub store_coowners {
                   9154:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9155:     my $cid = $cdom.'_'.$cnum;
                   9156:     my ($coowners,$delresult,$putresult);
                   9157:     if (@newcoowners) {
                   9158:         $coowners = join(',',@newcoowners);
                   9159:         my %coownershash = (
                   9160:                             'internal.co-owners' => $coowners,
                   9161:                            );
                   9162:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9163:         if ($putresult eq 'ok') {
                   9164:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9165:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9166:             }
                   9167:         }
                   9168:     }
                   9169:     if ($delcoowners) {
                   9170:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9171:         if ($delresult eq 'ok') {
                   9172:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9173:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9174:             }
                   9175:         }
                   9176:     }
                   9177:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9178:         my %crsinfo =
                   9179:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9180:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9181:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9182:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9183:         }
                   9184:     }
                   9185: }
                   9186: 
1.169     harris41 9187: # -------------------------------------------------- Modify user authentication
1.197     www      9188: # Overrides without validation
                   9189: 
1.169     harris41 9190: sub modifyuserauth {
                   9191:     my ($udom,$uname,$umode,$upass)=@_;
                   9192:     my $uhome=&homeserver($uname,$udom);
1.197     www      9193:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9194:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9195:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9196:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9197:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9198: 		     &escape($upass),$uhome);
1.620     albertel 9199:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9200:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9201:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9202:     &log($udom,,$uname,$uhome,
1.620     albertel 9203:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9204:                                      $env{'user.name'}.', '.$umode.
1.197     www      9205:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9206:     unless ($reply eq 'ok') {
1.197     www      9207:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9208: 	return 'error: '.$reply;
                   9209:     }   
1.170     harris41 9210:     return 'ok';
1.80      www      9211: }
                   9212: 
1.81      www      9213: # --------------------------------------------------------------- Modify a user
1.80      www      9214: 
1.81      www      9215: sub modifyuser {
1.206     matthew  9216:     my ($udom,    $uname, $uid,
                   9217:         $umode,   $upass, $first,
                   9218:         $middle,  $last,  $gene,
1.1058    raeburn  9219:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9220:     $udom= &LONCAPA::clean_domain($udom);
                   9221:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9222:     my $showcandelete = 'none';
                   9223:     if (ref($candelete) eq 'ARRAY') {
                   9224:         if (@{$candelete} > 0) {
                   9225:             $showcandelete = join(', ',@{$candelete});
                   9226:         }
                   9227:     }
1.81      www      9228:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9229:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9230: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9231:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9232:                                      ' desiredhome not specified'). 
1.620     albertel 9233:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9234:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9235:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9236:     my $newuser;
                   9237:     if ($uhome eq 'no_host') {
                   9238:         $newuser = 1;
                   9239:     }
1.80      www      9240: # ----------------------------------------------------------------- Create User
1.406     albertel 9241:     if (($uhome eq 'no_host') && 
                   9242: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9243:         my $unhome='';
1.844     albertel 9244:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9245:             $unhome = $desiredhome;
1.620     albertel 9246: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9247: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9248:         } else { # load balancing routine for determining $unhome
1.81      www      9249:             my $loadm=10000000;
1.841     albertel 9250: 	    my %servers = &get_servers($udom,'library');
                   9251: 	    foreach my $tryserver (keys(%servers)) {
                   9252: 		my $answer=reply('load',$tryserver);
                   9253: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9254: 		    $loadm=$answer;
                   9255: 		    $unhome=$tryserver;
                   9256: 		}
1.80      www      9257: 	    }
                   9258:         }
                   9259:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9260: 	    return 'error: unable to find a home server for '.$uname.
                   9261:                    ' in domain '.$udom;
1.80      www      9262:         }
                   9263:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9264:                          &escape($upass),$unhome);
                   9265: 	unless ($reply eq 'ok') {
                   9266:             return 'error: '.$reply;
                   9267:         }   
1.230     stredwic 9268:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9269:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9270: 	    return 'error: unable verify users home machine.';
1.80      www      9271:         }
1.209     matthew  9272:     }   # End of creation of new user
1.80      www      9273: # ---------------------------------------------------------------------- Add ID
                   9274:     if ($uid) {
                   9275:        $uid=~tr/A-Z/a-z/;
                   9276:        my %uidhash=&idrget($udom,$uname);
1.196     www      9277:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9278:          && (!$forceid)) {
1.80      www      9279: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9280: 	      return 'error: user id "'.$uid.'" does not match '.
                   9281:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9282:           }
                   9283:        } else {
1.1300    raeburn  9284: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9285:        }
                   9286:     }
                   9287: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9288:     my @tmp=&get('environment',
1.899     raeburn  9289: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9290:                     'permanentemail','inststatus'],
1.134     albertel 9291: 		   $udom,$uname);
1.1075    raeburn  9292:     my (%names,%oldnames);
1.313     matthew  9293:     if ($tmp[0] =~ m/^error:.*/) { 
                   9294:         %names=(); 
                   9295:     } else {
                   9296:         %names = @tmp;
1.1075    raeburn  9297:         %oldnames = %names;
1.313     matthew  9298:     }
1.388     www      9299: #
1.1058    raeburn  9300: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9301: # of users did not contain them), do not overwrite existing values
                   9302: # unless field is in $candelete array ref.  
                   9303: #
                   9304: 
                   9305:     my @fields = ('firstname','middlename','lastname','generation',
                   9306:                   'permanentemail','id');
                   9307:     my %newvalues;
                   9308:     if (ref($candelete) eq 'ARRAY') {
                   9309:         foreach my $field (@fields) {
                   9310:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9311:                 if ($field eq 'firstname') {
                   9312:                     $names{$field} = $first;
                   9313:                 } elsif ($field eq 'middlename') {
                   9314:                     $names{$field} = $middle;
                   9315:                 } elsif ($field eq 'lastname') {
                   9316:                     $names{$field} = $last;
                   9317:                 } elsif ($field eq 'generation') { 
                   9318:                     $names{$field} = $gene;
                   9319:                 } elsif ($field eq 'permanentemail') {
                   9320:                     $names{$field} = $email;
                   9321:                 } elsif ($field eq 'id') {
                   9322:                     $names{$field}  = $uid;
                   9323:                 }
                   9324:             }
                   9325:         }
                   9326:     }
1.388     www      9327:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9328:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9329:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9330:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9331:     if ($email) {
                   9332:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9333:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9334:     }
1.899     raeburn  9335:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9336:     if (defined($inststatus)) {
                   9337:         $names{'inststatus'} = '';
                   9338:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9339:         if (ref($usertypes) eq 'HASH') {
                   9340:             my @okstatuses; 
                   9341:             foreach my $item (split(/:/,$inststatus)) {
                   9342:                 if (defined($usertypes->{$item})) {
                   9343:                     push(@okstatuses,$item);  
                   9344:                 }
                   9345:             }
                   9346:             if (@okstatuses) {
                   9347:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9348:             }
                   9349:         }
                   9350:     }
1.1075    raeburn  9351:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9352:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9353:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9354:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9355:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9356:     } else {
                   9357:         $logmsg .= ' during self creation';
                   9358:     }
1.1075    raeburn  9359:     my $changed;
                   9360:     if ($newuser) {
                   9361:         $changed = 1;
                   9362:     } else {
                   9363:         foreach my $field (@fields) {
                   9364:             if ($names{$field} ne $oldnames{$field}) {
                   9365:                 $changed = 1;
                   9366:                 last;
                   9367:             }
                   9368:         }
                   9369:     }
                   9370:     unless ($changed) {
                   9371:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9372:         &logthis($logmsg);
                   9373:         return 'ok';
                   9374:     }
                   9375:     my $reply = &put('environment', \%names, $udom,$uname);
                   9376:     if ($reply ne 'ok') { 
                   9377:         return 'error: '.$reply;
                   9378:     }
1.1087    raeburn  9379:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9380:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9381:     }
1.1075    raeburn  9382:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9383:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9384:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9385:     &logthis($logmsg);
1.134     albertel 9386:     return 'ok';
1.80      www      9387: }
                   9388: 
1.81      www      9389: # -------------------------------------------------------------- Modify student
1.80      www      9390: 
1.81      www      9391: sub modifystudent {
                   9392:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9393:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9394:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9395:     if (!$cid) {
1.620     albertel 9396: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9397: 	    return 'not_in_class';
                   9398: 	}
1.80      www      9399:     }
                   9400: # --------------------------------------------------------------- Make the user
1.81      www      9401:     my $reply=&modifyuser
1.209     matthew  9402: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9403:          $desiredhome,$email,$inststatus);
1.80      www      9404:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9405:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9406:     # student's environment
1.297     matthew  9407:     $uid = undef if (!$forceid);
1.455     albertel 9408:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9409:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9410:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9411:     return $reply;
                   9412: }
                   9413: 
                   9414: sub modify_student_enrollment {
1.1216    raeburn  9415:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9416:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9417:     my ($cdom,$cnum,$chome);
                   9418:     if (!$cid) {
1.620     albertel 9419: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9420: 	    return 'not_in_class';
                   9421: 	}
1.620     albertel 9422: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9423: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9424:     } else {
                   9425: 	($cdom,$cnum)=split(/_/,$cid);
                   9426:     }
1.620     albertel 9427:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9428:     if (!$chome) {
1.457     raeburn  9429: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9430:     }
1.455     albertel 9431:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9432:     # Make sure the user exists
1.81      www      9433:     my $uhome=&homeserver($uname,$udom);
                   9434:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9435: 	return 'error: no such user';
                   9436:     }
1.297     matthew  9437:     # Get student data if we were not given enough information
                   9438:     if (!defined($first)  || $first  eq '' || 
                   9439:         !defined($last)   || $last   eq '' || 
                   9440:         !defined($uid)    || $uid    eq '' || 
                   9441:         !defined($middle) || $middle eq '' || 
                   9442:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9443:         # They did not supply us with enough data to enroll the student, so
                   9444:         # we need to pick up more information.
1.297     matthew  9445:         my %tmp = &get('environment',
1.294     matthew  9446:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9447:                        ,$udom,$uname);
                   9448: 
1.800     albertel 9449:         #foreach my $key (keys(%tmp)) {
                   9450:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9451:         #}
1.294     matthew  9452:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9453:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9454:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9455:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9456:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9457:     }
1.556     albertel 9458:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9459:     my $user = "$uname:$udom";
                   9460:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9461:     my $reply=cput('classlist',
1.1148    raeburn  9462: 		   {$user => 
1.1314    raeburn  9463: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9464: 		   $cdom,$cnum);
1.1148    raeburn  9465:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9466:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9467:     } else { 
1.81      www      9468: 	return 'error: '.$reply;
                   9469:     }
1.297     matthew  9470:     # Add student role to user
1.83      www      9471:     my $uurl='/'.$cid;
1.81      www      9472:     $uurl=~s/\_/\//g;
                   9473:     if ($usec) {
                   9474: 	$uurl.='/'.$usec;
                   9475:     }
1.1148    raeburn  9476:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9477:                              $selfenroll,$context);
                   9478:     if ($result ne 'ok') {
                   9479:         if ($old_entry{$user} ne '') {
                   9480:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9481:         } else {
                   9482:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9483:         }
                   9484:     }
                   9485:     return $result; 
1.21      www      9486: }
                   9487: 
1.556     albertel 9488: sub format_name {
                   9489:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9490:     my $name;
                   9491:     if ($first ne 'lastname') {
                   9492: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9493:     } else {
                   9494: 	if ($lastname=~/\S/) {
                   9495: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9496: 	    $name=~s/\s+,/,/;
                   9497: 	} else {
                   9498: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9499: 	}
                   9500:     }
                   9501:     $name=~s/^\s+//;
                   9502:     $name=~s/\s+$//;
                   9503:     $name=~s/\s+/ /g;
                   9504:     return $name;
                   9505: }
                   9506: 
1.84      www      9507: # ------------------------------------------------- Write to course preferences
                   9508: 
                   9509: sub writecoursepref {
                   9510:     my ($courseid,%prefs)=@_;
                   9511:     $courseid=~s/^\///;
                   9512:     $courseid=~s/\_/\//g;
                   9513:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9514:     my $chome=homeserver($cnum,$cdomain);
                   9515:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9516: 	return 'error: no such course';
                   9517:     }
                   9518:     my $cstring='';
1.800     albertel 9519:     foreach my $pref (keys(%prefs)) {
                   9520: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9521:     }
1.84      www      9522:     $cstring=~s/\&$//;
                   9523:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9524: }
                   9525: 
                   9526: # ---------------------------------------------------------- Make/modify course
                   9527: 
                   9528: sub createcourse {
1.741     raeburn  9529:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9530:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9531:     $url=&declutter($url);
                   9532:     my $cid='';
1.1028    raeburn  9533:     if ($context eq 'requestcourses') {
                   9534:         my $can_create = 0;
                   9535:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9536:         if ($udom eq $ownerdom) {
                   9537:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9538:                                   $context)) {
                   9539:                 $can_create = 1;
                   9540:             }
                   9541:         } else {
                   9542:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9543:                                            $category);
                   9544:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9545:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9546:                 if (@curr > 0) {
                   9547:                     my @options = qw(approval validate autolimit);
                   9548:                     my $optregex = join('|',@options);
                   9549:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9550:                         $can_create = 1;
                   9551:                     }
                   9552:                 }
                   9553:             }
                   9554:         }
                   9555:         if ($can_create) {
                   9556:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9557:                 unless (&allowed('ccc',$udom)) {
                   9558:                     return 'refused'; 
                   9559:                 }
1.1017    raeburn  9560:             }
                   9561:         } else {
                   9562:             return 'refused';
                   9563:         }
1.1028    raeburn  9564:     } elsif (!&allowed('ccc',$udom)) {
                   9565:         return 'refused';
1.84      www      9566:     }
1.1011    raeburn  9567: # --------------------------------------------------------------- Get Unique ID
                   9568:     my $uname;
                   9569:     if ($cnum =~ /^$match_courseid$/) {
                   9570:         my $chome=&homeserver($cnum,$udom,'true');
                   9571:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9572:             $uname = $cnum;
                   9573:         } else {
1.1038    raeburn  9574:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9575:         }
                   9576:     } else {
1.1038    raeburn  9577:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9578:     }
                   9579:     return $uname if ($uname =~ /^error/);
                   9580: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9581:     if (!defined($course_server)) {
                   9582:         if (defined(&domain($udom,'primary'))) {
                   9583:             $course_server = &domain($udom,'primary');
                   9584:         } else {
                   9585:             $course_server = $env{'user.home'}; 
                   9586:         }
                   9587:     }
                   9588:     my %host_servers =
                   9589:         &Apache::lonnet::get_servers($udom,'library');
                   9590:     unless ($host_servers{$course_server}) {
                   9591:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9592:     }
1.84      www      9593: # ------------------------------------------------------------- Make the course
                   9594:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9595:                       $course_server);
1.84      www      9596:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9597:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9598:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9599: 	return 'error: no such course';
                   9600:     }
1.271     www      9601: # ----------------------------------------------------------------- Course made
1.516     raeburn  9602: # log existence
1.1029    raeburn  9603:     my $now = time;
1.918     raeburn  9604:     my $newcourse = {
                   9605:                     $udom.'_'.$uname => {
1.921     raeburn  9606:                                      description => $description,
                   9607:                                      inst_code   => $inst_code,
                   9608:                                      owner       => $course_owner,
                   9609:                                      type        => $crstype,
1.1029    raeburn  9610:                                      creator     => $env{'user.name'}.':'.
                   9611:                                                     $env{'user.domain'},
                   9612:                                      created     => $now,
                   9613:                                      context     => $context,
1.918     raeburn  9614:                                                 },
                   9615:                     };
1.921     raeburn  9616:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9617: # set toplevel url
1.271     www      9618:     my $topurl=$url;
                   9619:     unless ($nonstandard) {
                   9620: # ------------------------------------------ For standard courses, make top url
                   9621:         my $mapurl=&clutter($url);
1.278     www      9622:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9623:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9624: <map>
                   9625: <resource id="1" type="start"></resource>
                   9626: <resource id="2" src="$mapurl"></resource>
                   9627: <resource id="3" type="finish"></resource>
                   9628: <link index="1" from="1" to="2"></link>
                   9629: <link index="2" from="2" to="3"></link>
                   9630: </map>
                   9631: ENDINITMAP
                   9632:         $topurl=&declutter(
1.638     albertel 9633:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9634:                           );
                   9635:     }
                   9636: # ----------------------------------------------------------- Write preferences
1.84      www      9637:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9638:                      ('description'              => $description,
                   9639:                       'url'                      => $topurl,
                   9640:                       'internal.creator'         => $env{'user.name'}.':'.
                   9641:                                                     $env{'user.domain'},
                   9642:                       'internal.created'         => $now,
                   9643:                       'internal.creationcontext' => $context)
                   9644:                     );
1.84      www      9645:     return '/'.$udom.'/'.$uname;
                   9646: }
                   9647: 
1.1011    raeburn  9648: # ------------------------------------------------------------------- Create ID
                   9649: sub generate_coursenum {
1.1038    raeburn  9650:     my ($udom,$crstype) = @_;
1.1011    raeburn  9651:     my $domdesc = &domain($udom);
                   9652:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9653:     my $first;
                   9654:     if ($crstype eq 'Community') {
                   9655:         $first = '0';
                   9656:     } else {
                   9657:         $first = int(1+rand(9)); 
                   9658:     } 
                   9659:     my $uname=$first.
1.1011    raeburn  9660:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9661:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9662:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9663: # ----------------------------------------------- Make sure that does not exist
                   9664:     my $uhome=&homeserver($uname,$udom,'true');
                   9665:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9666:         if ($crstype eq 'Community') {
                   9667:             $first = '0';
                   9668:         } else {
                   9669:             $first = int(1+rand(9));
                   9670:         }
                   9671:         $uname=$first.
1.1011    raeburn  9672:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9673:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9674:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9675:         $uhome=&homeserver($uname,$udom,'true');
                   9676:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9677:             return 'error: unable to generate unique course-ID';
                   9678:         }
                   9679:     }
                   9680:     return $uname;
                   9681: }
                   9682: 
1.813     albertel 9683: sub is_course {
1.1167    droeschl 9684:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9685:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9686: 
                   9687:     return unless $cdom and $cnum;
                   9688: 
                   9689:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9690:         '.');
                   9691: 
1.1219    raeburn  9692:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9693:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9694: }
                   9695: 
1.1015    raeburn  9696: sub store_userdata {
                   9697:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9698:     my $result;
1.1016    raeburn  9699:     if ($datakey ne '') {
1.1013    raeburn  9700:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9701:             if ($udom eq '' || $uname eq '') {
                   9702:                 $udom = $env{'user.domain'};
                   9703:                 $uname = $env{'user.name'};
                   9704:             }
                   9705:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9706:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9707:                 $result = 'error: no_host';
                   9708:             } else {
                   9709:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9710:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9711: 
                   9712:                 my $namevalue='';
                   9713:                 foreach my $key (keys(%{$storehash})) {
                   9714:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9715:                 }
                   9716:                 $namevalue=~s/\&$//;
1.1224    raeburn  9717:                 unless ($namespace eq 'courserequests') {
                   9718:                     $datakey = &escape($datakey);
                   9719:                 }
1.1105    raeburn  9720:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9721:                                   $namevalue,$uhome);
1.1013    raeburn  9722:             }
                   9723:         } else {
                   9724:             $result = 'error: data to store was not a hash reference'; 
                   9725:         }
                   9726:     } else {
                   9727:         $result= 'error: invalid requestkey'; 
                   9728:     }
                   9729:     return $result;
                   9730: }
                   9731: 
1.21      www      9732: # ---------------------------------------------------------- Assign Custom Role
                   9733: 
                   9734: sub assigncustomrole {
1.957     raeburn  9735:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9736:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9737:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9738: }
                   9739: 
                   9740: # ----------------------------------------------------------------- Revoke Role
                   9741: 
                   9742: sub revokerole {
1.957     raeburn  9743:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9744:     my $now=time;
1.965     raeburn  9745:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9746: }
                   9747: 
                   9748: # ---------------------------------------------------------- Revoke Custom Role
                   9749: 
                   9750: sub revokecustomrole {
1.957     raeburn  9751:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9752:     my $now=time;
1.357     www      9753:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9754:            $deleteflag,$selfenroll,$context);
1.17      www      9755: }
                   9756: 
1.533     banghart 9757: # ------------------------------------------------------------ Disk usage
1.535     albertel 9758: sub diskusage {
1.955     raeburn  9759:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9760:     $directorypath =~ s/\/$//;
                   9761:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9762:                        .&escape($getpropath).':'.&escape($uname).':'
                   9763:                        .&escape($udom),homeserver($uname,$udom));
                   9764:     if ($listing eq 'unknown_cmd') {
                   9765:         if ($getpropath) {
                   9766:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9767:         }
                   9768:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9769:     }
1.514     albertel 9770:     return $listing;
1.512     banghart 9771: }
                   9772: 
1.566     banghart 9773: sub is_locked {
1.1096    raeburn  9774:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9775:     my @check;
                   9776:     my $is_locked;
1.1093    raeburn  9777:     push (@check,$file_name);
1.613     albertel 9778:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9779: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9780:     my ($tmp)=keys(%locked);
                   9781:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9782:     
1.566     banghart 9783:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9784:         $is_locked = 'false';
                   9785:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9786:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9787:                $is_locked = 'true';
1.1096    raeburn  9788:                if (ref($which) eq 'ARRAY') {
                   9789:                    push(@{$which},$entry);
                   9790:                } else {
                   9791:                    last;
                   9792:                }
1.745     raeburn  9793:            }
                   9794:        }
1.566     banghart 9795:     } else {
                   9796:         $is_locked = 'false';
                   9797:     }
1.1093    raeburn  9798:     return $is_locked;
1.566     banghart 9799: }
                   9800: 
1.759     albertel 9801: sub declutter_portfile {
                   9802:     my ($file) = @_;
1.833     albertel 9803:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9804:     return $file;
                   9805: }
                   9806: 
1.559     banghart 9807: # ------------------------------------------------------------- Mark as Read Only
                   9808: 
                   9809: sub mark_as_readonly {
                   9810:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9811:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9812:     my ($tmp)=keys(%current_permissions);
                   9813:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9814:     foreach my $file (@{$files}) {
1.759     albertel 9815: 	$file = &declutter_portfile($file);
1.561     banghart 9816:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9817:     }
1.613     albertel 9818:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9819:     return;
                   9820: }
                   9821: 
1.572     banghart 9822: # ------------------------------------------------------------Save Selected Files
                   9823: 
                   9824: sub save_selected_files {
                   9825:     my ($user, $path, @files) = @_;
                   9826:     my $filename = $user."savedfiles";
1.573     banghart 9827:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9828:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9829:     foreach my $file (@files) {
1.620     albertel 9830:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9831:     }
                   9832:     foreach my $file (@other_files) {
1.574     banghart 9833:         print (OUT $file."\n");
1.572     banghart 9834:     }
1.574     banghart 9835:     close (OUT);
1.572     banghart 9836:     return 'ok';
                   9837: }
                   9838: 
1.574     banghart 9839: sub clear_selected_files {
                   9840:     my ($user) = @_;
                   9841:     my $filename = $user."savedfiles";
1.1117    foxr     9842:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9843:     print (OUT undef);
                   9844:     close (OUT);
                   9845:     return ("ok");    
                   9846: }
                   9847: 
1.572     banghart 9848: sub files_in_path {
                   9849:     my ($user, $path) = @_;
                   9850:     my $filename = $user."savedfiles";
                   9851:     my %return_files;
1.1117    foxr     9852:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9853:     while (my $line_in = <IN>) {
1.574     banghart 9854:         chomp ($line_in);
                   9855:         my @paths_and_file = split (m!/!, $line_in);
                   9856:         my $file_part = pop (@paths_and_file);
                   9857:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9858:         $path_part.='/';
                   9859:         my $path_and_file = $path_part.$file_part;
                   9860:         if ($path_part eq $path) {
                   9861:             $return_files{$file_part}= 'selected';
                   9862:         }
                   9863:     }
1.574     banghart 9864:     close (IN);
                   9865:     return (\%return_files);
1.572     banghart 9866: }
                   9867: 
                   9868: # called in portfolio select mode, to show files selected NOT in current directory
                   9869: sub files_not_in_path {
                   9870:     my ($user, $path) = @_;
                   9871:     my $filename = $user."savedfiles";
                   9872:     my @return_files;
                   9873:     my $path_part;
1.1117    foxr     9874:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9875:     while (my $line = <IN>) {
1.572     banghart 9876:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9877:         my @paths_and_file = split(m|/|, $line);
                   9878:         my $file_part = pop(@paths_and_file);
                   9879:         chomp($file_part);
                   9880:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9881:         $path_part .= '/';
                   9882:         my $path_and_file = $path_part.$file_part;
                   9883:         if ($path_part ne $path) {
1.800     albertel 9884:             push(@return_files, ($path_and_file));
1.572     banghart 9885:         }
                   9886:     }
1.800     albertel 9887:     close(OUT);
1.574     banghart 9888:     return (@return_files);
1.572     banghart 9889: }
                   9890: 
1.1273    raeburn  9891: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9892:  
                   9893: sub portfiles_versioning {
                   9894:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   9895:     my $portfolio_root = '/userfiles/portfolio';
                   9896:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   9897:     foreach my $file (@{$portfiles}) {
                   9898:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   9899:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   9900:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   9901:         my $getpropath = 1;
                   9902:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   9903:                                              $stu_name,$getpropath);
                   9904:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   9905:         my $new_answer = 
                   9906:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   9907:         if ($new_answer ne 'problem getting file') {
                   9908:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   9909:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   9910:                               [$symb,$env{'request.course.id'},'graded']);
                   9911:         }
                   9912:     }
                   9913: }
                   9914: 
                   9915: sub get_next_version {
                   9916:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   9917:     my $version;
                   9918:     if (ref($dir_list) eq 'ARRAY') {
                   9919:         foreach my $row (@{$dir_list}) {
                   9920:             my ($file) = split(/\&/,$row,2);
                   9921:             my ($file_name,$file_version,$file_ext) =
                   9922:                 &file_name_version_ext($file);
                   9923:             if (($file_name eq $answer_name) &&
                   9924:                 ($file_ext eq $answer_ext)) {
                   9925:                      # gets here if filename and extension match,
                   9926:                      # regardless of version
                   9927:                 if ($file_version ne '') {
                   9928:                     # a versioned file is found  so save it for later
                   9929:                     if ($file_version > $version) {
                   9930:                         $version = $file_version;
                   9931:                     }
                   9932:                 }
                   9933:             }
                   9934:         }
                   9935:     }
                   9936:     $version ++;
                   9937:     return($version);
                   9938: }
                   9939: 
                   9940: sub version_selected_portfile {
                   9941:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   9942:     my ($answer_name,$answer_ver,$answer_ext) =
                   9943:         &file_name_version_ext($file_name);
                   9944:     my $new_answer;
                   9945:     $env{'form.copy'} =
                   9946:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   9947:     if($env{'form.copy'} eq '-1') {
                   9948:         $new_answer = 'problem getting file';
                   9949:     } else {
                   9950:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   9951:         my $copy_result = 
                   9952:             &finishuserfileupload($stu_name,$domain,'copy',
                   9953:                                   '/portfolio'.$directory.$new_answer);
                   9954:     }
                   9955:     undef($env{'form.copy'});
                   9956:     return ($new_answer);
                   9957: }
                   9958: 
                   9959: sub file_name_version_ext {
                   9960:     my ($file)=@_;
                   9961:     my @file_parts = split(/\./, $file);
                   9962:     my ($name,$version,$ext);
                   9963:     if (@file_parts > 1) {
                   9964:         $ext=pop(@file_parts);
                   9965:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   9966:             $version=pop(@file_parts);
                   9967:         }
                   9968:         $name=join('.',@file_parts);
                   9969:     } else {
                   9970:         $name=join('.',@file_parts);
                   9971:     }
                   9972:     return($name,$version,$ext);
                   9973: }
                   9974: 
1.745     raeburn  9975: #----------------------------------------------Get portfolio file permissions
1.629     banghart 9976: 
1.745     raeburn  9977: sub get_portfile_permissions {
                   9978:     my ($domain,$user) = @_;
1.613     albertel 9979:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9980:     my ($tmp)=keys(%current_permissions);
                   9981:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  9982:     return \%current_permissions;
                   9983: }
                   9984: 
                   9985: #---------------------------------------------Get portfolio file access controls
                   9986: 
1.749     raeburn  9987: sub get_access_controls {
1.745     raeburn  9988:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 9989:     my %access;
                   9990:     my $real_file = $file;
                   9991:     $file =~ s/\.meta$//;
1.745     raeburn  9992:     if (defined($file)) {
1.749     raeburn  9993:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   9994:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 9995:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  9996:             }
                   9997:         }
1.745     raeburn  9998:     } else {
1.749     raeburn  9999:         foreach my $key (keys(%{$current_permissions})) {
                   10000:             if ($key =~ /\0accesscontrol$/) {
                   10001:                 if (defined($group)) {
                   10002:                     if ($key !~ m-^\Q$group\E/-) {
                   10003:                         next;
                   10004:                     }
                   10005:                 }
                   10006:                 my ($fullpath) = split(/\0/,$key);
                   10007:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10008:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10009:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10010:                     }
                   10011:                 }
                   10012:             }
                   10013:         }
                   10014:     }
                   10015:     return %access;
                   10016: }
                   10017: 
                   10018: sub modify_access_controls {
                   10019:     my ($file_name,$changes,$domain,$user)=@_;
                   10020:     my ($outcome,$deloutcome);
                   10021:     my %store_permissions;
                   10022:     my %new_values;
                   10023:     my %new_control;
                   10024:     my %translation;
                   10025:     my @deletions = ();
                   10026:     my $now = time;
                   10027:     if (exists($$changes{'activate'})) {
                   10028:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10029:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10030:             my $numnew = scalar(@newitems);
                   10031:             for (my $i=0; $i<$numnew; $i++) {
                   10032:                 my $newkey = $newitems[$i];
                   10033:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10034:                 if ($newkey =~ /^\d+:/) { 
                   10035:                     $newkey =~ s/^(\d+)/$newid/;
                   10036:                     $translation{$1} = $newid;
                   10037:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10038:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10039:                     $translation{$1} = $newid;
                   10040:                 }
1.749     raeburn  10041:                 $new_values{$file_name."\0".$newkey} = 
                   10042:                                           $$changes{'activate'}{$newitems[$i]};
                   10043:                 $new_control{$newkey} = $now;
                   10044:             }
                   10045:         }
                   10046:     }
                   10047:     my %todelete;
                   10048:     my %changed_items;
                   10049:     foreach my $action ('delete','update') {
                   10050:         if (exists($$changes{$action})) {
                   10051:             if (ref($$changes{$action}) eq 'HASH') {
                   10052:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10053:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10054:                     if ($action eq 'delete') { 
                   10055:                         $todelete{$itemnum} = 1;
                   10056:                     } else {
                   10057:                         $changed_items{$itemnum} = $key;
                   10058:                     }
                   10059:                 }
1.745     raeburn  10060:             }
                   10061:         }
1.749     raeburn  10062:     }
                   10063:     # get lock on access controls for file.
                   10064:     my $lockhash = {
                   10065:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10066:                                                        ':'.$env{'user.domain'},
                   10067:                    }; 
                   10068:     my $tries = 0;
                   10069:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10070:    
1.1288    damieng  10071:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10072:         $tries ++;
1.1289    damieng  10073:         sleep(0.1);
1.749     raeburn  10074:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10075:     }
                   10076:     if ($gotlock eq 'ok') {
                   10077:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10078:         my ($tmp)=keys(%curr_permissions);
                   10079:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10080:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10081:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10082:             if (ref($curr_controls) eq 'HASH') {
                   10083:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10084:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10085:                     if (defined($todelete{$itemnum})) {
                   10086:                         push(@deletions,$file_name."\0".$control_item);
                   10087:                     } else {
                   10088:                         if (defined($changed_items{$itemnum})) {
                   10089:                             $new_control{$changed_items{$itemnum}} = $now;
                   10090:                             push(@deletions,$file_name."\0".$control_item);
                   10091:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10092:                         } else {
                   10093:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10094:                         }
                   10095:                     }
1.745     raeburn  10096:                 }
                   10097:             }
                   10098:         }
1.970     raeburn  10099:         my ($group);
                   10100:         if (&is_course($domain,$user)) {
                   10101:             ($group,my $file) = split(/\//,$file_name,2);
                   10102:         }
1.749     raeburn  10103:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10104:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10105:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10106:         #  remove lock
                   10107:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10108:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10109:         my $sqlresult =
1.970     raeburn  10110:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10111:                                     $group);
1.749     raeburn  10112:     } else {
                   10113:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10114:     }
1.749     raeburn  10115:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10116: }
                   10117: 
1.827     raeburn  10118: sub make_public_indefinitely {
1.1271    raeburn  10119:     my (@requrl) = @_;
                   10120:     return &automated_portfile_access('public',\@requrl);
                   10121: }
                   10122: 
                   10123: sub automated_portfile_access {
                   10124:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10125:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10126:         return 'invalid';
                   10127:     }
1.1271    raeburn  10128:     my %urls;
                   10129:     if (ref($addsref) eq 'ARRAY') {
                   10130:         foreach my $requrl (@{$addsref}) {
                   10131:             if (&is_portfolio_url($requrl)) {
                   10132:                 unless (exists($urls{$requrl})) {
                   10133:                     $urls{$requrl} = 'add';
                   10134:                 }
                   10135:             }
                   10136:         }
                   10137:     }
                   10138:     if (ref($delsref) eq 'ARRAY') {
                   10139:         foreach my $requrl (@{$delsref}) { 
                   10140:             if (&is_portfolio_url($requrl)) {
                   10141:                 unless (exists($urls{$requrl})) {
                   10142:                     $urls{$requrl} = 'delete'; 
                   10143:                 }
                   10144:             }
                   10145:         }
                   10146:     }
                   10147:     unless (keys(%urls)) {
                   10148:         return 'invalid';
                   10149:     }
                   10150:     my $ip;
                   10151:     if ($accesstype eq 'ip') {
                   10152:         if (ref($info) eq 'HASH') {
                   10153:             if ($info->{'ip'} ne '') {
                   10154:                 $ip = $info->{'ip'};
                   10155:             }
                   10156:         }
                   10157:         if ($ip eq '') {
                   10158:             return 'invalid';
                   10159:         }
                   10160:     }
                   10161:     my $errors;
1.827     raeburn  10162:     my $now = time;
1.1271    raeburn  10163:     my %current_perms;
                   10164:     foreach my $requrl (sort(keys(%urls))) {
                   10165:         my $action;
                   10166:         if ($urls{$requrl} eq 'add') {
                   10167:             $action = 'activate';
                   10168:         } else {
                   10169:             $action = 'none';
                   10170:         }
                   10171:         my $aclnum = 0;
1.827     raeburn  10172:         my (undef,$udom,$unum,$file_name,$group) =
                   10173:             &parse_portfolio_url($requrl);
1.1271    raeburn  10174:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10175:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10176:         }
                   10177:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10178:                                                    $group,$file_name);
                   10179:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10180:             my ($num,$scope,$end,$start) = 
                   10181:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10182:             if ($scope eq $accesstype) {
                   10183:                 if (($start <= $now) && ($end == 0)) {
                   10184:                     if ($accesstype eq 'ip') {
                   10185:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10186:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10187:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10188:                                     if ($urls{$requrl} eq 'add') {
                   10189:                                         $action = 'none';
                   10190:                                         last;
                   10191:                                     } else {
                   10192:                                         $action = 'delete';
                   10193:                                         $aclnum = $num;
                   10194:                                         last;
                   10195:                                     }
                   10196:                                 }
                   10197:                             }
                   10198:                         }
                   10199:                     } elsif ($accesstype eq 'public') {
                   10200:                         if ($urls{$requrl} eq 'add') {
                   10201:                             $action = 'none';
                   10202:                             last;
                   10203:                         } else {
                   10204:                             $action = 'delete';
                   10205:                             $aclnum = $num;
                   10206:                             last;
                   10207:                         }
                   10208:                     }
                   10209:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10210:                     $action = 'update';
                   10211:                     $aclnum = $num;
1.1271    raeburn  10212:                     last;
1.827     raeburn  10213:                 }
                   10214:             }
                   10215:         }
                   10216:         if ($action eq 'none') {
1.1271    raeburn  10217:             next;
1.827     raeburn  10218:         } else {
                   10219:             my %changes;
                   10220:             my $newend = 0;
                   10221:             my $newstart = $now;
1.1271    raeburn  10222:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10223:             $changes{$action}{$newkey} = {
1.1271    raeburn  10224:                 type => $accesstype,
1.827     raeburn  10225:                 time => {
                   10226:                     start => $newstart,
                   10227:                     end   => $newend,
                   10228:                 },
                   10229:             };
1.1271    raeburn  10230:             if ($accesstype eq 'ip') {
                   10231:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10232:             }
1.827     raeburn  10233:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10234:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10235:             unless ($outcome eq 'ok') {
                   10236:                 $errors .= $outcome.' ';
                   10237:             }
1.827     raeburn  10238:         }
1.1271    raeburn  10239:     }
                   10240:     if ($errors) {
                   10241:         $errors =~ s/\s$//;
                   10242:         return $errors;
1.827     raeburn  10243:     } else {
1.1271    raeburn  10244:         return 'ok';
1.827     raeburn  10245:     }
                   10246: }
                   10247: 
1.745     raeburn  10248: #------------------------------------------------------Get Marked as Read Only
                   10249: 
                   10250: sub get_marked_as_readonly {
                   10251:     my ($domain,$user,$what,$group) = @_;
                   10252:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10253:     my @readonly_files;
1.629     banghart 10254:     my $cmp1=$what;
                   10255:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10256:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10257:         if (defined($group)) {
                   10258:             if ($file_name !~ m-^\Q$group\E/-) {
                   10259:                 next;
                   10260:             }
                   10261:         }
1.561     banghart 10262:         if (ref($value) eq "ARRAY"){
                   10263:             foreach my $stored_what (@{$value}) {
1.629     banghart 10264:                 my $cmp2=$stored_what;
1.759     albertel 10265:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10266:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10267:                 }
1.629     banghart 10268:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10269:                     push(@readonly_files, $file_name);
1.745     raeburn  10270:                     last;
1.563     banghart 10271:                 } elsif (!defined($what)) {
                   10272:                     push(@readonly_files, $file_name);
1.745     raeburn  10273:                     last;
1.561     banghart 10274:                 }
                   10275:             }
1.745     raeburn  10276:         }
1.561     banghart 10277:     }
                   10278:     return @readonly_files;
                   10279: }
1.577     banghart 10280: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10281: 
1.577     banghart 10282: sub get_marked_as_readonly_hash {
1.745     raeburn  10283:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10284:     my %readonly_files;
1.745     raeburn  10285:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10286:         if (defined($group)) {
                   10287:             if ($file_name !~ m-^\Q$group\E/-) {
                   10288:                 next;
                   10289:             }
                   10290:         }
1.577     banghart 10291:         if (ref($value) eq "ARRAY"){
                   10292:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10293:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10294:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10295:                         if ($lock_descriptor eq 'graded') {
                   10296:                             $readonly_files{$file_name} = 'graded';
                   10297:                         } elsif ($lock_descriptor eq 'handback') {
                   10298:                             $readonly_files{$file_name} = 'handback';
                   10299:                         } else {
                   10300:                             if (!exists($readonly_files{$file_name})) {
                   10301:                                 $readonly_files{$file_name} = 'locked';
                   10302:                             }
                   10303:                         }
1.745     raeburn  10304:                     }
1.750     banghart 10305:                 } 
1.577     banghart 10306:             }
                   10307:         } 
                   10308:     }
                   10309:     return %readonly_files;
                   10310: }
1.559     banghart 10311: # ------------------------------------------------------------ Unmark as Read Only
                   10312: 
                   10313: sub unmark_as_readonly {
1.629     banghart 10314:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10315:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10316:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10317:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10318:     my $symb_crs = $what;
                   10319:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10320:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10321:     my ($tmp)=keys(%current_permissions);
                   10322:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10323:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10324:     foreach my $file (@readonly_files) {
1.759     albertel 10325: 	my $clean_file = &declutter_portfile($file);
                   10326: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10327: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10328:         my @new_locks;
                   10329:         my @del_keys;
                   10330:         if (ref($current_locks) eq "ARRAY"){
                   10331:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10332:                 my $compare=$locker;
1.749     raeburn  10333:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10334:                     $compare=join('',@{$locker});
1.746     raeburn  10335:                     if ($compare ne $symb_crs) {
                   10336:                         push(@new_locks, $locker);
                   10337:                     }
1.563     banghart 10338:                 }
                   10339:             }
1.650     albertel 10340:             if (scalar(@new_locks) > 0) {
1.563     banghart 10341:                 $current_permissions{$file} = \@new_locks;
                   10342:             } else {
                   10343:                 push(@del_keys, $file);
1.613     albertel 10344:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10345:                 delete($current_permissions{$file});
1.563     banghart 10346:             }
                   10347:         }
1.561     banghart 10348:     }
1.613     albertel 10349:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10350:     return;
                   10351: }
1.512     banghart 10352: 
1.17      www      10353: # ------------------------------------------------------------ Directory lister
                   10354: 
                   10355: sub dirlist {
1.955     raeburn  10356:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10357:     $uri=~s/^\///;
                   10358:     $uri=~s/\/$//;
1.253     stredwic 10359:     my ($udom, $uname);
1.955     raeburn  10360:     if ($getuserdir) {
1.253     stredwic 10361:         $udom = $userdomain;
                   10362:         $uname = $username;
1.955     raeburn  10363:     } else {
                   10364:         (undef,$udom,$uname)=split(/\//,$uri);
                   10365:         if(defined($userdomain)) {
                   10366:             $udom = $userdomain;
                   10367:         }
                   10368:         if(defined($username)) {
                   10369:             $uname = $username;
                   10370:         }
1.253     stredwic 10371:     }
1.955     raeburn  10372:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10373: 
1.955     raeburn  10374:     $dirRoot = $perlvar{'lonDocRoot'};
                   10375:     if (defined($getpropath)) {
                   10376:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10377:         $dirRoot =~ s/\/$//;
1.955     raeburn  10378:     } elsif (defined($getuserdir)) {
                   10379:         my $subdir=$uname.'__';
                   10380:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10381:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10382:                    ."/$udom/$subdir/$uname";
                   10383:     } elsif (defined($alternateRoot)) {
                   10384:         $dirRoot = $alternateRoot;
1.751     banghart 10385:     }
1.253     stredwic 10386: 
                   10387:     if($udom) {
                   10388:         if($uname) {
1.1135    raeburn  10389:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10390:             if ($uhome eq 'no_host') {
                   10391:                 return ([],'no_host');
                   10392:             }
1.955     raeburn  10393:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10394:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10395:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10396:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10397:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10398:             } else {
                   10399:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10400:             }
1.605     matthew  10401:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10402:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10403:                 @listing_results = split(/:/,$listing);
                   10404:             } else {
                   10405:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10406:             }
1.1135    raeburn  10407:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10408:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10409:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10410:                 return ([],$listing);
                   10411:             } else {
                   10412:                 return (\@listing_results);
1.1135    raeburn  10413:             }
1.955     raeburn  10414:         } elsif(!$alternateRoot) {
1.1136    raeburn  10415:             my (%allusers,%listerror);
1.841     albertel 10416: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10417:  	    foreach my $tryserver (keys(%servers)) {
                   10418:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10419:                                   &escape($udom),$tryserver);
                   10420:                 if ($listing eq 'unknown_cmd') {
                   10421: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10422: 				      $udom, $tryserver);
                   10423:                 } else {
                   10424:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10425:                 }
1.841     albertel 10426: 		if ($listing eq 'unknown_cmd') {
                   10427: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10428: 				      $udom, $tryserver);
                   10429: 		    @listing_results = split(/:/,$listing);
                   10430: 		} else {
                   10431: 		    @listing_results =
                   10432: 			map { &unescape($_); } split(/:/,$listing);
                   10433: 		}
1.1136    raeburn  10434:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10435:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10436:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10437:                     $listerror{$tryserver} = $listing;
                   10438:                 } else {
1.841     albertel 10439: 		    foreach my $line (@listing_results) {
                   10440: 			my ($entry) = split(/&/,$line,2);
                   10441: 			$allusers{$entry} = 1;
                   10442: 		    }
                   10443: 		}
1.253     stredwic 10444:             }
1.1136    raeburn  10445:             my @alluserslist=();
1.800     albertel 10446:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10447:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10448:             }
1.1318    droeschl 10449: 
                   10450:             if (!%listerror) {
                   10451:                 # no errors
                   10452:                 return (\@alluserslist);
                   10453:             } elsif (scalar(keys(%servers)) == 1) {
                   10454:                 # one library server, one error 
                   10455:                 my ($key) = keys(%listerror);
                   10456:                 return (\@alluserslist, $listerror{$key});
                   10457:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10458:                 # con_lost indicates that we might miss data from at least one
                   10459:                 # library server
                   10460:                 return (\@alluserslist, 'con_lost');
                   10461:             } else {
                   10462:                 # multiple library servers and no con_lost -> data should be
                   10463:                 # complete. 
                   10464:                 return (\@alluserslist);
                   10465:             }
                   10466: 
1.253     stredwic 10467:         } else {
1.1136    raeburn  10468:             return ([],'missing username');
1.253     stredwic 10469:         }
1.955     raeburn  10470:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10471:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10472:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10473:         return (\@all_domains);
1.955     raeburn  10474:     } else {
1.1136    raeburn  10475:         return ([],'missing domain');
1.275     stredwic 10476:     }
                   10477: }
                   10478: 
                   10479: # --------------------------------------------- GetFileTimestamp
                   10480: # This function utilizes dirlist and returns the date stamp for
                   10481: # when it was last modified.  It will also return an error of -1
                   10482: # if an error occurs
                   10483: 
                   10484: sub GetFileTimestamp {
1.955     raeburn  10485:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10486:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10487:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10488:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10489:                                     undef,$getuserdir);
                   10490:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10491:         return -1;
                   10492:     }
                   10493:     if (ref($fileref) eq 'ARRAY') {
                   10494:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10495:         # @stats contains first the filename, then the stat output
                   10496:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10497:     } else {
                   10498:         return -1;
1.253     stredwic 10499:     }
1.26      www      10500: }
                   10501: 
1.712     albertel 10502: sub stat_file {
                   10503:     my ($uri) = @_;
1.787     albertel 10504:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10505: 
1.955     raeburn  10506:     my ($udom,$uname,$file);
1.712     albertel 10507:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10508: 	($udom,$uname,$file) =
1.811     albertel 10509: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10510: 	$file = 'userfiles/'.$file;
                   10511:     }
                   10512:     if ($uri =~ m-^/res/-) {
                   10513: 	($udom,$uname) = 
1.807     albertel 10514: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10515: 	$file = $uri;
                   10516:     }
                   10517: 
                   10518:     if (!$udom || !$uname || !$file) {
                   10519: 	# unable to handle the uri
                   10520: 	return ();
                   10521:     }
1.956     raeburn  10522:     my $getpropath;
                   10523:     if ($file =~ /^userfiles\//) {
                   10524:         $getpropath = 1;
                   10525:     }
1.1136    raeburn  10526:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10527:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10528:         return ();
                   10529:     } else {
                   10530:         if (ref($listref) eq 'ARRAY') {
                   10531:             my @stats = split('&',$listref->[0]);
                   10532: 	    shift(@stats); #filename is first
                   10533: 	    return @stats;
                   10534:         }
1.712     albertel 10535:     }
                   10536:     return ();
                   10537: }
                   10538: 
1.1313    raeburn  10539: # --------------------------------------------------------- recursedirs
                   10540: # Recursive function to traverse either a specific user's Authoring Space
                   10541: # or corresponding Published Resource Space, and populate the hash ref:
                   10542: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10543: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10544: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10545: # files in Authoring Space.
                   10546: #
                   10547: # Inputs:
                   10548: #
                   10549: # $is_home - true if current server is home server for user's space
                   10550: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10551: # $docroot - Document root (i.e., /home/httpd/html
                   10552: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10553: # $relpath - Current path (relative to top level).
                   10554: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10555: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10556: #
                   10557: # Returns: nothing
                   10558: #
                   10559: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10560: #
                   10561: # Currently used by interface/londocs.pm to create linked select boxes for
                   10562: # directory and filename to import a Course "Author" resource into a course, and
                   10563: # also to create linked select boxes for Authoring Space and Directory to choose
                   10564: # save location for creation of a new "standard" problem from the Course Editor.
                   10565: #
                   10566: 
                   10567: sub recursedirs {
                   10568:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10569:     return unless (ref($dirhashref) eq 'HASH');
                   10570:     my $currpath = $docroot.$toppath;
                   10571:     if ($relpath) {
                   10572:         $currpath .= "/$relpath";
                   10573:     }
                   10574:     my $savefile;
                   10575:     if (ref($filehashref)) {
                   10576:         $savefile = 1;
                   10577:     }
                   10578:     if ($is_home) {
                   10579:         if (opendir(my $dirh,$currpath)) {
                   10580:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10581:                 next if ($item eq '');
                   10582:                 if (-d "$currpath/$item") {
                   10583:                     my $newpath;
                   10584:                     if ($relpath) {
                   10585:                         $newpath = "$relpath/$item";
                   10586:                     } else {
                   10587:                         $newpath = $item;
                   10588:                     }
                   10589:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10590:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10591:                 } elsif ($savefile) {
                   10592:                     if ($context eq 'priv') {
                   10593:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10594:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10595:                         }
                   10596:                     } else {
                   10597:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10598:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10599:                         }
                   10600:                     }
                   10601:                 }
                   10602:             }
                   10603:             closedir($dirh);
                   10604:         }
                   10605:     } else {
                   10606:         my ($dirlistref,$listerror) =
                   10607:             &dirlist($toppath.$relpath);
                   10608:         my @dir_lines;
                   10609:         my $dirptr=16384;
                   10610:         if (ref($dirlistref) eq 'ARRAY') {
                   10611:             foreach my $dir_line (sort
                   10612:                               {
                   10613:                                   my ($afile)=split('&',$a,2);
                   10614:                                   my ($bfile)=split('&',$b,2);
                   10615:                                   return (lc($afile) cmp lc($bfile));
                   10616:                               } (@{$dirlistref})) {
                   10617:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10618:                     split(/\&/,$dir_line,16);
                   10619:                 $item =~ s/\s+$//;
                   10620:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10621:                 if ($dirptr&$testdir) {
                   10622:                     my $newpath;
                   10623:                     if ($relpath) {
                   10624:                         $newpath = "$relpath/$item";
                   10625:                     } else {
                   10626:                         $relpath = '/';
                   10627:                         $newpath = $item;
                   10628:                     }
                   10629:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10630:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10631:                 } elsif ($savefile) {
                   10632:                     if ($context eq 'priv') {
                   10633:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10634:                             $filehashref->{$relpath}{$item} = 1;
                   10635:                         }
                   10636:                     } else {
                   10637:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10638:                             $filehashref->{$relpath}{$item} = 1;
                   10639:                         }
                   10640:                     }
                   10641:                 }
                   10642:             }
                   10643:         }
                   10644:     }
                   10645:     return;
                   10646: }
                   10647: 
1.26      www      10648: # -------------------------------------------------------- Value of a Condition
                   10649: 
1.713     albertel 10650: # gets the value of a specific preevaluated condition
                   10651: #    stored in the string  $env{user.state.<cid>}
                   10652: # or looks up a condition reference in the bighash and if if hasn't
                   10653: # already been evaluated recurses into docondval to get the value of
                   10654: # the condition, then memoizing it to 
                   10655: #   $env{user.state.<cid>.<condition>}
1.40      www      10656: sub directcondval {
                   10657:     my $number=shift;
1.620     albertel 10658:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10659: 	&Apache::lonuserstate::evalstate();
                   10660:     }
1.713     albertel 10661:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10662: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10663:     } elsif ($number =~ /^_/) {
                   10664: 	my $sub_condition;
                   10665: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10666: 		&GDBM_READER(),0640)) {
                   10667: 	    $sub_condition=$bighash{'conditions'.$number};
                   10668: 	    untie(%bighash);
                   10669: 	}
                   10670: 	my $value = &docondval($sub_condition);
1.949     raeburn  10671: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10672: 	return $value;
                   10673:     }
1.620     albertel 10674:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10675:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10676:     } else {
                   10677:        return 2;
                   10678:     }
                   10679: }
                   10680: 
1.713     albertel 10681: # get the collection of conditions for this resource
1.26      www      10682: sub condval {
                   10683:     my $condidx=shift;
1.54      www      10684:     my $allpathcond='';
1.713     albertel 10685:     foreach my $cond (split(/\|/,$condidx)) {
                   10686: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10687: 	    $allpathcond.=
                   10688: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10689: 	}
1.191     harris41 10690:     }
1.54      www      10691:     $allpathcond=~s/\|$//;
1.713     albertel 10692:     return &docondval($allpathcond);
                   10693: }
                   10694: 
                   10695: #evaluates an expression of conditions
                   10696: sub docondval {
                   10697:     my ($allpathcond) = @_;
                   10698:     my $result=0;
                   10699:     if ($env{'request.course.id'}
                   10700: 	&& defined($allpathcond)) {
                   10701: 	my $operand='|';
                   10702: 	my @stack;
                   10703: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10704: 	    if ($chunk eq '(') {
                   10705: 		push @stack,($operand,$result);
                   10706: 	    } elsif ($chunk eq ')') {
                   10707: 		my $before=pop @stack;
                   10708: 		if (pop @stack eq '&') {
                   10709: 		    $result=$result>$before?$before:$result;
                   10710: 		} else {
                   10711: 		    $result=$result>$before?$result:$before;
                   10712: 		}
                   10713: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10714: 		$operand=$chunk;
                   10715: 	    } else {
                   10716: 		my $new=directcondval($chunk);
                   10717: 		if ($operand eq '&') {
                   10718: 		    $result=$result>$new?$new:$result;
                   10719: 		} else {
                   10720: 		    $result=$result>$new?$result:$new;
                   10721: 		}
                   10722: 	    }
                   10723: 	}
1.26      www      10724:     }
                   10725:     return $result;
1.421     albertel 10726: }
                   10727: 
                   10728: # ---------------------------------------------------- Devalidate courseresdata
                   10729: 
                   10730: sub devalidatecourseresdata {
                   10731:     my ($coursenum,$coursedomain)=@_;
                   10732:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10733:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10734: }
                   10735: 
1.763     www      10736: 
1.200     www      10737: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10738: #
                   10739: #  Parameters:
                   10740: #      $coursenum    - Number of the course.
                   10741: #      $coursedomain - Domain at which the course was created.
                   10742: #  Returns:
                   10743: #     A hash of the course parameters along (I think) with timestamps
                   10744: #     and version info.
1.877     foxr     10745: 
1.624     albertel 10746: sub get_courseresdata {
                   10747:     my ($coursenum,$coursedomain)=@_;
1.200     www      10748:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10749:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10750:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10751:     my %dumpreply;
1.417     albertel 10752:     unless (defined($cached)) {
1.624     albertel 10753: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10754: 	$result=\%dumpreply;
1.251     albertel 10755: 	my ($tmp) = keys(%dumpreply);
                   10756: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10757: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10758: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10759: 	    return $tmp;
1.416     albertel 10760: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10761: 	    $result=undef;
1.599     albertel 10762: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10763: 	}
                   10764:     }
1.624     albertel 10765:     return $result;
                   10766: }
                   10767: 
1.633     albertel 10768: sub devalidateuserresdata {
                   10769:     my ($uname,$udom)=@_;
                   10770:     my $hashid="$udom:$uname";
                   10771:     &devalidate_cache_new('userres',$hashid);
                   10772: }
                   10773: 
1.624     albertel 10774: sub get_userresdata {
                   10775:     my ($uname,$udom)=@_;
                   10776:     #most student don\'t have any data set, check if there is some data
                   10777:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10778: 
                   10779:     my $hashid="$udom:$uname";
                   10780:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10781:     if (!defined($cached)) {
                   10782: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10783: 	$result=\%resourcedata;
                   10784: 	&do_cache_new('userres',$hashid,$result,600);
                   10785:     }
                   10786:     my ($tmp)=keys(%$result);
                   10787:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10788: 	return $result;
                   10789:     }
                   10790:     #error 2 occurs when the .db doesn't exist
                   10791:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10792:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10793: 	    &logthis("<font color=\"blue\">WARNING:".
                   10794: 		     " Trying to get resource data for ".
                   10795: 		     $uname." at ".$udom.": ".
                   10796: 		     $tmp."</font>");
                   10797:         }
1.624     albertel 10798:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10799: 	#&EXT_cache_set($udom,$uname);
                   10800: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10801: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10802:     }
                   10803:     return $tmp;
                   10804: }
1.879     foxr     10805: #----------------------------------------------- resdata - return resource data
                   10806: #  Purpose:
                   10807: #    Return resource data for either users or for a course.
                   10808: #  Parameters:
                   10809: #     $name      - Course/user name.
                   10810: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10811: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10812: #     $mapp      - decluttered URL of enclosing map  
                   10813: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10814: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10815: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10816: #     $courseid  - CourseID (first part of param identifier).
                   10817: #     $modifier  - Middle part of param identifier.
                   10818: #     $what      - Last part of param identifier.
1.879     foxr     10819: #     @which     - Array of names of resources desired.
                   10820: #  Returns:
                   10821: #     The value of the first reasource in @which that is found in the
                   10822: #     resource hash.
                   10823: #  Exceptional Conditions:
                   10824: #     If the $type passed in is not valid (not the string 'course' or 
                   10825: #     'user', an undefined  reference is returned.
                   10826: #     If none of the resources are found, an undef is returned
1.624     albertel 10827: sub resdata {
1.1301    raeburn  10828:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10829:         $modifier,$what,@which)=@_;
1.624     albertel 10830:     my $result;
                   10831:     if ($type eq 'course') {
                   10832: 	$result=&get_courseresdata($name,$domain);
                   10833:     } elsif ($type eq 'user') {
                   10834: 	$result=&get_userresdata($name,$domain);
                   10835:     }
                   10836:     if (!ref($result)) { return $result; }    
1.251     albertel 10837:     foreach my $item (@which) {
1.1301    raeburn  10838:         if ($item->[1] eq 'course') {
                   10839:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10840:                 unless ($$recursed) {
1.1302    raeburn  10841:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10842:                     $$recursed = 1;
                   10843:                 }
                   10844:                 foreach my $item (@${recurseup}) {
                   10845:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10846:                     last if (defined($result->{$norecursechk}));
                   10847:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10848:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10849:                 }
                   10850:             }
                   10851:         }
                   10852:         if (defined($result->{$item->[0]})) {
1.927     albertel 10853: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10854: 	}
1.250     albertel 10855:     }
1.291     albertel 10856:     return undef;
1.200     www      10857: }
                   10858: 
1.1298    raeburn  10859: sub get_domain_ltitools {
                   10860:     my ($cdom) = @_;
                   10861:     my %ltitools;
                   10862:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10863:     if (defined($cached)) {
                   10864:         if (ref($result) eq 'HASH') {
                   10865:             %ltitools = %{$result};
                   10866:         }
                   10867:     } else {
                   10868:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10869:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10870:             %ltitools = %{$domconfig{'ltitools'}};
                   10871:         }
                   10872:         my $cachetime = 24*60*60;
                   10873:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10874:     }
                   10875:     return %ltitools;
                   10876: }
                   10877: 
1.1236    raeburn  10878: sub get_numsuppfiles {
                   10879:     my ($cnum,$cdom,$ignorecache)=@_;
                   10880:     my $hashid=$cnum.':'.$cdom;
                   10881:     my ($suppcount,$cached);
                   10882:     unless ($ignorecache) {
                   10883:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10884:     }
                   10885:     unless (defined($cached)) {
                   10886:         my $chome=&homeserver($cnum,$cdom);
                   10887:         unless ($chome eq 'no_host') {
                   10888:             ($suppcount,my $errors) = (0,0);
                   10889:             my $suppmap = 'supplemental.sequence';
                   10890:             ($suppcount,$errors) = 
                   10891:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   10892:         }
                   10893:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   10894:     }
                   10895:     return $suppcount;
                   10896: }
                   10897: 
1.379     matthew  10898: #
                   10899: # EXT resource caching routines
                   10900: #
                   10901: 
1.1302    raeburn  10902: {
                   10903: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   10904: #
                   10905: # The course for which we cache
                   10906: my $cachedmapkey='';
                   10907: # The cached recursive maps for this course
                   10908: my %cachedmaps=();
                   10909: # When this was last done
                   10910: my $cachedmaptime='';
                   10911: 
1.379     matthew  10912: sub clear_EXT_cache_status {
1.383     albertel 10913:     &delenv('cache.EXT.');
1.379     matthew  10914: }
                   10915: 
                   10916: sub EXT_cache_status {
                   10917:     my ($target_domain,$target_user) = @_;
1.383     albertel 10918:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 10919:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  10920:         # We know already the user has no data
                   10921:         return 1;
                   10922:     } else {
                   10923:         return 0;
                   10924:     }
                   10925: }
                   10926: 
                   10927: sub EXT_cache_set {
                   10928:     my ($target_domain,$target_user) = @_;
1.383     albertel 10929:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  10930:     #&appenv({$cachename => time});
1.379     matthew  10931: }
                   10932: 
1.28      www      10933: # --------------------------------------------------------- Value of a Variable
1.58      www      10934: sub EXT {
1.715     albertel 10935: 
1.1228    raeburn  10936:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      10937:     unless ($varname) { return ''; }
1.218     albertel 10938:     #get real user name/domain, courseid and symb
                   10939:     my $courseid;
1.359     albertel 10940:     my $publicuser;
1.427     www      10941:     if ($symbparm) {
                   10942: 	$symbparm=&get_symb_from_alias($symbparm);
                   10943:     }
1.218     albertel 10944:     if (!($uname && $udom)) {
1.790     albertel 10945:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 10946:       if (!$symbparm) {	$symbparm=$cursymb; }
                   10947:     } else {
1.620     albertel 10948: 	$courseid=$env{'request.course.id'};
1.218     albertel 10949:     }
1.48      www      10950:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   10951:     my $rest;
1.320     albertel 10952:     if (defined($therest[0])) {
1.48      www      10953:        $rest=join('.',@therest);
                   10954:     } else {
                   10955:        $rest='';
                   10956:     }
1.320     albertel 10957: 
1.57      www      10958:     my $qualifierrest=$qualifier;
                   10959:     if ($rest) { $qualifierrest.='.'.$rest; }
                   10960:     my $spacequalifierrest=$space;
                   10961:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      10962:     if ($realm eq 'user') {
1.48      www      10963: # --------------------------------------------------------------- user.resource
                   10964: 	if ($space eq 'resource') {
1.651     albertel 10965: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   10966: 		  || defined($Apache::lonhomework::parsing_a_task))
                   10967: 		 &&
1.744     albertel 10968: 		 ($symbparm eq &symbread()) ) {	
                   10969: 		# if we are in the middle of processing the resource the
                   10970: 		# get the value we are planning on committing
                   10971:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   10972:                     return $Apache::lonhomework::results{$qualifierrest};
                   10973:                 } else {
                   10974:                     return $Apache::lonhomework::history{$qualifierrest};
                   10975:                 }
1.335     albertel 10976: 	    } else {
1.359     albertel 10977: 		my %restored;
1.620     albertel 10978: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 10979: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   10980: 		} else {
                   10981: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   10982: 		}
1.335     albertel 10983: 		return $restored{$qualifierrest};
                   10984: 	    }
1.48      www      10985: # ----------------------------------------------------------------- user.access
                   10986:         } elsif ($space eq 'access') {
1.218     albertel 10987: 	    # FIXME - not supporting calls for a specific user
1.48      www      10988:             return &allowed($qualifier,$rest);
                   10989: # ------------------------------------------ user.preferences, user.environment
                   10990:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 10991: 	    if (($uname eq $env{'user.name'}) &&
                   10992: 		($udom eq $env{'user.domain'})) {
                   10993: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 10994: 	    } else {
1.359     albertel 10995: 		my %returnhash;
                   10996: 		if (!$publicuser) {
                   10997: 		    %returnhash=&userenvironment($udom,$uname,
                   10998: 						 $qualifierrest);
                   10999: 		}
1.218     albertel 11000: 		return $returnhash{$qualifierrest};
                   11001: 	    }
1.48      www      11002: # ----------------------------------------------------------------- user.course
                   11003:         } elsif ($space eq 'course') {
1.218     albertel 11004: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11005:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11006: # ------------------------------------------------------------------- user.role
                   11007:         } elsif ($space eq 'role') {
1.218     albertel 11008: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11009:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11010:             if ($qualifier eq 'value') {
                   11011: 		return $role;
                   11012:             } elsif ($qualifier eq 'extent') {
                   11013:                 return $where;
                   11014:             }
                   11015: # ----------------------------------------------------------------- user.domain
                   11016:         } elsif ($space eq 'domain') {
1.218     albertel 11017:             return $udom;
1.48      www      11018: # ------------------------------------------------------------------- user.name
                   11019:         } elsif ($space eq 'name') {
1.218     albertel 11020:             return $uname;
1.48      www      11021: # ---------------------------------------------------- Any other user namespace
1.29      www      11022:         } else {
1.359     albertel 11023: 	    my %reply;
                   11024: 	    if (!$publicuser) {
                   11025: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11026: 	    }
                   11027: 	    return $reply{$qualifierrest};
1.48      www      11028:         }
1.236     www      11029:     } elsif ($realm eq 'query') {
                   11030: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11031:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11032: 						[$spacequalifierrest]);
1.620     albertel 11033: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11034:    } elsif ($realm eq 'request') {
1.48      www      11035: # ------------------------------------------------------------- request.browser
                   11036:         if ($space eq 'browser') {
1.1145    bisitz   11037:             return $env{'browser.'.$qualifier};
1.57      www      11038: # ------------------------------------------------------------ request.filename
                   11039:         } else {
1.620     albertel 11040:             return $env{'request.'.$spacequalifierrest};
1.29      www      11041:         }
1.28      www      11042:     } elsif ($realm eq 'course') {
1.48      www      11043: # ---------------------------------------------------------- course.description
1.620     albertel 11044:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11045:     } elsif ($realm eq 'resource') {
1.165     www      11046: 
1.620     albertel 11047: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11048: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11049: 	}
1.693     albertel 11050: 
1.1232    raeburn  11051:         if ($qualifier eq '') {
                   11052: 	    if ($space eq 'title') {
                   11053: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11054: 	        return &gettitle($symbparm);
                   11055: 	    }
1.693     albertel 11056: 	
1.1232    raeburn  11057: 	    if ($space eq 'map') {
                   11058: 	        my ($map) = &decode_symb($symbparm);
                   11059: 	        return &symbread($map);
                   11060: 	    }
                   11061:             if ($space eq 'maptitle') {
                   11062:                 my ($map) = &decode_symb($symbparm);
                   11063:                 return &gettitle($map);
                   11064:             }
                   11065: 	    if ($space eq 'filename') {
                   11066: 	        if ($symbparm) {
                   11067: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11068: 	        }
                   11069: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11070: 	    }
1.1232    raeburn  11071: 
1.1233    raeburn  11072:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11073:                 if ($space eq 'visibleparts') {
                   11074:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11075:                     my $item;
                   11076:                     if (ref($navmap)) {
                   11077:                         my $res = $navmap->getBySymb($symbparm);
                   11078:                         my $parts = $res->parts();
                   11079:                         if (ref($parts) eq 'ARRAY') {
                   11080:                             $item = join(',',@{$parts});
                   11081:                         }
                   11082:                         undef($navmap);
1.1232    raeburn  11083:                     }
1.1233    raeburn  11084:                     return $item;
1.1232    raeburn  11085:                 }
                   11086:             }
                   11087:         }
1.693     albertel 11088: 
1.1301    raeburn  11089: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11090: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11091:         if (($courseid eq '') && ($cid)) {
                   11092:             $courseid = $cid;
                   11093:         }
                   11094: 	if (($symbparm && $courseid) && 
                   11095: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11096: 
1.218     albertel 11097: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11098: 
1.60      www      11099: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11100: 	    my $symbp=$symbparm;
1.1301    raeburn  11101: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11102: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11103:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11104: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11105: 	    if (($env{'user.name'} eq $uname) &&
                   11106: 		($env{'user.domain'} eq $udom)) {
                   11107: 		$section=$env{'request.course.sec'};
1.733     raeburn  11108:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11109:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11110: 	    } else {
1.539     albertel 11111: 		if (! defined($usection)) {
1.551     albertel 11112: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11113: 		} else {
                   11114: 		    $section = $usection;
                   11115: 		}
1.733     raeburn  11116:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11117: 	    }
                   11118: 
                   11119: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11120: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11121:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11122: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11123: 
1.593     albertel 11124: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11125: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11126:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11127: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11128: 
1.60      www      11129: # ----------------------------------------------------------- first, check user
1.624     albertel 11130: 
1.1301    raeburn  11131: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11132:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11133: 				       ([$courselevelr,'resource'],
                   11134: 					[$courselevelm,'map'     ],
1.1301    raeburn  11135:                                         [$courseleveli,'map'     ],
1.927     albertel 11136: 					[$courselevel, 'course'  ]));
1.931     albertel 11137: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11138: 
1.594     albertel 11139: # ------------------------------------------------ second, check some of course
1.684     raeburn  11140:             my $coursereply;
1.691     raeburn  11141:             if (@groups > 0) {
                   11142:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11143:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11144:                                        $mapp,\$recursed,\@recurseup);
                   11145:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11146:             }
1.96      www      11147: 
1.684     raeburn  11148: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11149: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11150: 				  'course',$mapp,\$recursed,\@recurseup,
                   11151:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11152: 				  ([$seclevelr,   'resource'],
                   11153: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11154:                                    [$secleveli,   'map'     ],
1.927     albertel 11155: 				   [$seclevel,    'course'  ],
                   11156: 				   [$courselevelr,'resource']));
                   11157: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11158: 
1.60      www      11159: # ------------------------------------------------------ third, check map parms
1.218     albertel 11160: 	    my %parmhash=();
                   11161: 	    my $thisparm='';
                   11162: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11163: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11164: 		    &GDBM_READER(),0640)) {
1.218     albertel 11165: 		$thisparm=$parmhash{$symbparm};
                   11166: 		untie(%parmhash);
                   11167: 	    }
1.927     albertel 11168: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11169: 	}
1.594     albertel 11170: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11171:  
                   11172:         my $what = $spacequalifierrest;
                   11173: 	$what=~s/\./\_/;
1.282     albertel 11174: 	my $filename;
                   11175: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11176: 	if ($symbparm) {
1.409     www      11177: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11178: 	} else {
1.620     albertel 11179: 	    $filename=$env{'request.filename'};
1.282     albertel 11180: 	}
1.1301    raeburn  11181: 	my $metadata=&metadata($filename,$what);
1.927     albertel 11182: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  11183: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 11184: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11185: 
1.1301    raeburn  11186: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11187: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11188: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11189: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11190: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11191: 				     'course',$mapp,\$recursed,\@recurseup,
                   11192:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11193: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11194:                                       [$courseleveli,'map'   ],
1.927     albertel 11195: 				      [$courselevel, 'course']));
                   11196: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11197: 	}
1.145     www      11198: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11199: 	unless ($space eq '0') {
1.336     albertel 11200: 	    my @parts=split(/_/,$space);
                   11201: 	    my $id=pop(@parts);
                   11202: 	    my $part=join('_',@parts);
                   11203: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11204: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11205: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11206: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11207: 	}
1.395     albertel 11208: 	if ($recurse) { return undef; }
                   11209: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11210: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11211: # ---------------------------------------------------- Any other user namespace
                   11212:     } elsif ($realm eq 'environment') {
                   11213: # ----------------------------------------------------------------- environment
1.620     albertel 11214: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11215: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11216: 	} else {
1.770     albertel 11217: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11218: 		return '';
                   11219: 	    }
1.219     albertel 11220: 	    my %returnhash=&userenvironment($udom,$uname,
                   11221: 					    $spacequalifierrest);
                   11222: 	    return $returnhash{$spacequalifierrest};
                   11223: 	}
1.28      www      11224:     } elsif ($realm eq 'system') {
1.48      www      11225: # ----------------------------------------------------------------- system.time
                   11226: 	if ($space eq 'time') {
                   11227: 	    return time;
                   11228:         }
1.696     albertel 11229:     } elsif ($realm eq 'server') {
                   11230: # ----------------------------------------------------------------- system.time
                   11231: 	if ($space eq 'name') {
                   11232: 	    return $ENV{'SERVER_NAME'};
                   11233:         }
1.28      www      11234:     }
1.48      www      11235:     return '';
1.61      www      11236: }
                   11237: 
1.927     albertel 11238: sub get_reply {
                   11239:     my ($reply_value) = @_;
1.940     raeburn  11240:     if (ref($reply_value) eq 'ARRAY') {
                   11241:         if (wantarray) {
                   11242: 	    return @$reply_value;
                   11243:         }
                   11244:         return $reply_value->[0];
                   11245:     } else {
                   11246:         return $reply_value;
1.927     albertel 11247:     }
                   11248: }
                   11249: 
1.691     raeburn  11250: sub check_group_parms {
1.1301    raeburn  11251:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11252:         $recursed,$recurseupref) = @_;
                   11253:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11254:                   [$what,'course']);
                   11255:     my $coursereply;
1.691     raeburn  11256:     foreach my $group (@{$groups}) {
1.1301    raeburn  11257:         my @groupitems = ();
1.691     raeburn  11258:         foreach my $level (@levels) {
1.927     albertel 11259:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11260:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11261:         }
1.1301    raeburn  11262:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11263:                                    $env{'course.'.$courseid.'.domain'},
                   11264:                                    'course',$mapp,$recursed,$recurseupref,
                   11265:                                    $courseid,'.['.$group.'].',$what,
                   11266:                                    @groupitems);
                   11267:         last if (defined($coursereply));
1.691     raeburn  11268:     }
                   11269:     return $coursereply;
                   11270: }
                   11271: 
1.1301    raeburn  11272: sub get_map_hierarchy {
1.1302    raeburn  11273:     my ($mapname,$courseid) = @_;
                   11274:     my @recurseup = ();
1.1301    raeburn  11275:     if ($mapname) {
1.1302    raeburn  11276:         if (($cachedmapkey eq $courseid) &&
                   11277:             (abs($cachedmaptime-time)<5)) {
                   11278:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11279:                 return @{$cachedmaps{$mapname}};
                   11280:             }
                   11281:         }
1.1301    raeburn  11282:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11283:         if (ref($navmap)) {
                   11284:             @recurseup = $navmap->recurseup_maps($mapname);
                   11285:             undef($navmap);
1.1302    raeburn  11286:             $cachedmaps{$mapname} = \@recurseup;
                   11287:             $cachedmaptime=time;
                   11288:             $cachedmapkey=$courseid;
1.1301    raeburn  11289:         }
                   11290:     }
                   11291:     return @recurseup;
                   11292: }
                   11293: 
1.1302    raeburn  11294: }
                   11295: 
1.691     raeburn  11296: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11297:     my ($courseid,@groups) = @_;
                   11298:     @groups = sort(@groups);
1.691     raeburn  11299:     return @groups;
                   11300: }
                   11301: 
1.395     albertel 11302: sub packages_tab_default {
                   11303:     my ($uri,$varname)=@_;
                   11304:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11305: 
                   11306:     my (@extension,@specifics,$do_default);
                   11307:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11308: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11309: 	if ($pack_type eq 'default') {
                   11310: 	    $do_default=1;
                   11311: 	} elsif ($pack_type eq 'extension') {
                   11312: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11313: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11314: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11315: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11316: 	}
                   11317:     }
                   11318:     # first look for a package that matches the requested part id
                   11319:     foreach my $package (@specifics) {
                   11320: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11321: 	next if ($pack_part ne $part);
                   11322: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11323: 	    return $packagetab{"$pack_type&$name&default"};
                   11324: 	}
                   11325:     }
                   11326:     # look for any possible matching non extension_ package
                   11327:     foreach my $package (@specifics) {
                   11328: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11329: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11330: 	    return $packagetab{"$pack_type&$name&default"};
                   11331: 	}
1.585     albertel 11332: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11333: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11334: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11335: 	}
                   11336:     }
1.738     albertel 11337:     # look for any posible extension_ match
                   11338:     foreach my $package (@extension) {
                   11339: 	my ($package,$pack_type)=@{$package};
                   11340: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11341: 	    return $packagetab{"$pack_type&$name&default"};
                   11342: 	}
                   11343: 	if (defined($packagetab{$package."&$name&default"})) {
                   11344: 	    return $packagetab{$package."&$name&default"};
                   11345: 	}
                   11346:     }
                   11347:     # look for a global default setting
                   11348:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11349: 	return $packagetab{"default&$name&default"};
                   11350:     }
1.395     albertel 11351:     return undef;
                   11352: }
                   11353: 
1.334     albertel 11354: sub add_prefix_and_part {
                   11355:     my ($prefix,$part)=@_;
                   11356:     my $keyroot;
                   11357:     if (defined($prefix) && $prefix !~ /^__/) {
                   11358: 	# prefix that has a part already
                   11359: 	$keyroot=$prefix;
                   11360:     } elsif (defined($prefix)) {
                   11361: 	# prefix that is missing a part
                   11362: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11363:     } else {
                   11364: 	# no prefix at all
                   11365: 	if (defined($part)) { $keyroot='_'.$part; }
                   11366:     }
                   11367:     return $keyroot;
                   11368: }
                   11369: 
1.71      www      11370: # ---------------------------------------------------------------- Get metadata
                   11371: 
1.599     albertel 11372: my %metaentry;
1.1070    www      11373: my %importedpartids;
1.71      www      11374: sub metadata {
1.176     www      11375:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11376:     $uri=&declutter($uri);
1.288     albertel 11377:     # if it is a non metadata possible uri return quickly
1.529     albertel 11378:     if (($uri eq '') || 
                   11379: 	(($uri =~ m|^/*adm/|) && 
1.1298    raeburn  11380: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|exttools?)$})) ||
1.1108    raeburn  11381:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11382: 	return undef;
                   11383:     }
1.1261    raeburn  11384:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11385: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11386: 	return undef;
1.288     albertel 11387:     }
1.73      www      11388:     my $filename=$uri;
                   11389:     $uri=~s/\.meta$//;
1.172     www      11390: #
                   11391: # Is the metadata already cached?
1.177     www      11392: # Look at timestamp of caching
1.172     www      11393: # Everything is cached by the main uri, libraries are never directly cached
                   11394: #
1.428     albertel 11395:     if (!defined($liburi)) {
1.599     albertel 11396: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11397: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11398:     }
                   11399:     {
1.1069    www      11400: # Imported parts would go here
1.1070    www      11401:         my %importedids=();
                   11402:         my @origfileimportpartids=();
1.1069    www      11403:         my $importedparts=0;
1.172     www      11404: #
                   11405: # Is this a recursive call for a library?
                   11406: #
1.599     albertel 11407: #	if (! exists($metacache{$uri})) {
                   11408: #	    $metacache{$uri}={};
                   11409: #	}
1.924     albertel 11410: 	my $cachetime = 60*60;
1.171     www      11411:         if ($liburi) {
                   11412: 	    $liburi=&declutter($liburi);
                   11413:             $filename=$liburi;
1.401     bowersj2 11414:         } else {
1.599     albertel 11415: 	    &devalidate_cache_new('meta',$uri);
                   11416: 	    undef(%metaentry);
1.401     bowersj2 11417: 	}
1.140     www      11418:         my %metathesekeys=();
1.73      www      11419:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11420: 	my $metastring;
1.1140    www      11421: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11422: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11423: 	    $metastring = 
1.929     albertel 11424: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11425: 					  ('grade_target' => 'meta'));
                   11426: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11427: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11428:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11429: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11430: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11431: 	    $metastring=&getfile($file);
1.489     albertel 11432: 	}
1.208     albertel 11433:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11434:         my $token;
1.140     www      11435:         undef %metathesekeys;
1.71      www      11436:         while ($token=$parser->get_token) {
1.339     albertel 11437: 	    if ($token->[0] eq 'S') {
                   11438: 		if (defined($token->[2]->{'package'})) {
1.172     www      11439: #
                   11440: # This is a package - get package info
                   11441: #
1.339     albertel 11442: 		    my $package=$token->[2]->{'package'};
                   11443: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11444: 		    if (defined($token->[2]->{'id'})) { 
                   11445: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11446: 		    }
1.599     albertel 11447: 		    if ($metaentry{':packages'}) {
                   11448: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11449: 		    } else {
1.599     albertel 11450: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11451: 		    }
1.736     albertel 11452: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11453: 			my $part=$keyroot;
                   11454: 			$part=~s/^\_//;
1.736     albertel 11455: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11456: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11457: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11458: 			    # ignore package.tab specified default values
                   11459:                             # here &package_tab_default() will fetch those
                   11460: 			    if ($subp eq 'default') { next; }
1.736     albertel 11461: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11462: 			    my $unikey;
                   11463: 			    if ($pack =~ /_0$/) {
                   11464: 				$unikey='parameter_0_'.$name;
                   11465: 				$part=0;
                   11466: 			    } else {
                   11467: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11468: 			    }
1.339     albertel 11469: 			    if ($subp eq 'display') {
                   11470: 				$value.=' [Part: '.$part.']';
                   11471: 			    }
1.599     albertel 11472: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11473: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11474: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11475: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11476: 			    }
1.599     albertel 11477: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11478: 				$metaentry{':'.$unikey}=
                   11479: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11480: 			    }
1.339     albertel 11481: 			}
                   11482: 		    }
                   11483: 		} else {
1.172     www      11484: #
                   11485: # This is not a package - some other kind of start tag
1.339     albertel 11486: #
                   11487: 		    my $entry=$token->[1];
1.1068    www      11488: 		    my $unikey='';
1.175     www      11489: 
1.339     albertel 11490: 		    if ($entry eq 'import') {
1.175     www      11491: #
                   11492: # Importing a library here
1.339     albertel 11493: #
1.1067    www      11494:                         my $location=$parser->get_text('/import');
                   11495:                         my $dir=$filename;
                   11496:                         $dir=~s|[^/]*$||;
                   11497:                         $location=&filelocation($dir,$location);
1.1069    www      11498:                        
1.1068    www      11499:                         my $importmode=$token->[2]->{'importmode'};
                   11500:                         if ($importmode eq 'problem') {
1.1069    www      11501: # Import as problem/response
1.1068    www      11502:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11503:                         } elsif ($importmode eq 'part') {
                   11504: # Import as part(s)
1.1069    www      11505:                            $importedparts=1;
                   11506: # We need to get the original file and the imported file to get the part order correct
                   11507: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11508: # Load and inspect original file
1.1070    www      11509:                            if ($#origfileimportpartids<0) {
                   11510:                               undef(%importedpartids);
                   11511:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11512:                               my $origfile=&getfile($origfilelocation);
                   11513:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11514:                            }
                   11515: 
1.1069    www      11516: # Load and inspect imported file
                   11517:                            my $impfile=&getfile($location);
                   11518:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11519:                            if ($#impfilepartids>=0) {
                   11520: # This problem had parts
1.1070    www      11521:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11522:                            } else {
                   11523: # Importing by turning a single problem into a problem part
                   11524: # It gets the import-tags ID as part-ID
                   11525:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11526:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11527:                            }
1.1068    www      11528:                         } else {
                   11529: # Normal import
                   11530:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11531:                            if (defined($token->[2]->{'id'})) {
                   11532:                               $unikey.='_'.$token->[2]->{'id'};
                   11533:                            }
1.1067    www      11534:                         }
                   11535: 
1.339     albertel 11536: 			if ($depthcount<20) {
1.736     albertel 11537: 			    my $metadata = 
                   11538: 				&metadata($uri,'keys', $location,$unikey,
                   11539: 					  $depthcount+1);
                   11540: 			    foreach my $meta (split(',',$metadata)) {
                   11541: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11542: 				$metathesekeys{$meta}=1;
1.339     albertel 11543: 			    }
1.1068    www      11544: 			
                   11545:                         }
1.1067    www      11546: 		    } else {
                   11547: #
                   11548: # Not importing, some other kind of non-package, non-library start tag
                   11549: # 
                   11550:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11551:                         if (defined($token->[2]->{'id'})) {
                   11552:                             $unikey.='_'.$token->[2]->{'id'};
                   11553:                         }
1.339     albertel 11554: 			if (defined($token->[2]->{'name'})) { 
                   11555: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11556: 			}
                   11557: 			$metathesekeys{$unikey}=1;
1.736     albertel 11558: 			foreach my $param (@{$token->[3]}) {
                   11559: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11560: 				$token->[2]->{$param};
1.339     albertel 11561: 			}
                   11562: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11563: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11564: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11565: 		 # only ws inside the tag, and not in default, so use default
                   11566: 		 # as value
1.599     albertel 11567: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11568: 			} elsif ( $internaltext =~ /\S/ ) {
                   11569: 		  # something interesting inside the tag
                   11570: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11571: 			} else {
1.908     albertel 11572: 		  # no interesting values, don't set a default
1.339     albertel 11573: 			}
1.172     www      11574: # end of not-a-package not-a-library import
1.339     albertel 11575: 		    }
1.172     www      11576: # end of not-a-package start tag
1.339     albertel 11577: 		}
1.172     www      11578: # the next is the end of "start tag"
1.339     albertel 11579: 	    }
                   11580: 	}
1.483     albertel 11581: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11582: 	$extension = lc($extension);
                   11583: 	if ($extension eq 'htm') { $extension='html'; }
                   11584: 
1.737     albertel 11585: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11586: 	    #no specific packages #how's our extension
                   11587: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11588: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11589: 					 \%metathesekeys);
                   11590: 	}
1.883     albertel 11591: 
                   11592: 	if (!exists($metaentry{':packages'})
                   11593: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11594: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11595: 		#no specific packages well let's get default then
                   11596: 		if ($key!~/^default&/) { next; }
1.488     albertel 11597: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11598: 					     \%metathesekeys);
                   11599: 	    }
                   11600: 	}
1.338     www      11601: # are there custom rights to evaluate
1.599     albertel 11602: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11603: 
1.338     www      11604:     #
                   11605:     # Importing a rights file here
1.339     albertel 11606:     #
                   11607: 	    unless ($depthcount) {
1.599     albertel 11608: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11609: 		my $dir=$filename;
                   11610: 		$dir=~s|[^/]*$||;
                   11611: 		$location=&filelocation($dir,$location);
1.736     albertel 11612: 		my $rights_metadata =
                   11613: 		    &metadata($uri,'keys',$location,'_rights',
                   11614: 			      $depthcount+1);
                   11615: 		foreach my $rights (split(',',$rights_metadata)) {
                   11616: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11617: 		    $metathesekeys{$rights}=1;
1.339     albertel 11618: 		}
                   11619: 	    }
                   11620: 	}
1.737     albertel 11621: 	# uniqifiy package listing
                   11622: 	my %seen;
                   11623: 	my @uniq_packages =
                   11624: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11625: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11626: 
1.1070    www      11627:         if ($importedparts) {
                   11628: # We had imported parts and need to rebuild partorder
                   11629:            $metaentry{':partorder'}='';
                   11630:            $metathesekeys{'partorder'}=1;
                   11631:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11632:                if ($origfileimportpartids[$index] eq 'part') {
                   11633: # original part, part of the problem
                   11634:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11635:                } else {
                   11636: # we have imported parts at this position
                   11637:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11638:                }
                   11639:            }
                   11640:            $metaentry{':partorder'}=~s/^\,//;
                   11641:         }
                   11642: 
1.737     albertel 11643: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11644: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11645: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11646: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11647: # this is the end of "was not already recently cached
1.71      www      11648:     }
1.599     albertel 11649:     return $metaentry{':'.$what};
1.261     albertel 11650: }
                   11651: 
1.488     albertel 11652: sub metadata_create_package_def {
1.483     albertel 11653:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11654:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11655:     if ($subp eq 'default') { next; }
                   11656:     
1.599     albertel 11657:     if (defined($metaentry{':packages'})) {
                   11658: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11659:     } else {
1.599     albertel 11660: 	$metaentry{':packages'}=$package;
1.483     albertel 11661:     }
                   11662:     my $value=$packagetab{$key};
                   11663:     my $unikey;
                   11664:     $unikey='parameter_0_'.$name;
1.599     albertel 11665:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11666:     $$metathesekeys{$unikey}=1;
1.599     albertel 11667:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11668: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11669:     }
1.599     albertel 11670:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11671: 	$metaentry{':'.$unikey}=
                   11672: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11673:     }
                   11674: }
                   11675: 
1.261     albertel 11676: sub metadata_generate_part0 {
                   11677:     my ($metadata,$metacache,$uri) = @_;
                   11678:     my %allnames;
1.737     albertel 11679:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11680: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11681: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11682: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11683: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11684: 	    $allnames{$name}=$part;
                   11685: 	  }
                   11686: 	}
                   11687:     }
                   11688:     foreach my $name (keys(%allnames)) {
                   11689:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11690:       my $key=":parameter_0_$name";
1.261     albertel 11691:       $$metacache{"$key.part"}='0';
                   11692:       $$metacache{"$key.name"}=$name;
1.428     albertel 11693:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11694: 					   $allnames{$name}.'_'.$name.
                   11695: 					   '.type'};
1.428     albertel 11696:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11697: 			     '.display'};
1.644     www      11698:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11699:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11700:       $$metacache{"$key.display"}=$olddis;
                   11701:     }
1.71      www      11702: }
                   11703: 
1.764     albertel 11704: # ------------------------------------------------------ Devalidate title cache
                   11705: 
                   11706: sub devalidate_title_cache {
                   11707:     my ($url)=@_;
                   11708:     if (!$env{'request.course.id'}) { return; }
                   11709:     my $symb=&symbread($url);
                   11710:     if (!$symb) { return; }
                   11711:     my $key=$env{'request.course.id'}."\0".$symb;
                   11712:     &devalidate_cache_new('title',$key);
                   11713: }
                   11714: 
1.1014    droeschl 11715: # ------------------------------------------------- Get the title of a course
                   11716: 
                   11717: sub current_course_title {
                   11718:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11719: }
1.301     www      11720: # ------------------------------------------------- Get the title of a resource
                   11721: 
                   11722: sub gettitle {
                   11723:     my $urlsymb=shift;
                   11724:     my $symb=&symbread($urlsymb);
1.534     albertel 11725:     if ($symb) {
1.620     albertel 11726: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11727: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11728: 	if (defined($cached)) { 
                   11729: 	    return $result;
                   11730: 	}
1.534     albertel 11731: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11732: 	my $title='';
1.907     albertel 11733: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11734: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11735: 	} else {
                   11736: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11737: 		    &GDBM_READER(),0640)) {
                   11738: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11739: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11740: 		untie(%bighash);
                   11741: 	    }
1.534     albertel 11742: 	}
                   11743: 	$title=~s/\&colon\;/\:/gs;
                   11744: 	if ($title) {
1.1159    www      11745: # Remember both $symb and $title for dynamic metadata
                   11746:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11747:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11748: # Cache this title and then return it
1.599     albertel 11749: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11750: 	}
                   11751: 	$urlsymb=$url;
                   11752:     }
                   11753:     my $title=&metadata($urlsymb,'title');
                   11754:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11755:     return $title;
1.301     www      11756: }
1.613     albertel 11757: 
1.614     albertel 11758: sub get_slot {
                   11759:     my ($which,$cnum,$cdom)=@_;
                   11760:     if (!$cnum || !$cdom) {
1.790     albertel 11761: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11762: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11763: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11764:     }
1.703     albertel 11765:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11766:     my %slotinfo;
                   11767:     if (exists($remembered{$key})) {
                   11768: 	$slotinfo{$which} = $remembered{$key};
                   11769:     } else {
                   11770: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11771: 	&Apache::lonhomework::showhash(%slotinfo);
                   11772: 	my ($tmp)=keys(%slotinfo);
                   11773: 	if ($tmp=~/^error:/) { return (); }
                   11774: 	$remembered{$key} = $slotinfo{$which};
                   11775:     }
1.616     albertel 11776:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11777: 	return %{$slotinfo{$which}};
                   11778:     }
                   11779:     return $slotinfo{$which};
1.614     albertel 11780: }
1.1150    raeburn  11781: 
                   11782: sub get_reservable_slots {
                   11783:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11784:     my $now = time;
                   11785:     my $reservable_info;
                   11786:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11787:     if (exists($remembered{$key})) {
                   11788:         $reservable_info = $remembered{$key};
                   11789:     } else {
                   11790:         my %resv;
                   11791:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11792:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11793:         $reservable_info = \%resv;
                   11794:         $remembered{$key} = $reservable_info;
                   11795:     }
                   11796:     return $reservable_info;
                   11797: }
                   11798: 
                   11799: sub get_course_slots {
                   11800:     my ($cnum,$cdom) = @_;
                   11801:     my $hashid=$cnum.':'.$cdom;
                   11802:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11803:     if (defined($cached)) {
                   11804:         if (ref($result) eq 'HASH') {
                   11805:             return %{$result};
                   11806:         }
                   11807:     } else {
                   11808:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11809:         my ($tmp) = keys(%slots);
                   11810:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11811:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11812:             return %slots;
                   11813:         }
                   11814:     }
                   11815:     return;
                   11816: }
                   11817: 
                   11818: sub devalidate_slots_cache {
                   11819:     my ($cnum,$cdom)=@_;
                   11820:     my $hashid=$cnum.':'.$cdom;
                   11821:     &devalidate_cache_new('allslots',$hashid);
                   11822: }
                   11823: 
1.1181    raeburn  11824: sub get_coursechange {
                   11825:     my ($cdom,$cnum) = @_;
                   11826:     if ($cdom eq '' || $cnum eq '') {
                   11827:         return unless ($env{'request.course.id'});
                   11828:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11829:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11830:     }
                   11831:     my $hashid=$cdom.'_'.$cnum;
                   11832:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11833:     if ((defined($cached)) && ($change ne '')) {
                   11834:         return $change;
                   11835:     } else {
                   11836:         my %crshash;
                   11837:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11838:         if ($crshash{'internal.contentchange'} eq '') {
                   11839:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11840:             if ($change eq '') {
                   11841:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11842:                 $change = $crshash{'internal.created'};
                   11843:             }
                   11844:         } else {
                   11845:             $change = $crshash{'internal.contentchange'};
                   11846:         }
                   11847:         my $cachetime = 600;
                   11848:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11849:     }
                   11850:     return $change;
                   11851: }
                   11852: 
                   11853: sub devalidate_coursechange_cache {
                   11854:     my ($cnum,$cdom)=@_;
                   11855:     my $hashid=$cnum.':'.$cdom;
                   11856:     &devalidate_cache_new('crschange',$hashid);
                   11857: }
                   11858: 
1.31      www      11859: # ------------------------------------------------- Update symbolic store links
                   11860: 
                   11861: sub symblist {
                   11862:     my ($mapname,%newhash)=@_;
1.438     www      11863:     $mapname=&deversion(&declutter($mapname));
1.31      www      11864:     my %hash;
1.620     albertel 11865:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11866:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11867:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11868: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11869: 		next if ($url eq 'last_known'
                   11870: 			 && $env{'form.no_update_last_known'});
                   11871: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11872: 						    $newhash{$url}->[1],
                   11873: 						    $newhash{$url}->[0]);
1.191     harris41 11874:             }
1.31      www      11875:             if (untie(%hash)) {
                   11876: 		return 'ok';
                   11877:             }
                   11878:         }
                   11879:     }
                   11880:     return 'error';
1.212     www      11881: }
                   11882: 
                   11883: # --------------------------------------------------------------- Verify a symb
                   11884: 
                   11885: sub symbverify {
1.1190    raeburn  11886:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      11887:     my $thisfn=$thisurl;
1.439     www      11888:     $thisfn=&declutter($thisfn);
1.215     www      11889: # direct jump to resource in page or to a sequence - will construct own symbs
                   11890:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   11891: # check URL part
1.409     www      11892:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      11893: 
1.431     www      11894:     unless ($url eq $thisfn) { return 0; }
1.213     www      11895: 
1.216     www      11896:     $symb=&symbclean($symb);
1.510     www      11897:     $thisurl=&deversion($thisurl);
1.439     www      11898:     $thisfn=&deversion($thisfn);
1.213     www      11899: 
                   11900:     my %bighash;
                   11901:     my $okay=0;
1.431     www      11902: 
1.620     albertel 11903:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 11904:                             &GDBM_READER(),0640)) {
1.1204    raeburn  11905:         my $noclutter;
1.1032    raeburn  11906:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   11907:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  11908:             if ($map =~ m{^uploaded/.+\.page$}) {
                   11909:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   11910:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   11911:                 $noclutter = 1;
                   11912:             }
                   11913:         }
                   11914:         my $ids;
                   11915:         if ($noclutter) {
                   11916:             $ids=$bighash{'ids_'.$thisurl};
                   11917:         } else {
                   11918:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  11919:         }
1.1102    raeburn  11920:         unless ($ids) {
                   11921:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   11922:             $ids=$bighash{$idkey};
1.216     www      11923:         }
                   11924:         if ($ids) {
                   11925: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  11926:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  11927:                 $symb =~ s/\?.+$//;
1.1202    raeburn  11928:             }
1.800     albertel 11929: 	    foreach my $id (split(/\,/,$ids)) {
                   11930: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      11931:                if (
                   11932:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  11933:    eq $symb) {
                   11934:                    if (ref($encstate)) {
                   11935:                        $$encstate = $bighash{'encrypted_'.$id};
                   11936:                    }
1.620     albertel 11937: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  11938: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   11939:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  11940: 		       $okay=1;
1.1202    raeburn  11941:                        last;
1.582     albertel 11942: 		   }
                   11943: 	       }
1.216     www      11944: 	   }
                   11945:         }
1.213     www      11946: 	untie(%bighash);
                   11947:     }
                   11948:     return $okay;
1.31      www      11949: }
                   11950: 
1.210     www      11951: # --------------------------------------------------------------- Clean-up symb
                   11952: 
                   11953: sub symbclean {
                   11954:     my $symb=shift;
1.568     albertel 11955:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      11956: # remove version from map
                   11957:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      11958: 
1.210     www      11959: # remove version from URL
                   11960:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      11961: 
1.507     www      11962: # remove wrapper
                   11963: 
1.510     www      11964:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 11965:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      11966:     return $symb;
1.409     www      11967: }
                   11968: 
                   11969: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 11970: 
                   11971: sub encode_symb {
                   11972:     my ($map,$resid,$url)=@_;
                   11973:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   11974: }
1.409     www      11975: 
                   11976: sub decode_symb {
1.568     albertel 11977:     my $symb=shift;
                   11978:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   11979:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      11980:     return (&fixversion($map),$resid,&fixversion($url));
                   11981: }
                   11982: 
                   11983: sub fixversion {
                   11984:     my $fn=shift;
1.609     banghart 11985:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      11986:     my %bighash;
                   11987:     my $uri=&clutter($fn);
1.620     albertel 11988:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      11989: # is this cached?
1.599     albertel 11990:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      11991:     if (defined($cached)) { return $result; }
                   11992: # unfortunately not cached, or expired
1.620     albertel 11993:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      11994: 	    &GDBM_READER(),0640)) {
                   11995:  	if ($bighash{'version_'.$uri}) {
                   11996:  	    my $version=$bighash{'version_'.$uri};
1.444     www      11997:  	    unless (($version eq 'mostrecent') || 
                   11998: 		    ($version==&getversion($uri))) {
1.440     www      11999:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12000:  	    }
                   12001:  	}
                   12002:  	untie %bighash;
1.413     www      12003:     }
1.599     albertel 12004:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12005: }
                   12006: 
                   12007: sub deversion {
                   12008:     my $url=shift;
                   12009:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12010:     return $url;
1.210     www      12011: }
                   12012: 
1.31      www      12013: # ------------------------------------------------------ Return symb list entry
                   12014: 
                   12015: sub symbread {
1.1282    raeburn  12016:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12017:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12018:     if (defined($env{$cache_str})) {
                   12019:         if ($ignorecachednull) {
                   12020:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12021:         } else {
                   12022:             return $env{$cache_str};
                   12023:         }
                   12024:     }
1.242     www      12025: # no filename provided? try from environment
1.1265    raeburn  12026:     unless ($thisfn) {
1.620     albertel 12027:         if ($env{'request.symb'}) {
                   12028: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12029: 	}
1.620     albertel 12030: 	$thisfn=$env{'request.filename'};
1.44      www      12031:     }
1.569     albertel 12032:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12033: # is that filename actually a symb? Verify, clean, and return
                   12034:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12035: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12036: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12037: 	}
1.242     www      12038:     }
1.44      www      12039:     $thisfn=declutter($thisfn);
1.31      www      12040:     my %hash;
1.37      www      12041:     my %bighash;
                   12042:     my $syval='';
1.620     albertel 12043:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12044:         my $targetfn = $thisfn;
1.609     banghart 12045:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12046:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12047:         }
1.687     albertel 12048: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12049: 	    $targetfn=$1;
                   12050: 	}
1.620     albertel 12051:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12052:                       &GDBM_READER(),0640)) {
1.481     raeburn  12053: 	    $syval=$hash{$targetfn};
1.37      www      12054:             untie(%hash);
                   12055:         }
                   12056: # ---------------------------------------------------------- There was an entry
                   12057:         if ($syval) {
1.601     albertel 12058: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12059: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12060: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12061: 		    #return $env{$cache_str}='';
1.601     albertel 12062: 		#}    
                   12063: 		#$syval.=$1;
                   12064: 	    #}
1.37      www      12065:         } else {
                   12066: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12067:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12068:                             &GDBM_READER(),0640)) {
1.37      www      12069: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12070:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12071:               unless ($ids) { 
                   12072:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12073:               }
                   12074:               unless ($ids) {
                   12075: # alias?
                   12076: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12077:               }
1.37      www      12078:               if ($ids) {
                   12079: # ------------------------------------------------------------------- Has ID(s)
                   12080:                  my @possibilities=split(/\,/,$ids);
1.39      www      12081:                  if ($#possibilities==0) {
                   12082: # ----------------------------------------------- There is only one possibility
1.37      www      12083: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12084: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12085: 						    $resid,$thisfn);
1.1282    raeburn  12086:                      if (ref($possibles) eq 'HASH') {
                   12087:                          $possibles->{$syval} = 1;    
                   12088:                      }
                   12089:                      if ($checkforblock) {
                   12090:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12091:                          if (@blockers) {
                   12092:                              $syval = '';
                   12093:                              return;
                   12094:                          }
                   12095:                      }
                   12096:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12097: # ------------------------------------------ There is more than one possibility
                   12098:                      my $realpossible=0;
1.800     albertel 12099:                      foreach my $id (@possibilities) {
                   12100: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12101:                          my $canaccess;
                   12102:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12103:                              $canaccess = 1;
                   12104:                          } else { 
                   12105:                              $canaccess = &allowed('bre',$file);
                   12106:                          }
                   12107:                          if ($canaccess) {
                   12108:          		     my ($mapid,$resid)=split(/\./,$id);
                   12109:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12110:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12111: 						             $resid,$thisfn);
                   12112:                                  if (ref($possibles) eq 'HASH') {
                   12113:                                      $possibles->{$syval} = 1;
                   12114:                                  }
                   12115:                                  if ($checkforblock) {
                   12116:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12117:                                      unless (@blockers > 0) {
                   12118:                                          $syval = $poss_syval;
                   12119:                                          $realpossible++;
                   12120:                                      }
                   12121:                                  } else {
                   12122:                                      $syval = $poss_syval;
                   12123:                                      $realpossible++;
                   12124:                                  }
                   12125:                              }
1.39      www      12126: 			 }
1.191     harris41 12127:                      }
1.39      www      12128: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12129:                  } else {
                   12130:                      $syval='';
1.37      www      12131:                  }
                   12132: 	      }
1.1282    raeburn  12133:               untie(%bighash);
1.481     raeburn  12134:            }
1.31      www      12135:         }
1.62      www      12136:         if ($syval) {
1.620     albertel 12137: 	    return $env{$cache_str}=$syval;
1.62      www      12138:         }
1.31      www      12139:     }
1.949     raeburn  12140:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12141:     return $env{$cache_str}='';
1.31      www      12142: }
                   12143: 
                   12144: # ---------------------------------------------------------- Return random seed
                   12145: 
1.32      www      12146: sub numval {
                   12147:     my $txt=shift;
                   12148:     $txt=~tr/A-J/0-9/;
                   12149:     $txt=~tr/a-j/0-9/;
                   12150:     $txt=~tr/K-T/0-9/;
                   12151:     $txt=~tr/k-t/0-9/;
                   12152:     $txt=~tr/U-Z/0-5/;
                   12153:     $txt=~tr/u-z/0-5/;
                   12154:     $txt=~s/\D//g;
1.564     albertel 12155:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12156:     return int($txt);
1.368     albertel 12157: }
                   12158: 
1.484     albertel 12159: sub numval2 {
                   12160:     my $txt=shift;
                   12161:     $txt=~tr/A-J/0-9/;
                   12162:     $txt=~tr/a-j/0-9/;
                   12163:     $txt=~tr/K-T/0-9/;
                   12164:     $txt=~tr/k-t/0-9/;
                   12165:     $txt=~tr/U-Z/0-5/;
                   12166:     $txt=~tr/u-z/0-5/;
                   12167:     $txt=~s/\D//g;
                   12168:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12169:     my $total;
                   12170:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12171:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12172:     return int($total);
                   12173: }
                   12174: 
1.575     albertel 12175: sub numval3 {
                   12176:     use integer;
                   12177:     my $txt=shift;
                   12178:     $txt=~tr/A-J/0-9/;
                   12179:     $txt=~tr/a-j/0-9/;
                   12180:     $txt=~tr/K-T/0-9/;
                   12181:     $txt=~tr/k-t/0-9/;
                   12182:     $txt=~tr/U-Z/0-5/;
                   12183:     $txt=~tr/u-z/0-5/;
                   12184:     $txt=~s/\D//g;
                   12185:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12186:     my $total;
                   12187:     foreach my $val (@txts) { $total+=$val; }
                   12188:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12189:     return $total;
                   12190: }
                   12191: 
1.675     albertel 12192: sub digest {
                   12193:     my ($data)=@_;
                   12194:     my $digest=&Digest::MD5::md5($data);
                   12195:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12196:     my ($e,$f);
                   12197:     {
                   12198:         use integer;
                   12199:         $e=($a+$b);
                   12200:         $f=($c+$d);
                   12201:         if ($_64bit) {
                   12202:             $e=(($e<<32)>>32);
                   12203:             $f=(($f<<32)>>32);
                   12204:         }
                   12205:     }
                   12206:     if (wantarray) {
                   12207: 	return ($e,$f);
                   12208:     } else {
                   12209: 	my $g;
                   12210: 	{
                   12211: 	    use integer;
                   12212: 	    $g=($e+$f);
                   12213: 	    if ($_64bit) {
                   12214: 		$g=(($g<<32)>>32);
                   12215: 	    }
                   12216: 	}
                   12217: 	return $g;
                   12218:     }
                   12219: }
                   12220: 
1.368     albertel 12221: sub latest_rnd_algorithm_id {
1.675     albertel 12222:     return '64bit5';
1.366     albertel 12223: }
1.32      www      12224: 
1.503     albertel 12225: sub get_rand_alg {
                   12226:     my ($courseid)=@_;
1.790     albertel 12227:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12228:     if ($courseid) {
1.620     albertel 12229: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12230:     }
                   12231:     return &latest_rnd_algorithm_id();
                   12232: }
                   12233: 
1.562     albertel 12234: sub validCODE {
                   12235:     my ($CODE)=@_;
                   12236:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12237:     return 0;
                   12238: }
                   12239: 
1.491     albertel 12240: sub getCODE {
1.620     albertel 12241:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12242:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12243: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12244: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12245: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12246:     }
                   12247:     return undef;
                   12248: }
1.1133    foxr     12249: #
                   12250: #  Determines the random seed for a specific context:
                   12251: #
                   12252: # parameters:
                   12253: #   symb      - in course context the symb for the seed.
                   12254: #   course_id - The course id of the form domain_coursenum.
                   12255: #   domain    - Domain for the user.
                   12256: #   course    - Course for the user.
                   12257: #   cenv      - environment of the course.
                   12258: #
                   12259: # NOTE:
                   12260: #   All parameters are picked out of the environment if missing
                   12261: #   or not defined.
                   12262: #   If a symb cannot be determined the current time is used instead.
                   12263: #
                   12264: #  For a given well defined symb, courside, domain, username,
                   12265: #  and course environment, the seed is reproducible.
                   12266: #
1.31      www      12267: sub rndseed {
1.1133    foxr     12268:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12269:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12270:     if (!defined($symb)) {
1.366     albertel 12271: 	unless ($symb=$wsymb) { return time; }
                   12272:     }
1.1146    foxr     12273:     if (!defined $courseid) { 
                   12274: 	$courseid=$wcourseid; 
                   12275:     }
                   12276:     if (!defined $domain) { $domain=$wdomain; }
                   12277:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12278: 
                   12279:     my $which;
                   12280:     if (defined($cenv->{'rndseed'})) {
                   12281: 	$which = $cenv->{'rndseed'};
                   12282:     } else {
                   12283: 	$which =&get_rand_alg($courseid);
                   12284:     }
1.491     albertel 12285:     if (defined(&getCODE())) {
1.1133    foxr     12286: 
1.675     albertel 12287: 	if ($which eq '64bit5') {
                   12288: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12289: 	} elsif ($which eq '64bit4') {
1.575     albertel 12290: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12291: 	} else {
                   12292: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12293: 	}
1.675     albertel 12294:     } elsif ($which eq '64bit5') {
                   12295: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12296:     } elsif ($which eq '64bit4') {
                   12297: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12298:     } elsif ($which eq '64bit3') {
                   12299: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12300:     } elsif ($which eq '64bit2') {
                   12301: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12302:     } elsif ($which eq '64bit') {
                   12303: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12304:     }
                   12305:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12306: }
                   12307: 
                   12308: sub rndseed_32bit {
                   12309:     my ($symb,$courseid,$domain,$username)=@_;
                   12310:     {
                   12311: 	use integer;
                   12312: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12313: 	my $symbseed=numval($symb) << 22;
                   12314: 	my $namechck=unpack("%32C*",$username) << 17;
                   12315: 	my $nameseed=numval($username) << 12;
                   12316: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12317: 	my $courseseed=unpack("%32C*",$courseid);
                   12318: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12319: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12320: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12321: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12322: 	return $num;
                   12323:     }
                   12324: }
                   12325: 
                   12326: sub rndseed_64bit {
                   12327:     my ($symb,$courseid,$domain,$username)=@_;
                   12328:     {
                   12329: 	use integer;
                   12330: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12331: 	my $symbseed=numval($symb) << 10;
                   12332: 	my $namechck=unpack("%32S*",$username);
                   12333: 	
                   12334: 	my $nameseed=numval($username) << 21;
                   12335: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12336: 	my $courseseed=unpack("%32S*",$courseid);
                   12337: 	
                   12338: 	my $num1=$symbchck+$symbseed+$namechck;
                   12339: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12340: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12341: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12342: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12343: 	return "$num1,$num2";
1.155     albertel 12344:     }
1.366     albertel 12345: }
                   12346: 
1.443     albertel 12347: sub rndseed_64bit2 {
                   12348:     my ($symb,$courseid,$domain,$username)=@_;
                   12349:     {
                   12350: 	use integer;
                   12351: 	# strings need to be an even # of cahracters long, it it is odd the
                   12352:         # last characters gets thrown away
                   12353: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12354: 	my $symbseed=numval($symb) << 10;
                   12355: 	my $namechck=unpack("%32S*",$username.' ');
                   12356: 	
                   12357: 	my $nameseed=numval($username) << 21;
1.501     albertel 12358: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12359: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12360: 	
                   12361: 	my $num1=$symbchck+$symbseed+$namechck;
                   12362: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12363: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12364: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12365: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12366: 	return "$num1,$num2";
                   12367:     }
                   12368: }
                   12369: 
                   12370: sub rndseed_64bit3 {
                   12371:     my ($symb,$courseid,$domain,$username)=@_;
                   12372:     {
                   12373: 	use integer;
                   12374: 	# strings need to be an even # of cahracters long, it it is odd the
                   12375:         # last characters gets thrown away
                   12376: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12377: 	my $symbseed=numval2($symb) << 10;
                   12378: 	my $namechck=unpack("%32S*",$username.' ');
                   12379: 	
                   12380: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12381: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12382: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12383: 	
                   12384: 	my $num1=$symbchck+$symbseed+$namechck;
                   12385: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12386: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12387: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12388: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12389: 	
1.503     albertel 12390: 	return "$num1:$num2";
1.443     albertel 12391:     }
                   12392: }
                   12393: 
1.575     albertel 12394: sub rndseed_64bit4 {
                   12395:     my ($symb,$courseid,$domain,$username)=@_;
                   12396:     {
                   12397: 	use integer;
                   12398: 	# strings need to be an even # of cahracters long, it it is odd the
                   12399:         # last characters gets thrown away
                   12400: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12401: 	my $symbseed=numval3($symb) << 10;
                   12402: 	my $namechck=unpack("%32S*",$username.' ');
                   12403: 	
                   12404: 	my $nameseed=numval3($username) << 21;
                   12405: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12406: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12407: 	
                   12408: 	my $num1=$symbchck+$symbseed+$namechck;
                   12409: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12410: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12411: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12412: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12413: 	
1.575     albertel 12414: 	return "$num1:$num2";
                   12415:     }
                   12416: }
                   12417: 
1.675     albertel 12418: sub rndseed_64bit5 {
                   12419:     my ($symb,$courseid,$domain,$username)=@_;
                   12420:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12421:     return "$num1:$num2";
                   12422: }
                   12423: 
1.366     albertel 12424: sub rndseed_CODE_64bit {
                   12425:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12426:     {
1.366     albertel 12427: 	use integer;
1.443     albertel 12428: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12429: 	my $symbseed=numval2($symb);
1.491     albertel 12430: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12431: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12432: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12433: 	my $num1=$symbseed+$CODEchck;
                   12434: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12435: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12436: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12437: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12438: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12439: 	return "$num1:$num2";
1.366     albertel 12440:     }
                   12441: }
                   12442: 
1.575     albertel 12443: sub rndseed_CODE_64bit4 {
                   12444:     my ($symb,$courseid,$domain,$username)=@_;
                   12445:     {
                   12446: 	use integer;
                   12447: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12448: 	my $symbseed=numval3($symb);
                   12449: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12450: 	my $CODEseed=numval3(&getCODE());
                   12451: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12452: 	my $num1=$symbseed+$CODEchck;
                   12453: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12454: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12455: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12456: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12457: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12458: 	return "$num1:$num2";
                   12459:     }
                   12460: }
                   12461: 
1.675     albertel 12462: sub rndseed_CODE_64bit5 {
                   12463:     my ($symb,$courseid,$domain,$username)=@_;
                   12464:     my $code = &getCODE();
                   12465:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12466:     return "$num1:$num2";
                   12467: }
                   12468: 
1.366     albertel 12469: sub setup_random_from_rndseed {
                   12470:     my ($rndseed)=@_;
1.503     albertel 12471:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12472:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12473:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12474:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12475:         } else {
                   12476:             &Math::Random::random_set_seed($num1,$num2);
                   12477:         }
1.366     albertel 12478:     } else {
                   12479: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12480:     }
1.36      albertel 12481: }
                   12482: 
1.474     albertel 12483: sub latest_receipt_algorithm_id {
1.835     albertel 12484:     return 'receipt3';
1.474     albertel 12485: }
                   12486: 
1.480     www      12487: sub recunique {
                   12488:     my $fucourseid=shift;
                   12489:     my $unique;
1.835     albertel 12490:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12491: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12492: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12493:     } else {
                   12494: 	$unique=$perlvar{'lonReceipt'};
                   12495:     }
                   12496:     return unpack("%32C*",$unique);
                   12497: }
                   12498: 
                   12499: sub recprefix {
                   12500:     my $fucourseid=shift;
                   12501:     my $prefix;
1.835     albertel 12502:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12503: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12504: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12505:     } else {
                   12506: 	$prefix=$perlvar{'lonHostID'};
                   12507:     }
                   12508:     return unpack("%32C*",$prefix);
                   12509: }
                   12510: 
1.76      www      12511: sub ireceipt {
1.474     albertel 12512:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12513: 
                   12514:     my $return =&recprefix($fucourseid).'-';
                   12515: 
                   12516:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12517: 	$env{'request.state'} eq 'construct') {
                   12518: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12519: 	return $return;
                   12520:     }
                   12521: 
1.76      www      12522:     my $cuname=unpack("%32C*",$funame);
                   12523:     my $cudom=unpack("%32C*",$fudom);
                   12524:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12525:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12526:     my $cunique=&recunique($fucourseid);
1.474     albertel 12527:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12528:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12529: 
1.790     albertel 12530: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12531: 			       
                   12532: 	$return.= ($cunique%$cuname+
                   12533: 		   $cunique%$cudom+
                   12534: 		   $cusymb%$cuname+
                   12535: 		   $cusymb%$cudom+
                   12536: 		   $cucourseid%$cuname+
                   12537: 		   $cucourseid%$cudom+
                   12538: 		   $cpart%$cuname+
                   12539: 		   $cpart%$cudom);
                   12540:     } else {
                   12541: 	$return.= ($cunique%$cuname+
                   12542: 		   $cunique%$cudom+
                   12543: 		   $cusymb%$cuname+
                   12544: 		   $cusymb%$cudom+
                   12545: 		   $cucourseid%$cuname+
                   12546: 		   $cucourseid%$cudom);
                   12547:     }
                   12548:     return $return;
1.76      www      12549: }
                   12550: 
                   12551: sub receipt {
1.474     albertel 12552:     my ($part)=@_;
1.790     albertel 12553:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12554:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12555: }
1.260     ng       12556: 
1.790     albertel 12557: sub whichuser {
                   12558:     my ($passedsymb)=@_;
                   12559:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12560:     if (defined($env{'form.grade_symb'})) {
                   12561: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12562: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12563: 	if (!$allowed &&
                   12564: 	    exists($env{'request.course.sec'}) &&
                   12565: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12566: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12567: 			      '/'.$env{'request.course.sec'});
                   12568: 	}
                   12569: 	if ($allowed) {
                   12570: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12571: 	    $courseid=$tmp_courseid;
                   12572: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12573: 	    ($name)=&get_env_multiple('form.grade_username');
                   12574: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12575: 	}
                   12576:     }
                   12577:     if (!$passedsymb) {
                   12578: 	$symb=&symbread();
                   12579:     } else {
                   12580: 	$symb=$passedsymb;
                   12581:     }
                   12582:     $courseid=$env{'request.course.id'};
                   12583:     $domain=$env{'user.domain'};
                   12584:     $name=$env{'user.name'};
                   12585:     if ($name eq 'public' && $domain eq 'public') {
                   12586: 	if (!defined($env{'form.username'})) {
                   12587: 	    $env{'form.username'}.=time.rand(10000000);
                   12588: 	}
                   12589: 	$name.=$env{'form.username'};
                   12590:     }
                   12591:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12592: 
                   12593: }
                   12594: 
1.36      albertel 12595: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12596: # returns either the contents of the file or 
                   12597: # -1 if the file doesn't exist
1.481     raeburn  12598: #
                   12599: # if the target is a file that was uploaded via DOCS, 
                   12600: # a check will be made to see if a current copy exists on the local server,
                   12601: # if it does this will be served, otherwise a copy will be retrieved from
                   12602: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12603: # the local server.   
1.472     albertel 12604: 
1.36      albertel 12605: sub getfile {
1.538     albertel 12606:     my ($file) = @_;
1.609     banghart 12607:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12608:     &repcopy($file);
                   12609:     return &readfile($file);
                   12610: }
                   12611: 
                   12612: sub repcopy_userfile {
                   12613:     my ($file)=@_;
1.1142    raeburn  12614:     my $londocroot = $perlvar{'lonDocRoot'};
                   12615:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12616:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12617:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12618: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12619:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12620:     if (-e "$file") {
1.828     www      12621: # we already have a local copy, check it out
1.538     albertel 12622: 	my @fileinfo = stat($file);
1.828     www      12623: 	my $rtncode;
                   12624: 	my $info;
1.538     albertel 12625: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12626: 	if ($lwpresp ne 'ok') {
1.828     www      12627: # there is no such file anymore, even though we had a local copy
1.482     albertel 12628: 	    if ($rtncode eq '404') {
1.538     albertel 12629: 		unlink($file);
1.482     albertel 12630: 	    }
                   12631: 	    return -1;
                   12632: 	}
                   12633: 	if ($info < $fileinfo[9]) {
1.828     www      12634: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12635: 	    return 'ok';
1.828     www      12636: 	} else {
                   12637: # the file is outdated, get rid of it
                   12638: 	    unlink($file);
1.482     albertel 12639: 	}
1.828     www      12640:     }
                   12641: # one way or the other, at this point, we don't have the file
                   12642: # construct the correct path for the file
                   12643:     my @parts = ($cdom,$cnum); 
                   12644:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12645: 	push @parts, split(/\//,$1);
                   12646:     }
                   12647:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12648:     foreach my $part (@parts) {
                   12649: 	$path .= '/'.$part;
                   12650: 	if (!-e $path) {
                   12651: 	    mkdir($path,0770);
1.482     albertel 12652: 	}
                   12653:     }
1.828     www      12654: # now the path exists for sure
                   12655: # get a user agent
                   12656:     my $ua=new LWP::UserAgent;
                   12657:     my $transferfile=$file.'.in.transfer';
                   12658: # FIXME: this should flock
                   12659:     if (-e $transferfile) { return 'ok'; }
                   12660:     my $request;
                   12661:     $uri=~s/^\///;
1.980     raeburn  12662:     my $homeserver = &homeserver($cnum,$cdom);
                   12663:     my $protocol = $protocol{$homeserver};
                   12664:     $protocol = 'http' if ($protocol ne 'https');
                   12665:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      12666:     my $response=$ua->request($request,$transferfile);
                   12667: # did it work?
                   12668:     if ($response->is_error()) {
                   12669: 	unlink($transferfile);
                   12670: 	&logthis("Userfile repcopy failed for $uri");
                   12671: 	return -1;
                   12672:     }
                   12673: # worked, rename the transfer file
                   12674:     rename($transferfile,$file);
1.607     raeburn  12675:     return 'ok';
1.481     raeburn  12676: }
                   12677: 
1.517     albertel 12678: sub tokenwrapper {
                   12679:     my $uri=shift;
1.980     raeburn  12680:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12681:     $uri=~s|^/||;
1.620     albertel 12682:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12683:     my $token=$1;
1.552     albertel 12684:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12685:     if ($udom && $uname && $file) {
                   12686: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12687:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12688:         my $homeserver = &homeserver($uname,$udom);
                   12689:         my $protocol = $protocol{$homeserver};
                   12690:         $protocol = 'http' if ($protocol ne 'https');
                   12691:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12692:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12693:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12694:     } else {
                   12695:         return '/adm/notfound.html';
                   12696:     }
                   12697: }
                   12698: 
1.828     www      12699: # call with reqtype HEAD: get last modification time
                   12700: # call with reqtype GET: get the file contents
                   12701: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12702: #
1.481     raeburn  12703: sub getuploaded {
                   12704:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12705:     $uri=~s/^\///;
1.980     raeburn  12706:     my $homeserver = &homeserver($cnum,$cdom);
                   12707:     my $protocol = $protocol{$homeserver};
                   12708:     $protocol = 'http' if ($protocol ne 'https');
                   12709:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12710:     my $ua=new LWP::UserAgent;
                   12711:     my $request=new HTTP::Request($reqtype,$uri);
                   12712:     my $response=$ua->request($request);
                   12713:     $$rtncode = $response->code;
1.482     albertel 12714:     if (! $response->is_success()) {
                   12715: 	return 'failed';
                   12716:     }      
                   12717:     if ($reqtype eq 'HEAD') {
1.486     www      12718: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12719:     } elsif ($reqtype eq 'GET') {
                   12720: 	$$info = $response->content;
1.472     albertel 12721:     }
1.482     albertel 12722:     return 'ok';
1.36      albertel 12723: }
                   12724: 
1.481     raeburn  12725: sub readfile {
                   12726:     my $file = shift;
                   12727:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12728:     my $fh;
                   12729:     open($fh,"<$file");
                   12730:     my $a='';
1.800     albertel 12731:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12732:     return $a;
                   12733: }
                   12734: 
1.36      albertel 12735: sub filelocation {
1.590     banghart 12736:     my ($dir,$file) = @_;
                   12737:     my $location;
                   12738:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12739: 
                   12740:     if ($file =~ m-^/adm/-) {
                   12741: 	$file=~s-^/adm/wrapper/-/-;
                   12742: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12743:     }
1.882     albertel 12744: 
1.1139    www      12745:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12746:         $location = $file;
1.609     banghart 12747:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12748:         my ($udom,$uname,$filename)=
1.811     albertel 12749:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12750:         my $home=&homeserver($uname,$udom);
                   12751:         my $is_me=0;
                   12752:         my @ids=&current_machine_ids();
                   12753:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12754:         if ($is_me) {
1.1117    foxr     12755:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12756:         } else {
                   12757:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12758:   	      $udom.'/'.$uname.'/'.$filename;
                   12759:         }
1.882     albertel 12760:     } elsif ($file =~ m-^/adm/-) {
                   12761: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12762:     } else {
                   12763:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12764:         $file=~s:^/(res|priv)/:/:;
                   12765:         my $space=$1;
1.590     banghart 12766:         if ( !( $file =~ m:^/:) ) {
                   12767:             $location = $dir. '/'.$file;
                   12768:         } else {
1.1142    raeburn  12769:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12770:         }
1.59      albertel 12771:     }
1.590     banghart 12772:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12773:     while ($location=~m{/\.\./}) {
                   12774: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12775: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12776: 	} else {
                   12777: 	    $location=~ s{/\.\./}{/}g;
                   12778: 	}
                   12779:     } #remove dir/..
1.590     banghart 12780:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12781:     return $location;
1.46      www      12782: }
1.36      albertel 12783: 
1.46      www      12784: sub hreflocation {
                   12785:     my ($dir,$file)=@_;
1.980     raeburn  12786:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12787: 	$file=filelocation($dir,$file);
1.700     albertel 12788:     } elsif ($file=~m-^/adm/-) {
                   12789: 	$file=~s-^/adm/wrapper/-/-;
                   12790: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12791:     }
                   12792:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12793: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12794:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12795: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12796: 	        {/uploaded/$1/$2/}x;
1.46      www      12797:     }
1.913     albertel 12798:     if ($file=~ m{^/userfiles/}) {
                   12799: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12800:     }
1.462     albertel 12801:     return $file;
1.465     albertel 12802: }
                   12803: 
1.1139    www      12804: 
                   12805: 
                   12806: 
                   12807: 
1.465     albertel 12808: sub current_machine_domains {
1.853     albertel 12809:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12810: }
                   12811: 
                   12812: sub machine_domains {
                   12813:     my ($hostname) = @_;
1.465     albertel 12814:     my @domains;
1.838     albertel 12815:     my %hostname = &all_hostnames();
1.465     albertel 12816:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12817: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12818: 	if ($hostname eq $name) {
1.844     albertel 12819: 	    push(@domains,&host_domain($id));
1.465     albertel 12820: 	}
                   12821:     }
                   12822:     return @domains;
                   12823: }
                   12824: 
                   12825: sub current_machine_ids {
1.853     albertel 12826:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12827: }
                   12828: 
                   12829: sub machine_ids {
                   12830:     my ($hostname) = @_;
                   12831:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12832:     my @ids;
1.888     albertel 12833:     my %name_to_host = &all_names();
1.889     albertel 12834:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12835: 	return @{ $name_to_host{$hostname} };
                   12836:     }
                   12837:     return;
1.31      www      12838: }
                   12839: 
1.824     raeburn  12840: sub additional_machine_domains {
                   12841:     my @domains;
                   12842:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12843:     while( my $line = <$fh>) {
                   12844:         $line =~ s/\s//g;
                   12845:         push(@domains,$line);
                   12846:     }
                   12847:     return @domains;
                   12848: }
                   12849: 
                   12850: sub default_login_domain {
                   12851:     my $domain = $perlvar{'lonDefDomain'};
                   12852:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12853:     foreach my $posdom (&current_machine_domains(),
                   12854:                         &additional_machine_domains()) {
                   12855:         if (lc($posdom) eq lc($testdomain)) {
                   12856:             $domain=$posdom;
                   12857:             last;
                   12858:         }
                   12859:     }
                   12860:     return $domain;
                   12861: }
                   12862: 
1.31      www      12863: # ------------------------------------------------------------- Declutters URLs
                   12864: 
                   12865: sub declutter {
                   12866:     my $thisfn=shift;
1.569     albertel 12867:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12868:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12869:         $thisfn=~s{^/home/httpd/html}{};
                   12870:     }
1.31      www      12871:     $thisfn=~s/^\///;
1.697     albertel 12872:     $thisfn=~s|^adm/wrapper/||;
                   12873:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12874:     $thisfn=~s/^res\///;
1.1172    bisitz   12875:     $thisfn=~s/^priv\///;
1.1032    raeburn  12876:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12877:         $thisfn=~s/\?.+$//;
                   12878:     }
1.268     www      12879:     return $thisfn;
                   12880: }
                   12881: 
                   12882: # ------------------------------------------------------------- Clutter up URLs
                   12883: 
                   12884: sub clutter {
                   12885:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12886:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 12887: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      12888:        $thisfn='/res'.$thisfn; 
                   12889:     }
1.1031    raeburn  12890:     if ($thisfn !~m|^/adm|) {
                   12891: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 12892: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 12893: 	} else {
                   12894: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   12895: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 12896: 	    if ($embstyle eq 'ssi'
                   12897: 		|| ($embstyle eq 'hdn')
                   12898: 		|| ($embstyle eq 'rat')
                   12899: 		|| ($embstyle eq 'prv')
                   12900: 		|| ($embstyle eq 'ign')) {
                   12901: 		#do nothing with these
                   12902: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 12903: 		|| ($embstyle eq 'emb')
                   12904: 		|| ($embstyle eq 'wrp')) {
                   12905: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 12906: 	    } elsif ($embstyle eq 'unk'
                   12907: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 12908: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 12909: 	    } else {
1.718     www      12910: #		&logthis("Got a blank emb style");
1.695     albertel 12911: 	    }
1.694     albertel 12912: 	}
1.1298    raeburn  12913:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/exttools?$}) {
                   12914:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 12915:     }
1.31      www      12916:     return $thisfn;
1.12      www      12917: }
                   12918: 
1.787     albertel 12919: sub clutter_with_no_wrapper {
                   12920:     my $uri = &clutter(shift);
                   12921:     if ($uri =~ m-^/adm/-) {
                   12922: 	$uri =~ s-^/adm/wrapper/-/-;
                   12923: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   12924:     }
                   12925:     return $uri;
                   12926: }
                   12927: 
1.557     albertel 12928: sub freeze_escape {
                   12929:     my ($value)=@_;
                   12930:     if (ref($value)) {
                   12931: 	$value=&nfreeze($value);
                   12932: 	return '__FROZEN__'.&escape($value);
                   12933:     }
                   12934:     return &escape($value);
                   12935: }
                   12936: 
1.11      www      12937: 
1.557     albertel 12938: sub thaw_unescape {
                   12939:     my ($value)=@_;
                   12940:     if ($value =~ /^__FROZEN__/) {
                   12941: 	substr($value,0,10,undef);
                   12942: 	$value=&unescape($value);
                   12943: 	return &thaw($value);
                   12944:     }
                   12945:     return &unescape($value);
                   12946: }
                   12947: 
1.436     albertel 12948: sub correct_line_ends {
                   12949:     my ($result)=@_;
                   12950:     $$result =~s/\r\n/\n/mg;
                   12951:     $$result =~s/\r/\n/mg;
1.415     albertel 12952: }
1.1       albertel 12953: # ================================================================ Main Program
                   12954: 
1.184     www      12955: sub goodbye {
1.204     albertel 12956:    &logthis("Starting Shut down");
1.443     albertel 12957: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 12958:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 12959: #converted
1.599     albertel 12960: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 12961:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   12962: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   12963: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 12964: #1.1 only
1.870     albertel 12965: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   12966: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   12967: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   12968: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   12969:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 12970:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   12971:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      12972:    &flushcourselogs();
                   12973:    &logthis("Shutting down");
                   12974: }
                   12975: 
1.852     albertel 12976: sub get_dns {
1.1210    raeburn  12977:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 12978:     if (!$ignore_cache) {
                   12979: 	my ($content,$cached)=
                   12980: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   12981: 	if ($cached) {
1.1210    raeburn  12982: 	    &$func($content,$hashref);
1.869     albertel 12983: 	    return;
                   12984: 	}
                   12985:     }
                   12986: 
                   12987:     my %alldns;
1.852     albertel 12988:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   12989:     foreach my $dns (<$config>) {
                   12990: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  12991:         my $line = $1;
                   12992:         my ($host,$protocol) = split(/:/,$line);
                   12993:         if ($protocol ne 'https') {
                   12994:             $protocol = 'http';
                   12995:         }
                   12996: 	$alldns{$host} = $protocol;
1.869     albertel 12997:     }
                   12998:     while (%alldns) {
1.1263    raeburn  12999: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.852     albertel 13000: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  13001:         $ua->timeout(30);
1.979     raeburn  13002: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 13003: 	my $response=$ua->request($request);
1.979     raeburn  13004:         delete($alldns{$dns});
1.852     albertel 13005: 	next if ($response->is_error());
                   13006: 	my @content = split("\n",$response->content);
1.1210    raeburn  13007: 	unless ($nocache) {
1.1219    raeburn  13008: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13009: 	}
                   13010: 	&$func(\@content,$hashref);
1.869     albertel 13011: 	return;
1.852     albertel 13012:     }
                   13013:     close($config);
1.871     albertel 13014:     my $which = (split('/',$url))[3];
                   13015:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13016:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13017:     my @content = <$config>;
1.1210    raeburn  13018:     &$func(\@content,$hashref);
                   13019:     return;
                   13020: }
                   13021: 
                   13022: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13023: sub parse_dns_checksums_tab {
1.1210    raeburn  13024:     my ($lines,$hashref) = @_;
1.1264    raeburn  13025:     my $lonhost = $perlvar{'lonHostID'};
                   13026:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13027:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13028:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13029:     my $webconfdir = '/etc/httpd/conf';
                   13030:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13031:         $webconfdir = '/etc/apache2';
                   13032:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13033:         if ($1 >= 10) {
                   13034:             $webconfdir = '/etc/apache2';
                   13035:         }
                   13036:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13037:         if ($1 >= 10.0) {
                   13038:             $webconfdir = '/etc/apache2';
                   13039:         }
                   13040:     }
1.1210    raeburn  13041:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13042:     my (%chksum,%revnum);
                   13043:     if (ref($lines) eq 'ARRAY') {
                   13044:         chomp(@{$lines});
1.1238    raeburn  13045:         my $version = shift(@{$lines});
                   13046:         if ($version eq $release) {  
1.1210    raeburn  13047:             foreach my $line (@{$lines}) {
1.1238    raeburn  13048:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13049:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13050:                     if ($webconfdir eq '/etc/apache2') {
                   13051:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13052:                     }
                   13053:                 }
1.1238    raeburn  13054:                 $chksum{$file} = $shasum;
                   13055:                 $revnum{$file} = $version;
1.1210    raeburn  13056:             }
                   13057:             if (ref($hashref) eq 'HASH') {
                   13058:                 %{$hashref} = (
                   13059:                                 sums     => \%chksum,
                   13060:                                 versions => \%revnum,
                   13061:                               );
                   13062:             }
                   13063:         }
                   13064:     }
1.869     albertel 13065:     return;
1.852     albertel 13066: }
1.1210    raeburn  13067: 
                   13068: sub fetch_dns_checksums {
1.1238    raeburn  13069:     my %checksums;
                   13070:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13071:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13072:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13073:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13074:              \%checksums);
1.1210    raeburn  13075:     return \%checksums;
                   13076: }
                   13077: 
1.327     albertel 13078: # ------------------------------------------------------------ Read domain file
                   13079: {
1.852     albertel 13080:     my $loaded;
1.846     albertel 13081:     my %domain;
                   13082: 
1.852     albertel 13083:     sub parse_domain_tab {
                   13084: 	my ($lines) = @_;
                   13085: 	foreach my $line (@$lines) {
                   13086: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13087: 
1.846     albertel 13088: 	    chomp($line);
1.852     albertel 13089: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13090: 	    my %this_domain;
                   13091: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13092: 			       'lang_def', 'city', 'longi', 'lati',
                   13093: 			       'primary') {
                   13094: 		$this_domain{$field} = shift(@elements);
                   13095: 	    }
                   13096: 	    $domain{$name} = \%this_domain;
1.852     albertel 13097: 	}
                   13098:     }
1.864     albertel 13099: 
                   13100:     sub reset_domain_info {
                   13101: 	undef($loaded);
                   13102: 	undef(%domain);
                   13103:     }
                   13104: 
1.852     albertel 13105:     sub load_domain_tab {
1.1293    raeburn  13106: 	my ($ignore_cache,$nocache) = @_;
                   13107: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13108: 	my $fh;
                   13109: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   13110: 	    my @lines = <$fh>;
                   13111: 	    &parse_domain_tab(\@lines);
1.448     albertel 13112: 	}
1.852     albertel 13113: 	close($fh);
                   13114: 	$loaded = 1;
1.327     albertel 13115:     }
1.846     albertel 13116: 
                   13117:     sub domain {
1.852     albertel 13118: 	&load_domain_tab() if (!$loaded);
                   13119: 
1.846     albertel 13120: 	my ($name,$what) = @_;
                   13121: 	return if ( !exists($domain{$name}) );
                   13122: 
                   13123: 	if (!$what) {
                   13124: 	    return $domain{$name}{'description'};
                   13125: 	}
                   13126: 	return $domain{$name}{$what};
                   13127:     }
1.974     raeburn  13128: 
                   13129:     sub domain_info {
                   13130:         &load_domain_tab() if (!$loaded);
                   13131:         return %domain;
                   13132:     }
                   13133: 
1.327     albertel 13134: }
                   13135: 
                   13136: 
1.1       albertel 13137: # ------------------------------------------------------------- Read hosts file
                   13138: {
1.838     albertel 13139:     my %hostname;
1.844     albertel 13140:     my %hostdom;
1.845     albertel 13141:     my %libserv;
1.852     albertel 13142:     my $loaded;
1.888     albertel 13143:     my %name_to_host;
1.1074    raeburn  13144:     my %internetdom;
1.1107    raeburn  13145:     my %LC_dns_serv;
1.852     albertel 13146: 
                   13147:     sub parse_hosts_tab {
                   13148: 	my ($file) = @_;
                   13149: 	foreach my $configline (@$file) {
                   13150: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13151:             chomp($configline);
                   13152: 	    if ($configline =~ /^\^/) {
                   13153:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13154:                     $LC_dns_serv{$1} = 1;
                   13155:                 }
                   13156:                 next;
                   13157:             }
1.1074    raeburn  13158: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13159: 	    $name=~s/\s//g;
                   13160: 	    if ($id && $domain && $role && $name) {
                   13161: 		$hostname{$id}=$name;
1.888     albertel 13162: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 13163: 		$hostdom{$id}=$domain;
                   13164: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13165:                 if (defined($protocol)) {
                   13166:                     if ($protocol eq 'https') {
                   13167:                         $protocol{$id} = $protocol;
                   13168:                     } else {
                   13169:                         $protocol{$id} = 'http'; 
                   13170:                     }
1.968     raeburn  13171:                 } else {
1.969     raeburn  13172:                     $protocol{$id} = 'http';
1.968     raeburn  13173:                 }
1.1074    raeburn  13174:                 if (defined($intdom)) {
                   13175:                     $internetdom{$id} = $intdom;
                   13176:                 }
1.852     albertel 13177: 	    }
                   13178: 	}
                   13179:     }
1.864     albertel 13180:     
                   13181:     sub reset_hosts_info {
1.897     albertel 13182: 	&purge_remembered();
1.864     albertel 13183: 	&reset_domain_info();
                   13184: 	&reset_hosts_ip_info();
1.892     albertel 13185: 	undef(%name_to_host);
1.864     albertel 13186: 	undef(%hostname);
                   13187: 	undef(%hostdom);
                   13188: 	undef(%libserv);
                   13189: 	undef($loaded);
                   13190:     }
1.1       albertel 13191: 
1.852     albertel 13192:     sub load_hosts_tab {
1.1293    raeburn  13193: 	my ($ignore_cache,$nocache) = @_;
                   13194: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 13195: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13196: 	my @config = <$config>;
                   13197: 	&parse_hosts_tab(\@config);
                   13198: 	close($config);
                   13199: 	$loaded=1;
1.1       albertel 13200:     }
1.852     albertel 13201: 
1.838     albertel 13202:     sub hostname {
1.852     albertel 13203: 	&load_hosts_tab() if (!$loaded);
                   13204: 
1.838     albertel 13205: 	my ($lonid) = @_;
                   13206: 	return $hostname{$lonid};
                   13207:     }
1.845     albertel 13208: 
1.838     albertel 13209:     sub all_hostnames {
1.852     albertel 13210: 	&load_hosts_tab() if (!$loaded);
                   13211: 
1.838     albertel 13212: 	return %hostname;
                   13213:     }
1.845     albertel 13214: 
1.888     albertel 13215:     sub all_names {
1.1293    raeburn  13216:         my ($ignore_cache,$nocache) = @_;
                   13217: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13218: 
                   13219: 	return %name_to_host;
                   13220:     }
                   13221: 
1.974     raeburn  13222:     sub all_host_domain {
                   13223:         &load_hosts_tab() if (!$loaded);
                   13224:         return %hostdom;
                   13225:     }
                   13226: 
1.845     albertel 13227:     sub is_library {
1.852     albertel 13228: 	&load_hosts_tab() if (!$loaded);
                   13229: 
1.845     albertel 13230: 	return exists($libserv{$_[0]});
                   13231:     }
                   13232: 
                   13233:     sub all_library {
1.852     albertel 13234: 	&load_hosts_tab() if (!$loaded);
                   13235: 
1.845     albertel 13236: 	return %libserv;
                   13237:     }
                   13238: 
1.1062    droeschl 13239:     sub unique_library {
                   13240: 	#2x reverse removes all hostnames that appear more than once
                   13241:         my %unique = reverse &all_library();
                   13242:         return reverse %unique;
                   13243:     }
                   13244: 
1.841     albertel 13245:     sub get_servers {
1.852     albertel 13246: 	&load_hosts_tab() if (!$loaded);
                   13247: 
1.841     albertel 13248: 	my ($domain,$type) = @_;
                   13249: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13250: 	                                          : %hostname;
                   13251: 	my %result;
1.842     albertel 13252: 	if (ref($domain) eq 'ARRAY') {
                   13253: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13254: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13255: 		    $result{$host} = $hostname;
                   13256: 		}
                   13257: 	    }
                   13258: 	} else {
                   13259: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13260: 		if ($hostdom{$host} eq $domain) {
                   13261: 		    $result{$host} = $hostname;
                   13262: 		}
1.841     albertel 13263: 	    }
                   13264: 	}
                   13265: 	return %result;
                   13266:     }
1.845     albertel 13267: 
1.1062    droeschl 13268:     sub get_unique_servers {
                   13269:         my %unique = reverse &get_servers(@_);
                   13270: 	return reverse %unique;
                   13271:     }
                   13272: 
1.844     albertel 13273:     sub host_domain {
1.852     albertel 13274: 	&load_hosts_tab() if (!$loaded);
                   13275: 
1.844     albertel 13276: 	my ($lonid) = @_;
                   13277: 	return $hostdom{$lonid};
                   13278:     }
                   13279: 
1.841     albertel 13280:     sub all_domains {
1.852     albertel 13281: 	&load_hosts_tab() if (!$loaded);
                   13282: 
1.841     albertel 13283: 	my %seen;
                   13284: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13285: 	return @uniq;
                   13286:     }
1.1074    raeburn  13287: 
                   13288:     sub internet_dom {
                   13289:         &load_hosts_tab() if (!$loaded);
                   13290: 
                   13291:         my ($lonid) = @_;
                   13292:         return $internetdom{$lonid};
                   13293:     }
1.1107    raeburn  13294: 
                   13295:     sub is_LC_dns {
                   13296:         &load_hosts_tab() if (!$loaded);
                   13297: 
                   13298:         my ($hostname) = @_;
                   13299:         return exists($LC_dns_serv{$hostname});
                   13300:     }
                   13301: 
1.1       albertel 13302: }
                   13303: 
1.847     albertel 13304: { 
                   13305:     my %iphost;
1.856     albertel 13306:     my %name_to_ip;
                   13307:     my %lonid_to_ip;
1.869     albertel 13308: 
1.847     albertel 13309:     sub get_hosts_from_ip {
                   13310: 	my ($ip) = @_;
                   13311: 	my %iphosts = &get_iphost();
                   13312: 	if (ref($iphosts{$ip})) {
                   13313: 	    return @{$iphosts{$ip}};
                   13314: 	}
                   13315: 	return;
1.839     albertel 13316:     }
1.864     albertel 13317:     
                   13318:     sub reset_hosts_ip_info {
                   13319: 	undef(%iphost);
                   13320: 	undef(%name_to_ip);
                   13321: 	undef(%lonid_to_ip);
                   13322:     }
1.856     albertel 13323: 
                   13324:     sub get_host_ip {
                   13325: 	my ($lonid) = @_;
                   13326: 	if (exists($lonid_to_ip{$lonid})) {
                   13327: 	    return $lonid_to_ip{$lonid};
                   13328: 	}
                   13329: 	my $name=&hostname($lonid);
                   13330:    	my $ip = gethostbyname($name);
                   13331: 	return if (!$ip || length($ip) ne 4);
                   13332: 	$ip=inet_ntoa($ip);
                   13333: 	$name_to_ip{$name}   = $ip;
                   13334: 	$lonid_to_ip{$lonid} = $ip;
                   13335: 	return $ip;
                   13336:     }
1.847     albertel 13337:     
                   13338:     sub get_iphost {
1.1293    raeburn  13339: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13340: 
1.869     albertel 13341: 	if (!$ignore_cache) {
                   13342: 	    if (%iphost) {
                   13343: 		return %iphost;
                   13344: 	    }
                   13345: 	    my ($ip_info,$cached)=
                   13346: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13347: 	    if ($cached) {
                   13348: 		%iphost      = %{$ip_info->[0]};
                   13349: 		%name_to_ip  = %{$ip_info->[1]};
                   13350: 		%lonid_to_ip = %{$ip_info->[2]};
                   13351: 		return %iphost;
                   13352: 	    }
                   13353: 	}
1.894     albertel 13354: 
                   13355: 	# get yesterday's info for fallback
                   13356: 	my %old_name_to_ip;
                   13357: 	my ($ip_info,$cached)=
                   13358: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13359: 	if ($cached) {
                   13360: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13361: 	}
                   13362: 
1.1293    raeburn  13363: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13364: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13365: 	    my $ip;
                   13366: 	    if (!exists($name_to_ip{$name})) {
                   13367: 		$ip = gethostbyname($name);
                   13368: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13369: 		    if (defined($old_name_to_ip{$name})) {
                   13370: 			$ip = $old_name_to_ip{$name};
                   13371: 			&logthis("Can't find $name defaulting to old $ip");
                   13372: 		    } else {
                   13373: 			&logthis("Name $name no IP found");
                   13374: 			next;
                   13375: 		    }
                   13376: 		} else {
                   13377: 		    $ip=inet_ntoa($ip);
1.847     albertel 13378: 		}
                   13379: 		$name_to_ip{$name} = $ip;
                   13380: 	    } else {
                   13381: 		$ip = $name_to_ip{$name};
1.653     albertel 13382: 	    }
1.888     albertel 13383: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13384: 		$lonid_to_ip{$id} = $ip;
                   13385: 	    }
                   13386: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13387: 	}
1.1293    raeburn  13388:         unless ($nocache) {
                   13389: 	    &do_cache_new('iphost','iphost',
                   13390: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13391: 		          48*60*60);
                   13392:         }
1.869     albertel 13393: 
1.847     albertel 13394: 	return %iphost;
1.598     albertel 13395:     }
                   13396: 
1.992     raeburn  13397:     #
                   13398:     #  Given a DNS returns the loncapa host name for that DNS 
                   13399:     # 
                   13400:     sub host_from_dns {
                   13401:         my ($dns) = @_;
                   13402:         my @hosts;
                   13403:         my $ip;
                   13404: 
1.993     raeburn  13405:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13406:             $ip = $name_to_ip{$dns};
                   13407:         }
                   13408:         if (!$ip) {
                   13409:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13410:             if (length($ip) == 4) { 
                   13411: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13412:             }
                   13413:         }
                   13414:         if ($ip) {
                   13415: 	    @hosts = get_hosts_from_ip($ip);
                   13416: 	    return $hosts[0];
                   13417:         }
                   13418:         return undef;
1.986     foxr     13419:     }
1.992     raeburn  13420: 
1.1074    raeburn  13421:     sub get_internet_names {
                   13422:         my ($lonid) = @_;
                   13423:         return if ($lonid eq '');
                   13424:         my ($idnref,$cached)=
                   13425:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13426:         if ($cached) {
                   13427:             return $idnref;
                   13428:         }
                   13429:         my $ip = &get_host_ip($lonid);
                   13430:         my @hosts = &get_hosts_from_ip($ip);
                   13431:         my %iphost = &get_iphost();
                   13432:         my (@idns,%seen);
                   13433:         foreach my $id (@hosts) {
                   13434:             my $dom = &host_domain($id);
                   13435:             my $prim_id = &domain($dom,'primary');
                   13436:             my $prim_ip = &get_host_ip($prim_id);
                   13437:             next if ($seen{$prim_ip});
                   13438:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13439:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13440:                     my $intdom = &internet_dom($id);
                   13441:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13442:                         push(@idns,$intdom);
                   13443:                     }
                   13444:                 }
                   13445:             }
                   13446:             $seen{$prim_ip} = 1;
                   13447:         }
1.1219    raeburn  13448:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13449:     }
                   13450: 
1.986     foxr     13451: }
                   13452: 
1.1079    raeburn  13453: sub all_loncaparevs {
1.1249    raeburn  13454:     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  13455: }
                   13456: 
1.1227    raeburn  13457: # ---------------------------------------------------------- Read loncaparev table
                   13458: {
                   13459:     sub load_loncaparevs { 
                   13460:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13461:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13462:                 while (my $configline=<$config>) {
                   13463:                     chomp($configline);
                   13464:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13465:                     $loncaparevs{$hostid}=$loncaparev;
                   13466:                 }
                   13467:                 close($config);
                   13468:             }
                   13469:         }
                   13470:     }
                   13471: }
                   13472: 
                   13473: # ---------------------------------------------------------- Read serverhostID table
                   13474: {
                   13475:     sub load_serverhomeIDs {
                   13476:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13477:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13478:                 while (my $configline=<$config>) {
                   13479:                     chomp($configline);
                   13480:                     my ($name,$id)=split(/:/,$configline);
                   13481:                     $serverhomeIDs{$name}=$id;
                   13482:                 }
                   13483:                 close($config);
                   13484:             }
                   13485:         }
                   13486:     }
                   13487: }
                   13488: 
                   13489: 
1.862     albertel 13490: BEGIN {
                   13491: 
                   13492: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13493:     unless ($readit) {
                   13494: {
                   13495:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13496:     %perlvar = (%perlvar,%{$configvars});
                   13497: }
                   13498: 
                   13499: 
1.1       albertel 13500: # ------------------------------------------------------ Read spare server file
                   13501: {
1.448     albertel 13502:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13503: 
                   13504:     while (my $configline=<$config>) {
                   13505:        chomp($configline);
1.284     matthew  13506:        if ($configline) {
1.784     albertel 13507: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13508: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13509: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13510:        }
                   13511:     }
1.448     albertel 13512:     close($config);
1.1       albertel 13513: }
1.11      www      13514: # ------------------------------------------------------------ Read permissions
                   13515: {
1.448     albertel 13516:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13517: 
                   13518:     while (my $configline=<$config>) {
1.448     albertel 13519: 	chomp($configline);
                   13520: 	if ($configline) {
                   13521: 	    my ($role,$perm)=split(/ /,$configline);
                   13522: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13523: 	}
1.11      www      13524:     }
1.448     albertel 13525:     close($config);
1.11      www      13526: }
                   13527: 
                   13528: # -------------------------------------------- Read plain texts for permissions
                   13529: {
1.448     albertel 13530:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13531: 
                   13532:     while (my $configline=<$config>) {
1.448     albertel 13533: 	chomp($configline);
                   13534: 	if ($configline) {
1.742     raeburn  13535: 	    my ($short,@plain)=split(/:/,$configline);
                   13536:             %{$prp{$short}} = ();
                   13537: 	    if (@plain > 0) {
                   13538:                 $prp{$short}{'std'} = $plain[0];
                   13539:                 for (my $i=1; $i<@plain; $i++) {
                   13540:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13541:                 }
                   13542:             }
1.448     albertel 13543: 	}
1.135     www      13544:     }
1.448     albertel 13545:     close($config);
1.135     www      13546: }
                   13547: 
                   13548: # ---------------------------------------------------------- Read package table
                   13549: {
1.448     albertel 13550:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13551: 
                   13552:     while (my $configline=<$config>) {
1.483     albertel 13553: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13554: 	chomp($configline);
                   13555: 	my ($short,$plain)=split(/:/,$configline);
                   13556: 	my ($pack,$name)=split(/\&/,$short);
                   13557: 	if ($plain ne '') {
                   13558: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13559: 	    $packagetab{$short}=$plain; 
                   13560: 	}
1.11      www      13561:     }
1.448     albertel 13562:     close($config);
1.329     matthew  13563: }
                   13564: 
1.1073    raeburn  13565: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13566: 
                   13567: &load_loncaparevs();
1.1073    raeburn  13568: 
1.1074    raeburn  13569: # ---------------------------------------------------------- Read serverhostID table
                   13570: 
1.1227    raeburn  13571: &load_serverhomeIDs();
                   13572: 
                   13573: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13574: {
                   13575:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13576:     if (-e $file) {
                   13577:         my $parser = HTML::LCParser->new($file);
                   13578:         while (my $token = $parser->get_token()) {
                   13579:             if ($token->[0] eq 'S') {
                   13580:                 my $item = $token->[1];
                   13581:                 my $name = $token->[2]{'name'};
                   13582:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13583:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13584:                 my $namematch = $token->[2]{'namematch'};
                   13585:                 if ($item eq 'parameter') {
                   13586:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13587:                         my $release = $parser->get_text();
                   13588:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13589:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13590:                     }
                   13591:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13592:                     my $release = $parser->get_text();
                   13593:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13594:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13595:                 }
                   13596:             }
                   13597:         }
                   13598:     }
1.1073    raeburn  13599: }
                   13600: 
1.1138    raeburn  13601: # ---------------------------------------------------------- Read managers table
                   13602: {
                   13603:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13604:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13605:             while (my $configline=<$config>) {
                   13606:                 chomp($configline);
                   13607:                 next if ($configline =~ /^\#/);
                   13608:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13609:                     $managerstab{$configline} = 1;
                   13610:                 }
                   13611:             }
                   13612:             close($config);
                   13613:         }
                   13614:     }
                   13615: }
                   13616: 
1.329     matthew  13617: # ------------- set up temporary directory
                   13618: {
1.1117    foxr     13619:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13620: 
1.11      www      13621: }
                   13622: 
1.794     albertel 13623: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13624: 				'compress_threshold'=> 20_000,
                   13625:  			        });
1.185     www      13626: 
1.281     www      13627: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13628: $dumpcount=0;
1.958     www      13629: $locknum=0;
1.22      www      13630: 
1.163     harris41 13631: &logtouch();
1.672     albertel 13632: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13633: $readit=1;
1.564     albertel 13634:     {
                   13635: 	use integer;
                   13636: 	my $test=(2**32)+1;
1.568     albertel 13637: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13638: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13639:     }
1.195     www      13640: }
1.1       albertel 13641: }
1.179     www      13642: 
1.1       albertel 13643: 1;
1.191     harris41 13644: __END__
                   13645: 
1.243     albertel 13646: =pod
                   13647: 
1.191     harris41 13648: =head1 NAME
                   13649: 
1.243     albertel 13650: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13651: 
                   13652: =head1 SYNOPSIS
                   13653: 
1.243     albertel 13654: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13655: 
                   13656:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13657: 
1.243     albertel 13658: Common parameters:
                   13659: 
                   13660: =over 4
                   13661: 
                   13662: =item *
                   13663: 
                   13664: $uname : an internal username (if $cname expecting a course Id specifically)
                   13665: 
                   13666: =item *
                   13667: 
                   13668: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13669: 
                   13670: =item *
                   13671: 
                   13672: $symb : a resource instance identifier
                   13673: 
                   13674: =item *
                   13675: 
                   13676: $namespace : the name of a .db file that contains the data needed or
                   13677: being set.
                   13678: 
                   13679: =back
                   13680: 
1.394     bowersj2 13681: =head1 OVERVIEW
1.191     harris41 13682: 
1.394     bowersj2 13683: lonnet provides subroutines which interact with the
                   13684: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13685: about classes, users, and resources.
1.243     albertel 13686: 
                   13687: For many of these objects you can also use this to store data about
                   13688: them or modify them in various ways.
1.191     harris41 13689: 
1.394     bowersj2 13690: =head2 Symbs
1.191     harris41 13691: 
1.394     bowersj2 13692: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13693: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13694: map, the resource number of the resource in the map, and the URL of
                   13695: the resource itself. The latter is somewhat redundant, but might help
                   13696: if maps change.
                   13697: 
                   13698: An example is
                   13699: 
                   13700:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13701: 
                   13702: The respective map entry is
                   13703: 
                   13704:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13705:   title="Problem 2">
                   13706:  </resource>
                   13707: 
                   13708: Symbs are used by the random number generator, as well as to store and
                   13709: restore data specific to a certain instance of for example a problem.
                   13710: 
                   13711: =head2 Storing And Retrieving Data
                   13712: 
                   13713: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13714: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13715: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13716: is is the non-critical message twin of cstore. These functions are for
                   13717: handlers to store a perl hash to a user's permanent data space in an
                   13718: easy manner, and to retrieve it again on another call. It is expected
                   13719: that a handler would use this once at the beginning to retrieve data,
                   13720: and then again once at the end to send only the new data back.
                   13721: 
                   13722: The data is stored in the user's data directory on the user's
                   13723: homeserver under the ID of the course.
                   13724: 
                   13725: The hash that is returned by restore will have all of the previous
                   13726: value for all of the elements of the hash.
                   13727: 
                   13728: Example:
                   13729: 
                   13730:  #creating a hash
                   13731:  my %hash;
                   13732:  $hash{'foo'}='bar';
                   13733: 
                   13734:  #storing it
                   13735:  &Apache::lonnet::cstore(\%hash);
                   13736: 
                   13737:  #changing a value
                   13738:  $hash{'foo'}='notbar';
                   13739: 
                   13740:  #adding a new value
                   13741:  $hash{'bar'}='foo';
                   13742:  &Apache::lonnet::cstore(\%hash);
                   13743: 
                   13744:  #retrieving the hash
                   13745:  my %history=&Apache::lonnet::restore();
                   13746: 
                   13747:  #print the hash
                   13748:  foreach my $key (sort(keys(%history))) {
                   13749:    print("\%history{$key} = $history{$key}");
                   13750:  }
                   13751: 
                   13752: Will print out:
1.191     harris41 13753: 
1.394     bowersj2 13754:  %history{1:foo} = bar
                   13755:  %history{1:keys} = foo:timestamp
                   13756:  %history{1:timestamp} = 990455579
                   13757:  %history{2:bar} = foo
                   13758:  %history{2:foo} = notbar
                   13759:  %history{2:keys} = foo:bar:timestamp
                   13760:  %history{2:timestamp} = 990455580
                   13761:  %history{bar} = foo
                   13762:  %history{foo} = notbar
                   13763:  %history{timestamp} = 990455580
                   13764:  %history{version} = 2
                   13765: 
                   13766: Note that the special hash entries C<keys>, C<version> and
                   13767: C<timestamp> were added to the hash. C<version> will be equal to the
                   13768: total number of versions of the data that have been stored. The
                   13769: C<timestamp> attribute will be the UNIX time the hash was
                   13770: stored. C<keys> is available in every historical section to list which
                   13771: keys were added or changed at a specific historical revision of a
                   13772: hash.
                   13773: 
                   13774: B<Warning>: do not store the hash that restore returns directly. This
                   13775: will cause a mess since it will restore the historical keys as if the
                   13776: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13777: 
1.394     bowersj2 13778: Calling convention:
1.191     harris41 13779: 
1.1225    raeburn  13780:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13781:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13782: 
1.394     bowersj2 13783: For more detailed information, see lonnet specific documentation.
1.191     harris41 13784: 
1.394     bowersj2 13785: =head1 RETURN MESSAGES
1.191     harris41 13786: 
1.394     bowersj2 13787: =over 4
1.191     harris41 13788: 
1.394     bowersj2 13789: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13790: 
1.394     bowersj2 13791: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13792: when the connection is brought back up
1.191     harris41 13793: 
1.394     bowersj2 13794: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13795: for later delivery
1.191     harris41 13796: 
1.967     bisitz   13797: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13798: 
1.394     bowersj2 13799: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13800: that was requested
1.191     harris41 13801: 
1.243     albertel 13802: =back
1.191     harris41 13803: 
1.243     albertel 13804: =head1 PUBLIC SUBROUTINES
1.191     harris41 13805: 
1.243     albertel 13806: =head2 Session Environment Functions
1.191     harris41 13807: 
1.243     albertel 13808: =over 4
1.191     harris41 13809: 
1.394     bowersj2 13810: =item * 
                   13811: X<appenv()>
1.949     raeburn  13812: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13813: the user envirnoment file, and will be restored for each access this
1.620     albertel 13814: user makes during this session, also modifies the %env for the current
1.949     raeburn  13815: process. Optional rolesarrayref - if defined contains a reference to an array
                   13816: of roles which are exempt from the restriction on modifying user.role entries 
                   13817: in the user's environment.db and in %env.    
1.191     harris41 13818: 
                   13819: =item *
1.394     bowersj2 13820: X<delenv()>
1.987     raeburn  13821: B<delenv($delthis,$regexp)>: removes all items from the session
                   13822: environment file that begin with $delthis. If the 
                   13823: optional second arg - $regexp - is true, $delthis is treated as a 
                   13824: regular expression, otherwise \Q$delthis\E is used. 
                   13825: The values are also deleted from the current processes %env.
1.191     harris41 13826: 
1.795     albertel 13827: =item * get_env_multiple($name) 
                   13828: 
                   13829: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13830: values may be defined and end up as an array ref.
                   13831: 
                   13832: returns an array of values
                   13833: 
1.243     albertel 13834: =back
                   13835: 
                   13836: =head2 User Information
1.191     harris41 13837: 
1.243     albertel 13838: =over 4
1.191     harris41 13839: 
                   13840: =item *
1.394     bowersj2 13841: X<queryauthenticate()>
                   13842: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13843: authentication scheme
                   13844: 
                   13845: =item *
1.394     bowersj2 13846: X<authenticate()>
1.1073    raeburn  13847: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13848: authenticate user from domain's lib servers (first use the current
                   13849: one). C<$upass> should be the users password.
1.1073    raeburn  13850: $checkdefauth is optional (value is 1 if a check should be made to
                   13851:    authenticate user using default authentication method, and allow
                   13852:    account creation if username does not have account in the domain).
                   13853: $clientcancheckhost is optional (value is 1 if checking whether the
                   13854:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13855: 
                   13856: =item *
1.394     bowersj2 13857: X<homeserver()>
                   13858: B<homeserver($uname,$udom)>: find the server which has
                   13859: the user's directory and files (there must be only one), this caches
                   13860: the answer, and also caches if there is a borken connection.
1.191     harris41 13861: 
                   13862: =item *
1.394     bowersj2 13863: X<idget()>
1.1300    raeburn  13864: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13865: a list of student/employee IDs or clicker IDs
                   13866: (student/employee IDs are a unique resource in a domain, there must be 
                   13867: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13868: clickerIDs are not necessarily unique, as students might share clickers.
                   13869: (returns hash: id=>name,id=>name)
1.191     harris41 13870: 
                   13871: =item *
1.394     bowersj2 13872: X<idrget()>
                   13873: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13874: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13875: 
                   13876: =item *
1.394     bowersj2 13877: X<idput()>
1.1300    raeburn  13878: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13879: names and associated student/employee IDs or clicker IDs.
                   13880: 
                   13881: =item *
                   13882: X<iddel()>
                   13883: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   13884: student/employee ID or clicker ID username look-ups from domain.
                   13885: The homeserver ($uhome) and namespace ($namespace) are optional.
                   13886: If no $uhome is provided, it will be determined usig &homeserver()
                   13887: for each user.  If no $namespace is provided, the default is ids.
                   13888: 
                   13889: =item *
                   13890: X<updateclickers()>
                   13891: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   13892: clicker ID-to-username look-ups in clickers.db on library server.
                   13893: Permitted actions are add or del (i.e., add or delete). The 
                   13894: clickers.db contains clickerID as keys (escaped), and each corresponding
                   13895: value is an escaped comma-separated list of usernames (for whom the
                   13896: library server is the homeserver), who registered that particular ID.
                   13897: If $critical is true, the update will be sent via &critical, otherwise
                   13898: &reply() will be used.
1.191     harris41 13899: 
                   13900: =item *
1.394     bowersj2 13901: X<rolesinit()>
1.1169    droeschl 13902: B<rolesinit($udom,$username)>: get user privileges.
                   13903: returns user role, first access and timer interval hashes
1.243     albertel 13904: 
                   13905: =item *
1.1171    droeschl 13906: X<privileged()>
                   13907: B<privileged($username,$domain)>: returns a true if user has a
                   13908: privileged and active role (i.e. su or dc), false otherwise.
                   13909: 
                   13910: =item *
1.551     albertel 13911: X<getsection()>
                   13912: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 13913: course $cname, return section name/number or '' for "not in course"
                   13914: and '-1' for "no section"
                   13915: 
                   13916: =item *
1.394     bowersj2 13917: X<userenvironment()>
                   13918: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 13919: passed in @what from the requested user's environment, returns a hash
                   13920: 
1.858     raeburn  13921: =item * 
                   13922: X<userlog_query()>
1.859     albertel 13923: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   13924: activity.log file. %filters defines filters applied when parsing the
                   13925: log file. These can be start or end timestamps, or the type of action
                   13926: - log to look for Login or Logout events, check for Checkin or
                   13927: Checkout, role for role selection. The response is in the form
                   13928: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   13929: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  13930: 
1.243     albertel 13931: =back
                   13932: 
                   13933: =head2 User Roles
                   13934: 
                   13935: =over 4
                   13936: 
                   13937: =item *
                   13938: 
1.1284    raeburn  13939: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   13940: returns codes for allowed actions.
                   13941: 
                   13942: The first argument is required, all others are optional.
                   13943: 
                   13944: $priv is the privilege being checked.
                   13945: $uri contains additional information about what is being checked for access (e.g.,
                   13946: URL, course ID etc.). 
                   13947: $symb is the unique resource instance identifier in a course; if needed,
                   13948: but not provided, it will be retrieved via a call to &symbread(). 
                   13949: $role is the role for which a priv is being checked (only used if priv is evb). 
                   13950: $clientip is the user's IP address (only used when checking for access to portfolio 
                   13951: files).
                   13952: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   13953: prevents recursive calls to &allowed.
                   13954: 
1.243     albertel 13955:  F: full access
                   13956:  U,I,K: authentication modes (cxx only)
                   13957:  '': forbidden
                   13958:  1: user needs to choose course
                   13959:  2: browse allowed
1.766     albertel 13960:  A: passphrase authentication needed
1.1284    raeburn  13961:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 13962: 
                   13963: =item *
                   13964: 
1.1192    raeburn  13965: constructaccess($url,$setpriv) : check for access to construction space URL
                   13966: 
                   13967: See if the owner domain and name in the URL match those in the
                   13968: expected environment.  If so, return three element list
                   13969: ($ownername,$ownerdomain,$ownerhome).
                   13970: 
                   13971: Otherwise return the null string.
                   13972: 
                   13973: If second argument 'setpriv' is true, it assigns the privileges,
                   13974: and returns the same three element list, unless the owner has
                   13975: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   13976: in which case the null string is returned.
                   13977: 
                   13978: =item *
                   13979: 
1.1326    raeburn  13980: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   13981: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   13982: for system, domain, and course level. $uname and $udom are optional (current
                   13983: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 13984: 
                   13985: =item *
                   13986: 
1.988     raeburn  13987: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   13988: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  13989: $type is Course (default) or Community.
1.988     raeburn  13990: If $forcedefault evaluates to true, text returned will be default 
                   13991: text for $type. Otherwise, if this is a course, the text returned 
                   13992: will be a custom name for the role (if defined in the course's 
                   13993: environment).  If no custom name is defined the default is returned.
                   13994:    
1.832     raeburn  13995: =item *
                   13996: 
1.1219    raeburn  13997: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  13998: All arguments are optional. Returns a hash of a roles, either for
                   13999: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14000: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14001: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14002: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14003: For each key, value is set to colon-separated start and end times for
                   14004: the role.  If no username and domain are specified, will default to
1.934     raeburn  14005: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14006: of role statuses (active, future or previous), roles 
                   14007: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14008: to restrict the list of roles reported. If no array ref is 
                   14009: provided for types, will default to return only active roles.
1.834     albertel 14010: 
1.1195    raeburn  14011: =item *
                   14012: 
                   14013: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14014: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14015: 
                   14016: Additional optional arguments are: $type (if role checking is to be restricted 
                   14017: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14018: available roles) or future (roles available in the future), and
                   14019: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14020: have active Domain Coordinator role in course's domain or in additional
                   14021: domains (specified in 'Domains to check for privileged users' in course
                   14022: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14023: 
                   14024: =item *
                   14025: 
                   14026: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14027: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14028: $possdomains and $possroles are optional array refs -- to domains to check and
                   14029: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14030: users' roles.db to check for a dc or su role in any domain. This can be
                   14031: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14032: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14033: this then allows &privileged_by_domain() to be used, which caches the identity
                   14034: of privileged users, eliminating the need for repeated calls to &dump().
                   14035: 
                   14036: =item *
                   14037: 
                   14038: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14039: where the outer hash keys are domains specified in the $possdomains array ref,
                   14040: next inner hash keys are privileged roles specified in the $roles array ref,
                   14041: and the innermost hash contains key = value pairs for username:domain = end:start
                   14042: for active or future "privileged" users with that role in that domain. To avoid
                   14043: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14044: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14045: 
1.243     albertel 14046: =back
                   14047: 
                   14048: =head2 User Modification
                   14049: 
                   14050: =over 4
                   14051: 
                   14052: =item *
                   14053: 
1.957     raeburn  14054: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14055: user for the level given by URL.  Optional start and end dates (leave empty
                   14056: string or zero for "no date")
1.191     harris41 14057: 
                   14058: =item *
                   14059: 
1.243     albertel 14060: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14061: change a users, password, possible return values are: ok,
                   14062: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14063: refused
1.191     harris41 14064: 
                   14065: =item *
                   14066: 
1.243     albertel 14067: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14068: 
                   14069: =item *
                   14070: 
1.1058    raeburn  14071: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14072:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14073: 
                   14074: will update user information (firstname,middlename,lastname,generation,
                   14075: permanentemail), and if forceid is true, student/employee ID also.
                   14076: A user's institutional affiliation(s) can also be updated.
                   14077: User information fields will not be overwritten with empty entries 
                   14078: unless the field is included in the $candelete array reference.
                   14079: This array is included when a single user is modified via "Manage Users",
                   14080: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14081: 
                   14082: =item *
                   14083: 
1.286     matthew  14084: modifystudent
                   14085: 
1.957     raeburn  14086: modify a student's enrollment and identification information.
1.1235    raeburn  14087: The course id is resolved based on the current user's environment.  
                   14088: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14089: associated with a course.
                   14090: 
1.297     matthew  14091: This call is essentially a wrapper for lonnet::modifyuser and
                   14092: lonnet::modify_student_enrollment
1.286     matthew  14093: 
                   14094: Inputs: 
                   14095: 
                   14096: =over 4
                   14097: 
1.957     raeburn  14098: =item B<$udom> Student's loncapa domain
1.286     matthew  14099: 
1.957     raeburn  14100: =item B<$uname> Student's loncapa login name
1.286     matthew  14101: 
1.964     bisitz   14102: =item B<$uid> Student/Employee ID
1.286     matthew  14103: 
1.957     raeburn  14104: =item B<$umode> Student's authentication mode
1.286     matthew  14105: 
1.957     raeburn  14106: =item B<$upass> Student's password
1.286     matthew  14107: 
1.957     raeburn  14108: =item B<$first> Student's first name
1.286     matthew  14109: 
1.957     raeburn  14110: =item B<$middle> Student's middle name
1.286     matthew  14111: 
1.957     raeburn  14112: =item B<$last> Student's last name
1.286     matthew  14113: 
1.957     raeburn  14114: =item B<$gene> Student's generation
1.286     matthew  14115: 
1.957     raeburn  14116: =item B<$usec> Student's section in course
1.286     matthew  14117: 
                   14118: =item B<$end> Unix time of the roles expiration
                   14119: 
                   14120: =item B<$start> Unix time of the roles start date
                   14121: 
                   14122: =item B<$forceid> If defined, allow $uid to be changed
                   14123: 
                   14124: =item B<$desiredhome> server to use as home server for student
                   14125: 
1.957     raeburn  14126: =item B<$email> Student's permanent e-mail address
                   14127: 
                   14128: =item B<$type> Type of enrollment (auto or manual)
                   14129: 
1.963     raeburn  14130: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14131: 
                   14132: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14133: 
1.963     raeburn  14134: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14135: 
1.963     raeburn  14136: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14137: 
1.1216    raeburn  14138: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14139: 
                   14140: =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  14141: 
1.286     matthew  14142: =back
1.297     matthew  14143: 
                   14144: =item *
                   14145: 
                   14146: modify_student_enrollment
                   14147: 
1.1235    raeburn  14148: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14149: 'role.request.course' must be defined for this function to proceed.
                   14150: 
                   14151: Inputs:
                   14152: 
                   14153: =over 4
                   14154: 
1.1235    raeburn  14155: =item $udom, student's domain
1.297     matthew  14156: 
1.1235    raeburn  14157: =item $uname, student's name
1.297     matthew  14158: 
1.1235    raeburn  14159: =item $uid, student's user id
1.297     matthew  14160: 
1.1235    raeburn  14161: =item $first, student's first name
1.297     matthew  14162: 
                   14163: =item $middle
                   14164: 
                   14165: =item $last
                   14166: 
                   14167: =item $gene
                   14168: 
                   14169: =item $usec
                   14170: 
                   14171: =item $end
                   14172: 
                   14173: =item $start
                   14174: 
1.957     raeburn  14175: =item $type
                   14176: 
                   14177: =item $locktype
                   14178: 
                   14179: =item $cid
                   14180: 
                   14181: =item $selfenroll
                   14182: 
                   14183: =item $context
                   14184: 
1.1216    raeburn  14185: =item $credits, number of credits student will earn from this class
                   14186: 
1.1314    raeburn  14187: =item $instsec, institutional course section code for student
                   14188: 
1.297     matthew  14189: =back
                   14190: 
1.191     harris41 14191: 
                   14192: =item *
                   14193: 
1.243     albertel 14194: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14195: custom role; give a custom role to a user for the level given by URL.  Specify
                   14196: name and domain of role author, and role name
1.191     harris41 14197: 
                   14198: =item *
                   14199: 
1.243     albertel 14200: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14201: 
                   14202: =item *
                   14203: 
1.243     albertel 14204: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14205: 
                   14206: =back
                   14207: 
                   14208: =head2 Course Infomation
                   14209: 
                   14210: =over 4
1.191     harris41 14211: 
                   14212: =item *
                   14213: 
1.1118    foxr     14214: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14215: specified course id, including all environment settings for the
                   14216: course, the description of the course will be in the hash under the
                   14217: key 'description'
1.191     harris41 14218: 
1.1118    foxr     14219: $options is an optional parameter that if supplied is a hash reference that controls
                   14220: what how this function works.  It has the following key/values:
                   14221: 
                   14222: =over 4
                   14223: 
                   14224: =item freshen_cache
                   14225: 
                   14226: If defined, and the environment cache for the course is valid, it is 
                   14227: returned in the returned hash.
                   14228: 
                   14229: =item one_time
                   14230: 
                   14231: If defined, the last cache time is set to _now_
                   14232: 
                   14233: =item user
                   14234: 
                   14235: If defined, the supplied username is used instead of the current user.
                   14236: 
                   14237: 
                   14238: =back
                   14239: 
1.191     harris41 14240: =item *
                   14241: 
1.624     albertel 14242: resdata($name,$domain,$type,@which) : request for current parameter
                   14243: setting for a specific $type, where $type is either 'course' or 'user',
                   14244: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14245: answers for 10 minutes.
1.243     albertel 14246: 
1.877     foxr     14247: =item *
                   14248: 
                   14249: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14250: data base, returning a hash that is keyed by the resource name and has
                   14251: values that are the resource value.  I believe that the timestamps and
                   14252: versions are also returned.
                   14253: 
1.1236    raeburn  14254: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14255: supplemental content area. This routine caches the number of files for 
                   14256: 10 minutes.
                   14257: 
1.243     albertel 14258: =back
                   14259: 
                   14260: =head2 Course Modification
                   14261: 
                   14262: =over 4
1.191     harris41 14263: 
                   14264: =item *
                   14265: 
1.243     albertel 14266: writecoursepref($courseid,%prefs) : write preferences (environment
                   14267: database) for a course
1.191     harris41 14268: 
                   14269: =item *
                   14270: 
1.1011    raeburn  14271: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14272: 
                   14273: =item *
                   14274: 
1.1038    raeburn  14275: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14276: 
1.1167    droeschl 14277: =item *
                   14278: 
                   14279: is_course($courseid), is_course($cdom, $cnum)
                   14280: 
                   14281: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14282: two component version $cdom, $cnum. It checks if the specified course exists.
                   14283: 
                   14284: Returns:
                   14285:     undef if the course doesn't exist, otherwise
                   14286:     in scalar context the combined courseid.
                   14287:     in list context the two components of the course identifier, domain and 
                   14288:     courseid.    
                   14289: 
1.243     albertel 14290: =back
                   14291: 
                   14292: =head2 Resource Subroutines
                   14293: 
                   14294: =over 4
1.191     harris41 14295: 
                   14296: =item *
                   14297: 
1.243     albertel 14298: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14299: 
                   14300: =item *
                   14301: 
1.243     albertel 14302: repcopy($filename) : subscribes to the requested file, and attempts to
                   14303: replicate from the owning library server, Might return
1.607     raeburn  14304: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14305: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14306: resource. Expects the local filesystem pathname
                   14307: (/home/httpd/html/res/....)
                   14308: 
                   14309: =back
                   14310: 
                   14311: =head2 Resource Information
                   14312: 
                   14313: =over 4
1.191     harris41 14314: 
                   14315: =item *
                   14316: 
1.1228    raeburn  14317: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14318: and returns the value of a variety of different possible values,
                   14319: $varname should be a request string, and the other parameters can be
                   14320: used to specify who and what one is asking about. Ordinarily, $cid 
                   14321: does not need to be specified, as it is retrived from 
                   14322: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14323: within lonuserstate::loadmap() when initializing a course, before
                   14324: $env{'request.course.id'} has been set, so it needs to be provided
                   14325: in that one case.
1.243     albertel 14326: 
                   14327: Possible values for $varname are environment.lastname (or other item
                   14328: from the envirnment hash), user.name (or someother aspect about the
                   14329: user), resource.0.maxtries (or some other part and parameter of a
                   14330: resource)
1.204     albertel 14331: 
                   14332: =item *
                   14333: 
1.243     albertel 14334: directcondval($number) : get current value of a condition; reads from a state
                   14335: string
1.204     albertel 14336: 
                   14337: =item *
                   14338: 
1.243     albertel 14339: condval($condidx) : value of condition index based on state
1.204     albertel 14340: 
                   14341: =item *
                   14342: 
1.243     albertel 14343: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14344: resource's metadata, $what should be either a specific key, or either
                   14345: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14346: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14347: 
                   14348: this function automatically caches all requests
1.191     harris41 14349: 
                   14350: =item *
                   14351: 
1.243     albertel 14352: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14353: network of library servers; returns file handle of where SQL and regex results
                   14354: will be stored for query
1.191     harris41 14355: 
                   14356: =item *
                   14357: 
1.1282    raeburn  14358: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14359: return symbolic list entry (all arguments optional). 
                   14360: 
                   14361: Args: filename is the filename (including path) for the file for which a symb 
                   14362: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14363: to check access status if more than one resource was found in the bighash 
                   14364: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14365: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14366: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14367: cause possible symbs to be checked to determine if they are subject to content
                   14368: blocking, if so they will not be included as possible symbs; possibles is a
                   14369: ref to a hash, which, as a side effect, will be populated with all possible 
                   14370: symbs (content blocking not tested).
                   14371:  
1.243     albertel 14372: returns the data handle
1.191     harris41 14373: 
                   14374: =item *
                   14375: 
1.1190    raeburn  14376: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14377: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14378: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14379: on failure, user must be in a course, as it assumes the existence of
                   14380: the course initial hash, and uses $env('request.course.id'}.  The third
                   14381: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14382: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14383: encrypted; otherwise it will be null.  
1.191     harris41 14384: 
                   14385: =item *
                   14386: 
1.243     albertel 14387: symbclean($symb) : removes versions numbers from a symb, returns the
                   14388: cleaned symb
1.191     harris41 14389: 
                   14390: =item *
                   14391: 
1.243     albertel 14392: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14393: course map, user must be in a course for it to work.
1.191     harris41 14394: 
                   14395: =item *
                   14396: 
1.243     albertel 14397: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14398: 
                   14399: =item *
                   14400: 
1.243     albertel 14401: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14402: a random seed, all arguments are optional, if they aren't sent it uses the
                   14403: environment to derive them. Note: if symb isn't sent and it can't get one
                   14404: from &symbread it will use the current time as its return value
1.191     harris41 14405: 
                   14406: =item *
                   14407: 
1.243     albertel 14408: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14409: unfakeable, receipt
1.191     harris41 14410: 
                   14411: =item *
                   14412: 
1.620     albertel 14413: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14414: 
                   14415: =item *
                   14416: 
1.243     albertel 14417: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14418: 
                   14419: =item *
                   14420: 
1.243     albertel 14421: 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 14422: 
                   14423: =item *
                   14424: 
1.243     albertel 14425: 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 14426: 
                   14427: =item *
                   14428: 
1.243     albertel 14429: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14430: 
                   14431: =item *
                   14432: 
1.243     albertel 14433: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14434: forcing spreadsheet to reevaluate the resource scores next time.
                   14435: 
1.1195    raeburn  14436: =item * 
                   14437: 
1.1196    raeburn  14438: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14439: when viewing in course context.
1.1195    raeburn  14440: 
1.1196    raeburn  14441:  input: six args -- filename (decluttered), course number, course domain,
                   14442:                     url, symb (if registered) and group (if this is a 
                   14443:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14444: 
1.1196    raeburn  14445:  output: array of five scalars --
1.1195    raeburn  14446:          $cfile -- url for file editing if editable on current server
                   14447:          $home -- homeserver of resource (i.e., for author if published,
                   14448:                                           or course if uploaded.).
                   14449:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14450:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14451:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14452: 
                   14453: =item *
                   14454: 
                   14455: is_course_upload($file,$cnum,$cdom)
                   14456: 
                   14457: Used in course context to determine if current file was uploaded to 
                   14458: the course (i.e., would be found in /userfiles/docs on the course's 
                   14459: homeserver.
                   14460: 
                   14461:   input: 3 args -- filename (decluttered), course number and course domain.
                   14462:   output: boolean -- 1 if file was uploaded.
                   14463: 
1.243     albertel 14464: =back
                   14465: 
                   14466: =head2 Storing/Retreiving Data
                   14467: 
                   14468: =over 4
1.191     harris41 14469: 
                   14470: =item *
                   14471: 
1.1269    raeburn  14472: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14473: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14474: the remaining args aren't required and if they aren't passed or are '' they will
                   14475: be derived from the env (with the exception of $laststore, which is an 
                   14476: optional arg used when a user's submission is stored in grading).
                   14477: $laststore is $version=$timestamp, where $version is the most recent version
                   14478: number retrieved for the corresponding $symb in the $namespace db file, and
                   14479: $timestamp is the timestamp for that transaction (UNIX time).
                   14480: $laststore is currently only passed when cstore() is called by 
                   14481: structuretags::finalize_storage().
1.191     harris41 14482: 
                   14483: =item *
                   14484: 
1.1269    raeburn  14485: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14486: but uses critical subroutine
1.191     harris41 14487: 
                   14488: =item *
                   14489: 
1.243     albertel 14490: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14491: all args are optional
1.191     harris41 14492: 
                   14493: =item *
                   14494: 
1.717     albertel 14495: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14496: dumps the complete (or key matching regexp) namespace into a hash
                   14497: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14498: normally &store()ed into
                   14499: 
                   14500: $range should be either an integer '100' (give me the first 100
                   14501:                                            matching records)
                   14502:               or be  two integers sperated by a - with no spaces
                   14503:                  '30-50' (give me the 30th through the 50th matching
                   14504:                           records)
                   14505: 
                   14506: 
                   14507: =item *
                   14508: 
1.1269    raeburn  14509: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14510: replaces a &store() version of data with a replacement set of data
                   14511: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14512: reference. If $tolog is true, the transaction is logged in the courselog
                   14513: with an action=PUTSTORE.
1.717     albertel 14514: 
                   14515: =item *
                   14516: 
1.243     albertel 14517: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14518: works very similar to store/cstore, but all data is stored in a
                   14519: temporary location and can be reset using tmpreset, $storehash should
                   14520: be a hash reference, returns nothing on success
1.191     harris41 14521: 
                   14522: =item *
                   14523: 
1.243     albertel 14524: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14525: similar to restore, but all data is stored in a temporary location and
                   14526: can be reset using tmpreset. Returns a hash of values on success,
                   14527: error string otherwise.
1.191     harris41 14528: 
                   14529: =item *
                   14530: 
1.243     albertel 14531: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14532: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14533: 
                   14534: =item *
                   14535: 
1.243     albertel 14536: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14537: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14538: 
                   14539: =item *
                   14540: 
1.243     albertel 14541: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14542: namesp ($udom and $uname are optional)
1.191     harris41 14543: 
                   14544: =item *
                   14545: 
1.702     albertel 14546: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14547: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14548: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14549: 
1.702     albertel 14550: $range should be either an integer '100' (give me the first 100
                   14551:                                            matching records)
                   14552:               or be  two integers sperated by a - with no spaces
                   14553:                  '30-50' (give me the 30th through the 50th matching
                   14554:                           records)
1.449     matthew  14555: =item *
                   14556: 
                   14557: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14558: $store can be a scalar, an array reference, or if the amount to be 
                   14559: incremented is > 1, a hash reference.
                   14560: 
                   14561: ($udom and $uname are optional)
1.191     harris41 14562: 
                   14563: =item *
                   14564: 
1.243     albertel 14565: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14566: ($udom and $uname are optional)
1.191     harris41 14567: 
                   14568: =item *
                   14569: 
1.243     albertel 14570: cput($namespace,$storehash,$udom,$uname) : critical put
                   14571: ($udom and $uname are optional)
1.191     harris41 14572: 
                   14573: =item *
                   14574: 
1.748     albertel 14575: newput($namespace,$storehash,$udom,$uname) :
                   14576: 
                   14577: Attempts to store the items in the $storehash, but only if they don't
                   14578: currently exist, if this succeeds you can be certain that you have 
                   14579: successfully created a new key value pair in the $namespace db.
                   14580: 
                   14581: 
                   14582: Args:
                   14583:  $namespace: name of database to store values to
                   14584:  $storehash: hashref to store to the db
                   14585:  $udom: (optional) domain of user containing the db
                   14586:  $uname: (optional) name of user caontaining the db
                   14587: 
                   14588: Returns:
                   14589:  'ok' -> succeeded in storing all keys of $storehash
                   14590:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14591:                         least <key> already existed in the db (other
                   14592:                         requested keys may also already exist)
1.967     bisitz   14593:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14594:  'con_lost' -> unable to contact request server
                   14595:  'refused' -> action was not allowed by remote machine
                   14596: 
                   14597: 
                   14598: =item *
                   14599: 
1.243     albertel 14600: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14601: reference filled in from namesp (encrypts the return communication)
                   14602: ($udom and $uname are optional)
1.191     harris41 14603: 
                   14604: =item *
                   14605: 
1.243     albertel 14606: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14607: critical subroutine
                   14608: 
1.806     raeburn  14609: =item *
                   14610: 
1.860     raeburn  14611: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14612: array reference filled in from namespace found in domain level on either
                   14613: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14614: 
                   14615: =item *
                   14616: 
1.860     raeburn  14617: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14618: domain level either on specified domain server ($uhome) or primary domain 
                   14619: server ($udom and $uhome are optional)
1.806     raeburn  14620: 
1.943     raeburn  14621: =item * 
                   14622: 
1.1240    raeburn  14623: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14624: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14625: the target domain.
                   14626: 
                   14627: May also include additional key => value pairs for the following groups:
                   14628: 
                   14629: =over
                   14630: 
                   14631: =item
                   14632: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14633: 
                   14634: =over
                   14635: 
                   14636: =item defaultquota, authorquota
                   14637: 
                   14638: =back
                   14639: 
                   14640: =item
                   14641: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14642: portfolio for users).
                   14643: 
                   14644: =over
                   14645: 
                   14646: =item
                   14647: aboutme, blog, webdav, portfolio
                   14648: 
                   14649: =back
                   14650: 
                   14651: =item
                   14652: requestcourses: ability to request courses, and how requests are processed.
                   14653: 
                   14654: =over
                   14655: 
                   14656: =item
1.1305    raeburn  14657: official, unofficial, community, textbook, placement
1.1240    raeburn  14658: 
                   14659: =back
                   14660: 
                   14661: =item
                   14662: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14663: 
                   14664: =over
                   14665: 
                   14666: =item
1.1256    raeburn  14667: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14668: 
                   14669: =back
                   14670: 
                   14671: =item
                   14672: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14673: for course's uploaded content.
                   14674: 
                   14675: =over
                   14676: 
                   14677: =item
1.1246    raeburn  14678: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14679: communityquota, textbookquota, placementquota
1.1240    raeburn  14680: 
                   14681: =back
                   14682: 
                   14683: =item
                   14684: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14685: on your servers.
                   14686: 
                   14687: =over
                   14688: 
                   14689: =item 
                   14690: remotesessions, hostedsessions
                   14691: 
                   14692: =back
                   14693: 
                   14694: =back
                   14695: 
                   14696: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14697: utility to create a configuration.db file on a domain's primary library server 
                   14698: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14699: -- corresponding values are authentication type (internal, krb4, krb5,
                   14700: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14701: will be available. Values are retrieved from cache (if current), unless the
                   14702: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14703: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14704: 
                   14705: Typical usage:
1.943     raeburn  14706: 
1.1240    raeburn  14707: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14708: 
1.243     albertel 14709: =back
                   14710: 
                   14711: =head2 Network Status Functions
                   14712: 
                   14713: =over 4
1.191     harris41 14714: 
                   14715: =item *
                   14716: 
1.1137    raeburn  14717: dirlist() : return directory list based on URI (first arg).
                   14718: 
                   14719: Inputs: 1 required, 5 optional.
                   14720: 
                   14721: =over
                   14722: 
                   14723: =item 
                   14724: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14725: 
                   14726: =item
                   14727: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14728: 
                   14729: =item
                   14730: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14731: 
                   14732: =item
                   14733: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14734: 
                   14735: =item
                   14736: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14737: 
                   14738: =item 
                   14739: $alternateRoot - path to prepend in place of path from $uri.
                   14740: 
                   14741: =back
                   14742: 
                   14743: Returns: Array of up to two items.
                   14744: 
                   14745: =over
                   14746: 
                   14747: a reference to an array of files/subdirectories
                   14748: 
                   14749: =over
                   14750: 
                   14751: Each element in the array of files/subdirectories is a & separated list of
                   14752: item name and the result of running stat on the item.  If dirlist was requested
                   14753: for a file instead of a directory, the item name will be ''. For a directory 
                   14754: listing, if the item is a metadata file, the element will end &N&M 
                   14755: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14756: default copyright set (1).  
                   14757: 
                   14758: =back
                   14759: 
                   14760: a scalar containing error condition (if encountered).
                   14761: 
                   14762: =over
                   14763: 
                   14764: =item 
                   14765: no_host (no homeserver identified for $username:$domain).
                   14766: 
                   14767: =item 
                   14768: no_such_host (server contacted for listing not identified as valid host).
                   14769: 
                   14770: =item 
                   14771: con_lost (connection to remote server failed).
                   14772: 
                   14773: =item 
                   14774: refused (invalid $username:$domain received on lond side).
                   14775: 
                   14776: =item 
                   14777: no_such_dir (directory at specified path on lond side does not exist). 
                   14778: 
                   14779: =item 
                   14780: empty (directory at specified path on lond side is empty).
                   14781: 
                   14782: =over
                   14783: 
                   14784: This is currently not encountered because the &ls3, &ls2, 
                   14785: &ls (_handler) routines on the lond side do not filter out
                   14786: . and .. from a directory listing. 
                   14787: 
                   14788: =back
                   14789: 
                   14790: =back
                   14791: 
                   14792: =back
1.191     harris41 14793: 
                   14794: =item *
                   14795: 
1.243     albertel 14796: spareserver() : find server with least workload from spare.tab
                   14797: 
1.986     foxr     14798: 
                   14799: =item *
                   14800: 
                   14801: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14802: if there is no corresponding loncapa host.
                   14803: 
1.243     albertel 14804: =back
                   14805: 
1.986     foxr     14806: 
1.243     albertel 14807: =head2 Apache Request
                   14808: 
                   14809: =over 4
1.191     harris41 14810: 
                   14811: =item *
                   14812: 
1.243     albertel 14813: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14814: localhost, posts hash
                   14815: 
                   14816: =back
                   14817: 
                   14818: =head2 Data to String to Data
                   14819: 
                   14820: =over 4
1.191     harris41 14821: 
                   14822: =item *
                   14823: 
1.243     albertel 14824: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14825: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14826: 
                   14827: =item *
                   14828: 
1.243     albertel 14829: hashref2str($hashref) : convert a hashref into a string complete with
                   14830: escaping and '=' and '&' separators, supports elements that are
                   14831: arrayrefs and hashrefs
1.191     harris41 14832: 
                   14833: =item *
                   14834: 
1.243     albertel 14835: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14836: with escaping and '&' separators, supports elements that are arrayrefs
                   14837: and hashrefs
1.191     harris41 14838: 
                   14839: =item *
                   14840: 
1.243     albertel 14841: str2hash($string) : convert string to hash using unescaping and
                   14842: splitting on '=' and '&', supports elements that are arrayrefs and
                   14843: hashrefs
1.191     harris41 14844: 
                   14845: =item *
                   14846: 
1.243     albertel 14847: str2array($string) : convert string to hash using unescaping and
                   14848: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14849: 
                   14850: =back
                   14851: 
                   14852: =head2 Logging Routines
                   14853: 
                   14854: 
                   14855: These routines allow one to make log messages in the lonnet.log and
                   14856: lonnet.perm logfiles.
1.191     harris41 14857: 
1.1119    foxr     14858: =over 4
                   14859: 
1.191     harris41 14860: =item *
                   14861: 
1.243     albertel 14862: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14863: 
                   14864: =item *
                   14865: 
1.243     albertel 14866: logthis() : append message to the normal lonnet.log file, it gets
                   14867: preiodically rolled over and deleted.
1.191     harris41 14868: 
                   14869: =item *
                   14870: 
1.243     albertel 14871: logperm() : append a permanent message to lonnet.perm.log, this log
                   14872: file never gets deleted by any automated portion of the system, only
                   14873: messages of critical importance should go in here.
                   14874: 
1.1119    foxr     14875: 
1.243     albertel 14876: =back
                   14877: 
                   14878: =head2 General File Helper Routines
                   14879: 
                   14880: =over 4
1.191     harris41 14881: 
                   14882: =item *
                   14883: 
1.481     raeburn  14884: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   14885: (a) files in /uploaded
                   14886:   (i) If a local copy of the file exists - 
                   14887:       compares modification date of local copy with last-modified date for 
                   14888:       definitive version stored on home server for course. If local copy is 
                   14889:       stale, requests a new version from the home server and stores it. 
                   14890:       If the original has been removed from the home server, then local copy 
                   14891:       is unlinked.
                   14892:   (ii) If local copy does not exist -
                   14893:       requests the file from the home server and stores it. 
                   14894:   
                   14895:   If $caller is 'uploadrep':  
                   14896:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   14897:     for request for files originally uploaded via DOCS. 
                   14898:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   14899:   
                   14900:   Otherwise:
                   14901:      This indicates a call from the content generation phase of the request.
                   14902:      -  returns the entire contents of the file or -1.
                   14903:      
                   14904: (b) files in /res
                   14905:    - returns the entire contents of a file or -1; 
                   14906:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 14907: 
1.712     albertel 14908: 
                   14909: =item *
                   14910: 
                   14911: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   14912:                   reference
                   14913: 
                   14914: returns either a stat() list of data about the file or an empty list
                   14915: if the file doesn't exist or couldn't find out about it (connection
                   14916: problems or user unknown)
                   14917: 
1.191     harris41 14918: =item *
                   14919: 
1.243     albertel 14920: filelocation($dir,$file) : returns file system location of a file
                   14921: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   14922: directory that relative $file lookups are to looked in ($dir of /a/dir
                   14923: and a file of ../bob will become /a/bob)
1.191     harris41 14924: 
                   14925: =item *
                   14926: 
                   14927: hreflocation($dir,$file) : returns file system location or a URL; same as
                   14928: filelocation except for hrefs
                   14929: 
                   14930: =item *
                   14931: 
1.1261    raeburn  14932: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   14933: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 14934: 
1.243     albertel 14935: =back
                   14936: 
1.608     albertel 14937: =head2 Usererfile file routines (/uploaded*)
                   14938: 
                   14939: =over 4
                   14940: 
                   14941: =item *
                   14942: 
                   14943: userfileupload(): main rotine for putting a file in a user or course's
                   14944:                   filespace, arguments are,
                   14945: 
1.620     albertel 14946:  formname - required - this is the name of the element in $env where the
1.608     albertel 14947:            filename, and the contents of the file to create/modifed exist
1.620     albertel 14948:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   14949:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  14950:  context - if coursedoc, store the file in the course of the active role
                   14951:              of the current user; 
                   14952:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   14953:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 14954:  subdir - required - subdirectory to put the file in under ../userfiles/
                   14955:          if undefined, it will be placed in "unknown"
                   14956: 
                   14957:  (This routine calls clean_filename() to remove any dangerous
                   14958:  characters from the filename, and then calls finuserfileupload() to
                   14959:  complete the transaction)
                   14960: 
                   14961:  returns either the url of the uploaded file (/uploaded/....) if successful
                   14962:  and /adm/notfound.html if unsuccessful
                   14963: 
                   14964: =item *
                   14965: 
                   14966: clean_filename(): routine for cleaing a filename up for storage in
                   14967:                  userfile space, argument is:
                   14968: 
                   14969:  filename - proposed filename
                   14970: 
                   14971: returns: the new clean filename
                   14972: 
                   14973: =item *
                   14974: 
1.1090    raeburn  14975: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 14976: userspace, probably shouldn't be called directly
                   14977: 
                   14978:   docuname: username or courseid of destination for the file
                   14979:   docudom: domain of user/course of destination for the file
                   14980:   formname: same as for userfileupload()
1.1090    raeburn  14981:   fname: filename (including subdirectories) for the file
                   14982:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   14983:   allfiles: reference to hash used to store objects found by parser
                   14984:   codebase: reference to hash used for codebases of java objects found by parser
                   14985:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   14986:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   14987:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   14988:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   14989:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   14990:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  14991:   mimetype: reference to scalar to accommodate mime type determined
                   14992:             from File::MMagic if $parser = parse.
1.608     albertel 14993: 
                   14994:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  14995:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   14996:  was 'overwrite').
                   14997:  
1.608     albertel 14998: 
                   14999: =item *
                   15000: 
                   15001: renameuserfile(): renames an existing userfile to a new name
                   15002: 
                   15003:   Args:
                   15004:    docuname: username or courseid of destination for the file
                   15005:    docudom: domain of user/course of destination for the file
                   15006:    old: current file name (including any subdirs under userfiles)
                   15007:    new: desired file name (including any subdirs under userfiles)
                   15008: 
                   15009: =item *
                   15010: 
                   15011: mkdiruserfile(): creates a directory is a userfiles dir
                   15012: 
                   15013:   Args:
                   15014:    docuname: username or courseid of destination for the file
                   15015:    docudom: domain of user/course of destination for the file
                   15016:    dir: dir to create (including any subdirs under userfiles)
                   15017: 
                   15018: =item *
                   15019: 
                   15020: removeuserfile(): removes a file that exists in userfiles
                   15021: 
                   15022:   Args:
                   15023:    docuname: username or courseid of destination for the file
                   15024:    docudom: domain of user/course of destination for the file
                   15025:    fname: filname to delete (including any subdirs under userfiles)
                   15026: 
                   15027: =item *
                   15028: 
                   15029: removeuploadedurl(): convience function for removeuserfile()
                   15030: 
                   15031:   Args:
                   15032:    url:  a full /uploaded/... url to delete
                   15033: 
1.747     albertel 15034: =item * 
                   15035: 
                   15036: get_portfile_permissions():
                   15037:   Args:
                   15038:     domain: domain of user or course contain the portfolio files
                   15039:     user: name of user or num of course contain the portfolio files
                   15040:   Returns:
                   15041:     hashref of a dump of the proper file_permissions.db
                   15042:    
                   15043: 
                   15044: =item * 
                   15045: 
                   15046: get_access_controls():
                   15047: 
                   15048: Args:
                   15049:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15050:   group: (optional) the group you want the files associated with
                   15051:   file: (optional) the file you want access info on
                   15052: 
                   15053: Returns:
1.749     raeburn  15054:     a hash (keys are file names) of hashes containing
                   15055:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15056:         values are XML containing access control settings (see below) 
1.747     albertel 15057: 
                   15058: Internal notes:
                   15059: 
1.749     raeburn  15060:  access controls are stored in file_permissions.db as key=value pairs.
                   15061:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15062:         where scope -> public,guest,course,group,domains or users.
                   15063:               end -> UNIX time for end of access (0 -> no end date)
                   15064:               start -> UNIX time for start of access
                   15065: 
                   15066:     value -> XML description of access control
                   15067:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15068:             <start></start>
                   15069:             <end></end>
                   15070: 
                   15071:             <password></password>  for scope type = guest
                   15072: 
                   15073:             <domain></domain>     for scope type = course or group
                   15074:             <number></number>
                   15075:             <roles id="">
                   15076:              <role></role>
                   15077:              <access></access>
                   15078:              <section></section>
                   15079:              <group></group>
                   15080:             </roles>
                   15081: 
                   15082:             <dom></dom>         for scope type = domains
                   15083: 
                   15084:             <users>             for scope type = users
                   15085:              <user>
                   15086:               <uname></uname>
                   15087:               <udom></udom>
                   15088:              </user>
                   15089:             </users>
                   15090:            </scope> 
                   15091:               
                   15092:  Access data is also aggregated for each file in an additional key=value pair:
                   15093:  key -> path to file/file_name\0accesscontrol 
                   15094:  value -> reference to hash
                   15095:           hash contains key = value pairs
                   15096:           where key = uniqueID:scope_end_start
                   15097:                 value = UNIX time record was last updated
                   15098: 
                   15099:           Used to improve speed of look-ups of access controls for each file.  
                   15100:  
                   15101:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15102: 
1.1198    raeburn  15103: =item *
                   15104: 
1.749     raeburn  15105: modify_access_controls():
                   15106: 
                   15107: Modifies access controls for a portfolio file
                   15108: Args
                   15109: 1. file name
                   15110: 2. reference to hash of required changes,
                   15111: 3. domain
                   15112: 4. username
                   15113:   where domain,username are the domain of the portfolio owner 
                   15114:   (either a user or a course) 
                   15115: 
                   15116: Returns:
                   15117: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15118: 2. result of deletions ('ok' or 'error', with error message).
                   15119: 3. reference to hash of any new or updated access controls.
                   15120: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15121:    key = integer (inbound ID)
1.1198    raeburn  15122:    value = uniqueID
                   15123: 
                   15124: =item *
                   15125: 
                   15126: get_timebased_id():
                   15127: 
                   15128: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15129: course via the Course Editor (e.g., folders, composite pages, 
                   15130: group bulletin boards).
                   15131: 
                   15132: Args: (first three required; six others optional)
                   15133: 
                   15134: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15135:    docssequence, or name of group
                   15136: 
                   15137: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15138:    e.g., num, boardids
                   15139: 
                   15140: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15141:    file will be named nohist_namespace.db
                   15142: 
                   15143: 4. cdom: domain of course; default is current course domain from %env
                   15144: 
                   15145: 5. cnum: course number; default is current course number from %env
                   15146: 
                   15147: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15148:    unix timestamp to form the suffix, if the plain timestamp is already
                   15149:    in use.  Default is to not do this, but simply increment the unix 
                   15150:    timestamp by 1 until a unique key is obtained.
                   15151: 
                   15152: 7. who: holder of locking key; defaults to user:domain for user.
                   15153: 
                   15154: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15155:    retrying); default is 3.
                   15156: 
                   15157: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15158: 
                   15159: Returns:
                   15160: 
                   15161: 1. suffix obtained (numeric)
                   15162: 
                   15163: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15164: 
                   15165: 3. error: contains (localized) error message if an error occurred.
                   15166: 
1.747     albertel 15167: 
1.608     albertel 15168: =back
                   15169: 
1.243     albertel 15170: =head2 HTTP Helper Routines
                   15171: 
                   15172: =over 4
                   15173: 
1.191     harris41 15174: =item *
                   15175: 
                   15176: escape() : unpack non-word characters into CGI-compatible hex codes
                   15177: 
                   15178: =item *
                   15179: 
                   15180: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15181: 
1.243     albertel 15182: =back
                   15183: 
                   15184: =head1 PRIVATE SUBROUTINES
                   15185: 
                   15186: =head2 Underlying communication routines (Shouldn't call)
                   15187: 
                   15188: =over 4
                   15189: 
                   15190: =item *
                   15191: 
                   15192: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15193: 
                   15194: =item *
                   15195: 
                   15196: reply() : uses subreply to send a message to remote machine, logs all failures
                   15197: 
                   15198: =item *
                   15199: 
                   15200: critical() : passes a critical message to another server; if cannot
                   15201: get through then place message in connection buffer directory and
                   15202: returns con_delayed, if incapable of saving message, returns
                   15203: con_failed
                   15204: 
                   15205: =item *
                   15206: 
                   15207: reconlonc() : tries to reconnect lonc client processes.
                   15208: 
                   15209: =back
                   15210: 
                   15211: =head2 Resource Access Logging
                   15212: 
                   15213: =over 4
                   15214: 
                   15215: =item *
                   15216: 
                   15217: flushcourselogs() : flush (save) buffer logs and access logs
                   15218: 
                   15219: =item *
                   15220: 
                   15221: courselog($what) : save message for course in hash
                   15222: 
                   15223: =item *
                   15224: 
                   15225: courseacclog($what) : save message for course using &courselog().  Perform
                   15226: special processing for specific resource types (problems, exams, quizzes, etc).
                   15227: 
1.191     harris41 15228: =item *
                   15229: 
                   15230: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15231: as a PerlChildExitHandler
1.243     albertel 15232: 
                   15233: =back
                   15234: 
                   15235: =head2 Other
                   15236: 
                   15237: =over 4
                   15238: 
                   15239: =item *
                   15240: 
                   15241: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15242: 
                   15243: =back
                   15244: 
                   15245: =cut
1.877     foxr     15246: 

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