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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1346  ! raeburn     4: # $Id: lonnet.pm,v 1.1345 2017/05/23 03:07:43 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
                     76: 
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.1245    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     82:             %managerstab);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.1289    damieng    94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.807     albertel   99: use LONCAPA qw(:DEFAULT :match);
1.740     www       100: use LONCAPA::Configuration;
1.1160    www       101: use LONCAPA::lonmetadata;
1.1167    droeschl  102: use LONCAPA::Lond;
1.1345    raeburn   103: use LONCAPA::LWPReq;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
                    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:             }
1.1346  ! raeburn   246:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
        !           247:             if ($1 < 12) {
        !           248:                 $uselocal = 0;
        !           249:             }
1.1315    raeburn   250:         }
                    251:     }
                    252:     if ($uselocal) {
                    253:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
                    254:     } else {
                    255:         $rep=&reply('servercerts',$lonhost);
                    256:     }
                    257:     my ($result,%returnhash);
                    258:     if (defined($lonhost)) {
                    259:         if (!defined(&hostname($lonhost))) {
                    260:             return;
                    261:         }
                    262:     }
                    263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    264:         ($rep eq 'unknown_cmd')) {
                    265:         $result = $rep;
                    266:     } else {
                    267:         $result = 'ok';
                    268:         my @pairs=split(/\&/,$rep);
                    269:         foreach my $item (@pairs) {
                    270:             my ($key,$value)=split(/=/,$item,2);
                    271:             my $what = &unescape($key);
                    272:             $returnhash{$what}=&thaw_unescape($value);
                    273:         }
                    274:     }
                    275:     return ($result,\%returnhash);
                    276: }
                    277: 
1.993     raeburn   278: sub get_server_loncaparev {
1.1073    raeburn   279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   280:     if (defined($lonhost)) {
                    281:         if (!defined(&hostname($lonhost))) {
                    282:             undef($lonhost);
                    283:         }
                    284:     }
                    285:     if (!defined($lonhost)) {
                    286:         if (defined(&domain($dom,'primary'))) {
                    287:             $lonhost=&domain($dom,'primary');
                    288:             if ($lonhost eq 'no_host') {
                    289:                 undef($lonhost);
                    290:             }
                    291:         }
                    292:     }
                    293:     if (defined($lonhost)) {
1.1073    raeburn   294:         my $cachetime = 12*3600;
                    295:         if (!$ignore_cache) {
                    296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    297:             if (defined($cached)) {
                    298:                 return $loncaparev;
                    299:             }
                    300:         }
                    301:         my ($answer,$loncaparev);
                    302:         my @ids=&current_machine_ids();
                    303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    304:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   306:                 $loncaparev = $1;
                    307:             }
                    308:         } else {
                    309:             $answer = &reply('serverloncaparev',$lonhost);
                    310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    311:                 if ($caller eq 'loncron') {
                    312:                     my $protocol = $protocol{$lonhost};
                    313:                     $protocol = 'http' if ($protocol ne 'https');
                    314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    315:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   317:                     unless ($response->is_error()) {
                    318:                         my $content = $response->content;
1.1081    raeburn   319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   320:                             $loncaparev = $1;
                    321:                         }
                    322:                     }
                    323:                 } else {
                    324:                     $loncaparev = $loncaparevs{$lonhost};
                    325:                 }
1.1081    raeburn   326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   327:                 $loncaparev = $1;
                    328:             }
1.993     raeburn   329:         }
1.1073    raeburn   330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   331:     }
                    332: }
                    333: 
1.1074    raeburn   334: sub get_server_homeID {
                    335:     my ($hostname,$ignore_cache,$caller) = @_;
                    336:     unless ($ignore_cache) {
                    337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    338:         if (defined($cached)) {
                    339:             return $serverhomeID;
                    340:         }
                    341:     }
                    342:     my $cachetime = 12*3600;
                    343:     my $serverhomeID;
                    344:     if ($caller eq 'loncron') { 
                    345:         my @machine_ids = &machine_ids($hostname);
                    346:         foreach my $id (@machine_ids) {
                    347:             my $response = &reply('serverhomeID',$id);
                    348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    349:                 $serverhomeID = $response;
                    350:                 last;
                    351:             }
                    352:         }
                    353:         if ($serverhomeID eq '') {
                    354:             $serverhomeID = $machine_ids[-1];
                    355:         }
                    356:     } else {
                    357:         $serverhomeID = $serverhomeIDs{$hostname};
                    358:     }
                    359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    360: }
                    361: 
1.1121    raeburn   362: sub get_remote_globals {
                    363:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   364:     my ($result,%returnhash,%whatneeded);
                    365:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   366:         foreach my $what (sort(keys(%{$whathash}))) {
                    367:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   368:             my ($response,$cached);
1.1121    raeburn   369:             unless ($ignore_cache) {
1.1125    raeburn   370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   371:             }
                    372:             if (defined($cached)) {
1.1125    raeburn   373:                 $returnhash{$what} = $response;
1.1121    raeburn   374:             } else {
1.1125    raeburn   375:                 $whatneeded{$what} = 1;
1.1121    raeburn   376:             }
                    377:         }
1.1125    raeburn   378:         if (keys(%whatneeded) == 0) {
                    379:             $result = 'ok';
                    380:         } else {
1.1121    raeburn   381:             my $requested = &freeze_escape(\%whatneeded);
                    382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    384:                 ($rep eq 'unknown_cmd')) {
                    385:                 $result = $rep;
                    386:             } else {
                    387:                 $result = 'ok';
1.1121    raeburn   388:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   389:                 foreach my $item (@pairs) {
                    390:                     my ($key,$value)=split(/=/,$item,2);
                    391:                     my $what = &unescape($key);
                    392:                     my $hashid = $lonhost.'-'.$what;
                    393:                     $returnhash{$what}=&thaw_unescape($value);
                    394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   395:                 }
                    396:             }
                    397:         }
                    398:     }
1.1125    raeburn   399:     return ($result,\%returnhash);
1.1121    raeburn   400: }
                    401: 
1.1124    raeburn   402: sub remote_devalidate_cache {
1.1241    raeburn   403:     my ($lonhost,$cachekeys) = @_;
                    404:     my $items;
                    405:     return unless (ref($cachekeys) eq 'ARRAY');
                    406:     my $cachestr = join('&',@{$cachekeys});
                    407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   408:     return $response;
                    409: }
                    410: 
1.1       albertel  411: # -------------------------------------------------- Non-critical communication
                    412: sub subreply {
                    413:     my ($cmd,$server)=@_;
1.838     albertel  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      415:     #
                    416:     #  With loncnew process trimming, there's a timing hole between lonc server
                    417:     #  process exit and the master server picking up the listen on the AF_UNIX
                    418:     #  socket.  In that time interval, a lock file will exist:
                    419: 
                    420:     my $lockfile=$peerfile.".lock";
                    421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   422: 	sleep(0.1);
1.549     foxr      423:     }
                    424:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      425:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      426:     #
1.550     foxr      427:     #   We'll give the connection a few tries before abandoning it.  If
                    428:     #   connection is not possible, we'll con_lost back to the client.
                    429:     #   
                    430:     my $client;
                    431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    433: 				      Type    => SOCK_STREAM,
                    434: 				      Timeout => 10);
1.869     albertel  435: 	if ($client) {
1.550     foxr      436: 	    last;		# Connected!
1.850     albertel  437: 	} else {
1.853     albertel  438: 	    &create_connection(&hostname($server),$server);
1.550     foxr      439: 	}
1.1289    damieng   440:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      441:     }
                    442:     my $answer;
                    443:     if ($client) {
1.704     albertel  444: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      445: 	$answer=<$client>;
                    446: 	if (!$answer) { $answer="con_lost"; }
                    447: 	chomp($answer);
                    448:     } else {
                    449: 	$answer = 'con_lost';	# Failed connection.
                    450:     }
1.1       albertel  451:     return $answer;
                    452: }
                    453: 
                    454: sub reply {
                    455:     my ($cmd,$server)=@_;
1.838     albertel  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  457:     my $answer=subreply($cmd,$server);
1.65      www       458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  459:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       460:                 " $cmd to $server returned $answer</font>");
                    461:     }
1.1       albertel  462:     return $answer;
                    463: }
                    464: 
                    465: # ----------------------------------------------------------- Send USR1 to lonc
                    466: 
                    467: sub reconlonc {
1.891     albertel  468:     my ($lonid) = @_;
                    469:     if ($lonid) {
1.1295    raeburn   470:         my $hostname = &hostname($lonid);
1.891     albertel  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    472: 	if ($hostname && -e $peerfile) {
                    473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    475: 					     Type    => SOCK_STREAM,
                    476: 					     Timeout => 10);
                    477: 	    if ($client) {
                    478: 		print $client ("reset_retries\n");
                    479: 		my $answer=<$client>;
                    480: 		#reset just this one.
                    481: 	    }
                    482: 	}
                    483: 	return;
                    484:     }
                    485: 
1.836     www       486:     &logthis("Trying to reconnect lonc");
1.1       albertel  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  488:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  489: 	my $loncpid=<$fh>;
                    490:         chomp($loncpid);
                    491:         if (kill 0 => $loncpid) {
                    492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    493:             kill USR1 => $loncpid;
                    494:             sleep 1;
1.1295    raeburn   495:         } else {
1.12      www       496: 	    &logthis(
1.672     albertel  497:                "<font color=\"blue\">WARNING:".
1.12      www       498:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  499:         }
                    500:     } else {
1.836     www       501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  502:     }
                    503: }
                    504: 
                    505: # ------------------------------------------------------ Critical communication
1.12      www       506: 
1.1       albertel  507: sub critical {
                    508:     my ($cmd,$server)=@_;
1.838     albertel  509:     unless (&hostname($server)) {
1.672     albertel  510:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       511:                " Critical message to unknown server ($server)</font>");
                    512:         return 'no_such_host';
                    513:     }
1.1       albertel  514:     my $answer=reply($cmd,$server);
                    515:     if ($answer eq 'con_lost') {
1.1295    raeburn   516: 	&reconlonc($server);
1.589     albertel  517: 	my $answer=reply($cmd,$server);
1.1       albertel  518:         if ($answer eq 'con_lost') {
                    519:             my $now=time;
                    520:             my $middlename=$cmd;
1.5       www       521:             $middlename=substr($middlename,0,16);
1.1       albertel  522:             $middlename=~s/\W//g;
                    523:             my $dfilename=
1.305     www       524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    525:             $dumpcount++;
1.1       albertel  526:             {
1.448     albertel  527: 		my $dfh;
                    528: 		if (open($dfh,">$dfilename")) {
                    529: 		    print $dfh "$cmd\n"; 
                    530: 		    close($dfh);
                    531: 		}
1.1       albertel  532:             }
1.1288    damieng   533:             sleep 1;
1.1       albertel  534:             my $wcmd='';
                    535:             {
1.448     albertel  536: 		my $dfh;
                    537: 		if (open($dfh,"<$dfilename")) {
                    538: 		    $wcmd=<$dfh>; 
                    539: 		    close($dfh);
                    540: 		}
1.1       albertel  541:             }
                    542:             chomp($wcmd);
1.7       www       543:             if ($wcmd eq $cmd) {
1.672     albertel  544: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       545:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  546:                 &logperm("D:$server:$cmd");
                    547: 	        return 'con_delayed';
                    548:             } else {
1.672     albertel  549:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       550:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  551:                 &logperm("F:$server:$cmd");
                    552:                 return 'con_failed';
                    553:             }
                    554:         }
                    555:     }
                    556:     return $answer;
1.405     albertel  557: }
                    558: 
1.755     albertel  559: # ------------------------------------------- check if return value is an error
                    560: 
                    561: sub error {
                    562:     my ($result) = @_;
1.756     albertel  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  564: 	if ($2 == 2) { return undef; }
                    565: 	return $1;
                    566:     }
                    567:     return undef;
                    568: }
                    569: 
1.783     albertel  570: sub convert_and_load_session_env {
                    571:     my ($lonidsdir,$handle)=@_;
                    572:     my @profile;
                    573:     {
1.917     albertel  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    575: 	if (!$opened) {
1.915     albertel  576: 	    return 0;
                    577: 	}
1.783     albertel  578: 	flock($idf,LOCK_SH);
                    579: 	@profile=<$idf>;
                    580: 	close($idf);
                    581:     }
                    582:     my %temp_env;
                    583:     foreach my $line (@profile) {
1.786     albertel  584: 	if ($line !~ m/=/) {
                    585: 	    return 0;
                    586: 	}
1.783     albertel  587: 	chomp($line);
                    588: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    590:     }
                    591:     unlink("$lonidsdir/$handle.id");
                    592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    593: 	    0640)) {
                    594: 	%disk_env = %temp_env;
                    595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    596: 	untie(%disk_env);
                    597:     }
1.786     albertel  598:     return 1;
1.783     albertel  599: }
                    600: 
1.374     www       601: # ------------------------------------------- Transfer profile into environment
1.780     albertel  602: my $env_loaded;
                    603: sub transfer_profile_to_env {
1.788     albertel  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    605:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       606: 
1.720     albertel  607:     if (!defined($lonidsdir)) {
                    608: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    609:     }
                    610:     if (!defined($handle)) {
                    611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    612:     }
                    613: 
1.786     albertel  614:     my $convert;
                    615:     {
1.917     albertel  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    617: 	if (!$opened) {
1.915     albertel  618: 	    return;
                    619: 	}
1.786     albertel  620: 	flock($idf,LOCK_SH);
                    621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    622: 		&GDBM_READER(),0640)) {
                    623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    624: 	    untie(%disk_env);
                    625: 	} else {
                    626: 	    $convert = 1;
                    627: 	}
                    628:     }
                    629:     if ($convert) {
                    630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    631: 	    &logthis("Failed to load session, or convert session.");
                    632: 	}
1.374     www       633:     }
1.783     albertel  634: 
1.786     albertel  635:     my %remove;
1.783     albertel  636:     while ( my $envname = each(%env) ) {
1.433     matthew   637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    638:             if ($time < time-300) {
1.783     albertel  639:                 $remove{$key}++;
1.433     matthew   640:             }
                    641:         }
                    642:     }
1.783     albertel  643: 
1.619     albertel  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  645:     $env_loaded=1;
1.783     albertel  646:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   647:         &delenv($expired_key);
1.374     www       648:     }
1.1       albertel  649: }
                    650: 
1.916     albertel  651: # ---------------------------------------------------- Check for valid session 
                    652: sub check_for_valid_session {
1.1245    raeburn   653:     my ($r,$name,$userhashref) = @_;
1.916     albertel  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1337    raeburn   655:     my ($linkname,$pubname);
1.1155    raeburn   656:     if ($name eq '') {
                    657:         $name = 'lonID';
1.1337    raeburn   658:         $linkname = 'lonLinkID';
                    659:         $pubname = 'lonPubID';
1.1155    raeburn   660:     }
                    661:     my $lonid=$cookies{$name};
1.1337    raeburn   662:     if (!$lonid) {
                    663:         if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
                    664:             $lonid=$cookies{$linkname};
                    665:         }
                    666:         if (!$lonid) {
                    667:             if (($name eq 'lonID') && ($pubname)) {
                    668:                 $lonid=$cookies{$pubname};
                    669:             }
                    670:         }
                    671:     }
1.916     albertel  672:     return undef if (!$lonid);
                    673: 
                    674:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   675:     my $lonidsdir;
                    676:     if ($name eq 'lonDAV') {
                    677:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    678:     } else {
                    679:         $lonidsdir=$r->dir_config('lonIDsDir');
                    680:     }
1.916     albertel  681:     return undef if (!-e "$lonidsdir/$handle.id");
                    682: 
1.917     albertel  683:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    684:     return undef if (!$opened);
1.916     albertel  685: 
                    686:     flock($idf,LOCK_SH);
                    687:     my %disk_env;
                    688:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    689: 	    &GDBM_READER(),0640)) {
                    690: 	return undef;	
                    691:     }
                    692: 
                    693:     if (!defined($disk_env{'user.name'})
                    694: 	|| !defined($disk_env{'user.domain'})) {
                    695: 	return undef;
                    696:     }
1.1245    raeburn   697: 
                    698:     if (ref($userhashref) eq 'HASH') {
                    699:         $userhashref->{'name'} = $disk_env{'user.name'};
                    700:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1212    raeburn   701:     }
1.1245    raeburn   702: 
1.916     albertel  703:     return $handle;
                    704: }
                    705: 
1.830     albertel  706: sub timed_flock {
                    707:     my ($file,$lock_type) = @_;
                    708:     my $failed=0;
                    709:     eval {
                    710: 	local $SIG{__DIE__}='DEFAULT';
                    711: 	local $SIG{ALRM}=sub {
                    712: 	    $failed=1;
                    713: 	    die("failed lock");
                    714: 	};
                    715: 	alarm(13);
                    716: 	flock($file,$lock_type);
                    717: 	alarm(0);
                    718:     };
                    719:     if ($failed) {
                    720: 	return undef;
                    721:     } else {
                    722: 	return 1;
                    723:     }
                    724: }
                    725: 
1.5       www       726: # ---------------------------------------------------------- Append Environment
                    727: 
                    728: sub appenv {
1.949     raeburn   729:     my ($newenv,$roles) = @_;
                    730:     if (ref($newenv) eq 'HASH') {
                    731:         foreach my $key (keys(%{$newenv})) {
                    732:             my $refused = 0;
                    733: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    734:                 $refused = 1;
                    735:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   736:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   737:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    738:                         $refused = 0;
                    739:                     }
                    740:                 }
                    741:             }
                    742:             if ($refused) {
                    743:                 &logthis("<font color=\"blue\">WARNING: ".
                    744:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    745:                          .'</font>');
                    746: 	        delete($newenv->{$key});
                    747:             } else {
                    748:                 $env{$key}=$newenv->{$key};
                    749:             }
                    750:         }
                    751:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    752:         if ($opened
                    753: 	    && &timed_flock($env_file,LOCK_EX)
                    754: 	    &&
                    755: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    756: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    757: 	    while (my ($key,$value) = each(%{$newenv})) {
                    758: 	        $disk_env{$key} = $value;
                    759: 	    }
                    760: 	    untie(%disk_env);
1.35      www       761:         }
1.191     harris41  762:     }
1.56      www       763:     return 'ok';
                    764: }
                    765: # ----------------------------------------------------- Delete from Environment
                    766: 
                    767: sub delenv {
1.1104    raeburn   768:     my ($delthis,$regexp,$roles) = @_;
                    769:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    770:         my $refused = 1;
                    771:         if (ref($roles) eq 'ARRAY') {
                    772:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    773:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    774:                 $refused = 0;
                    775:             }
                    776:         }
                    777:         if ($refused) {
                    778:             &logthis("<font color=\"blue\">WARNING: ".
                    779:                      "Attempt to delete from environment ".$delthis);
                    780:             return 'error';
                    781:         }
1.56      www       782:     }
1.917     albertel  783:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    784:     if ($opened
1.915     albertel  785: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  786: 	&&
                    787: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    788: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  789: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   790: 	    if ($regexp) {
                    791:                 if ($key=~/^$delthis/) {
                    792:                     delete($env{$key});
                    793:                     delete($disk_env{$key});
                    794:                 } 
                    795:             } else {
                    796:                 if ($key=~/^\Q$delthis\E/) {
                    797: 		    delete($env{$key});
                    798: 		    delete($disk_env{$key});
                    799: 	        }
                    800:             }
1.448     albertel  801: 	}
1.783     albertel  802: 	untie(%disk_env);
1.5       www       803:     }
                    804:     return 'ok';
1.369     albertel  805: }
                    806: 
1.790     albertel  807: sub get_env_multiple {
                    808:     my ($name) = @_;
                    809:     my @values;
                    810:     if (defined($env{$name})) {
                    811:         # exists is it an array
                    812:         if (ref($env{$name})) {
                    813:             @values=@{ $env{$name} };
                    814:         } else {
                    815:             $values[0]=$env{$name};
                    816:         }
                    817:     }
                    818:     return(@values);
                    819: }
                    820: 
1.958     www       821: # ------------------------------------------------------------------- Locking
                    822: 
                    823: sub set_lock {
                    824:     my ($text)=@_;
                    825:     $locknum++;
                    826:     my $id=$$.'-'.$locknum;
                    827:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    828:              'session.lock.'.$id => $text});
                    829:     return $id;
                    830: }
                    831: 
                    832: sub get_locks {
                    833:     my $num=0;
                    834:     my %texts=();
                    835:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    836:        if ($lock=~/\w/) {
                    837:           $num++;
                    838:           $texts{$lock}=$env{'session.lock.'.$lock};
                    839:        }
                    840:    }
                    841:    return ($num,%texts);
                    842: }
                    843: 
                    844: sub remove_lock {
                    845:     my ($id)=@_;
                    846:     my $newlocks='';
                    847:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    848:        if (($lock=~/\w/) && ($lock ne $id)) {
                    849:           $newlocks.=','.$lock;
                    850:        }
                    851:     }
                    852:     &appenv({'session.locks' => $newlocks});
                    853:     &delenv('session.lock.'.$id);
                    854: }
                    855: 
                    856: sub remove_all_locks {
                    857:     my $activelocks=$env{'session.locks'};
                    858:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    859:        if ($lock=~/\w/) {
                    860:           &remove_lock($lock);
                    861:        }
                    862:     }
                    863: }
                    864: 
                    865: 
1.369     albertel  866: # ------------------------------------------ Find out current server userload
                    867: sub userload {
                    868:     my $numusers=0;
                    869:     {
                    870: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    871: 	my $filename;
                    872: 	my $curtime=time;
                    873: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  874: 	    next if ($filename eq '.' || $filename eq '..');
                    875: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  876: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  877: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  878: 	}
                    879: 	closedir(LONIDS);
                    880:     }
                    881:     my $userloadpercent=0;
                    882:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    883:     if ($maxuserload) {
1.371     albertel  884: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  885:     }
1.372     albertel  886:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  887:     return $userloadpercent;
1.283     www       888: }
                    889: 
1.1       albertel  890: # ------------------------------ Find server with least workload from spare.tab
1.11      www       891: 
1.1       albertel  892: sub spareserver {
1.1083    raeburn   893:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  894:     my $spare_server;
1.370     albertel  895:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  896:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    897:                                                      :  $userloadpercent;
1.1083    raeburn   898:     my ($uint_dom,$remotesessions);
                    899:     if (($udom ne '') && (&domain($udom) ne '')) {
                    900:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    901:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    902:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    903:         $remotesessions = $udomdefaults{'remotesessions'};
                    904:     }
1.1123    raeburn   905:     my $spareshash = &this_host_spares($udom);
                    906:     if (ref($spareshash) eq 'HASH') {
                    907:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    908:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   909:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    910:                                              $try_server));
1.1123    raeburn   911: 	        ($spare_server, $lowest_load) =
                    912: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    913:             }
1.1083    raeburn   914:         }
1.784     albertel  915: 
1.1123    raeburn   916:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    917: 
                    918:         if (!$found_server) {
                    919:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    920: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   921:                     next unless (&spare_can_host($udom,$uint_dom,
                    922:                                                  $remotesessions,$try_server));
1.1123    raeburn   923: 	            ($spare_server, $lowest_load) =
                    924: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    925:                 }
                    926: 	    }
                    927:         }
1.784     albertel  928:     }
                    929: 
                    930:     if (!$want_server_name) {
1.968     raeburn   931:         my $protocol = 'http';
                    932:         if ($protocol{$spare_server} eq 'https') {
                    933:             $protocol = $protocol{$spare_server};
                    934:         }
1.1001    raeburn   935:         if (defined($spare_server)) {
                    936:             my $hostname = &hostname($spare_server);
1.1083    raeburn   937:             if (defined($hostname)) {
1.1001    raeburn   938: 	        $spare_server = $protocol.'://'.$hostname;
                    939:             }
                    940:         }
1.784     albertel  941:     }
                    942:     return $spare_server;
                    943: }
                    944: 
                    945: sub compare_server_load {
1.1253    raeburn   946:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    947: 
                    948:     if ($required) {
                    949:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    950:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    951:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    952:         if (($major eq '' && $minor eq '') ||
                    953:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    954:             return ($spare_server,$lowest_load);
                    955:         }
                    956:     }
1.784     albertel  957: 
                    958:     my $loadans     = &reply('load',    $try_server);
                    959:     my $userloadans = &reply('userload',$try_server);
                    960: 
                    961:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   962: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  963:     }
                    964: 
                    965:     my $load;
                    966:     if ($loadans =~ /\d/) {
                    967: 	if ($userloadans =~ /\d/) {
                    968: 	    #both are numbers, pick the bigger one
                    969: 	    $load = ($loadans > $userloadans) ? $loadans 
                    970: 		                              : $userloadans;
1.411     albertel  971: 	} else {
1.784     albertel  972: 	    $load = $loadans;
1.411     albertel  973: 	}
1.784     albertel  974:     } else {
                    975: 	$load = $userloadans;
                    976:     }
                    977: 
                    978:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    979: 	$spare_server = $try_server;
                    980: 	$lowest_load  = $load;
1.370     albertel  981:     }
1.784     albertel  982:     return ($spare_server,$lowest_load);
1.202     matthew   983: }
1.914     albertel  984: 
                    985: # --------------------------- ask offload servers if user already has a session
                    986: sub find_existing_session {
                    987:     my ($udom,$uname) = @_;
1.1123    raeburn   988:     my $spareshash = &this_host_spares($udom);
                    989:     if (ref($spareshash) eq 'HASH') {
                    990:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    991:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    992:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    993:             }
                    994:         }
                    995:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    996:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    997:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    998:             }
                    999:         }
1.914     albertel 1000:     }
                   1001:     return;
                   1002: }
                   1003: 
                   1004: # -------------------------------- ask if server already has a session for user
                   1005: sub has_user_session {
                   1006:     my ($lonid,$udom,$uname) = @_;
                   1007:     my $result = &reply(join(':','userhassession',
                   1008: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1009:     return 1 if ($result eq 'ok');
                   1010: 
                   1011:     return 0;
                   1012: }
                   1013: 
1.1076    raeburn  1014: # --------- determine least loaded server in a user's domain which allows login
                   1015: 
                   1016: sub choose_server {
1.1259    raeburn  1017:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1018:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1019:     my %servers = &get_servers($udom);
1.1076    raeburn  1020:     my $lowest_load = 30000;
1.1259    raeburn  1021:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1022:     if ($skiploadbal) {
                   1023:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1024:         unless (defined($cached)) {
                   1025:             my $cachetime = 60*60*24;
                   1026:             my %domconfig =
                   1027:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1028:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1029:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1030:                                            $cachetime);
                   1031:             }
                   1032:         }
                   1033:     }
1.1076    raeburn  1034:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1035:         if ($skiploadbal) {
                   1036:             if (ref($balancers) eq 'HASH') {
                   1037:                 next if (exists($balancers->{$lonhost}));
                   1038:             }
                   1039:         }   
1.1115    raeburn  1040:         my $loginvia;
                   1041:         if ($checkloginvia) {
                   1042:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1043:             if ($loginvia) {
                   1044:                 my ($server,$path) = split(/:/,$loginvia);
                   1045:                 ($login_host, $lowest_load) =
1.1253    raeburn  1046:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1047:                 if ($login_host eq $server) {
                   1048:                     $portal_path = $path;
1.1151    raeburn  1049:                     $isredirect = 1;
1.1116    raeburn  1050:                 }
                   1051:             } else {
                   1052:                 ($login_host, $lowest_load) =
1.1253    raeburn  1053:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1054:                 if ($login_host eq $lonhost) {
                   1055:                     $portal_path = '';
1.1151    raeburn  1056:                     $isredirect = ''; 
1.1116    raeburn  1057:                 }
                   1058:             }
                   1059:         } else {
1.1076    raeburn  1060:             ($login_host, $lowest_load) =
1.1253    raeburn  1061:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1062:         }
                   1063:     }
                   1064:     if ($login_host ne '') {
1.1116    raeburn  1065:         $hostname = &hostname($login_host);
1.1076    raeburn  1066:     }
1.1331    raeburn  1067:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1068: }
                   1069: 
1.202     matthew  1070: # --------------------------------------------- Try to change a user's password
                   1071: 
                   1072: sub changepass {
1.799     raeburn  1073:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1074:     $currentpass = &escape($currentpass);
                   1075:     $newpass     = &escape($newpass);
1.1030    raeburn  1076:     my $lonhost = $perlvar{'lonHostID'};
                   1077:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1078: 		       $server);
                   1079:     if (! $answer) {
                   1080: 	&logthis("No reply on password change request to $server ".
                   1081: 		 "by $uname in domain $udom.");
                   1082:     } elsif ($answer =~ "^ok") {
                   1083:         &logthis("$uname in $udom successfully changed their password ".
                   1084: 		 "on $server.");
                   1085:     } elsif ($answer =~ "^pwchange_failure") {
                   1086: 	&logthis("$uname in $udom was unable to change their password ".
                   1087: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1088: 		 "or pwchange");
                   1089:     } elsif ($answer =~ "^non_authorized") {
                   1090:         &logthis("$uname in $udom did not get their password correct when ".
                   1091: 		 "attempting to change it on $server.");
                   1092:     } elsif ($answer =~ "^auth_mode_error") {
                   1093:         &logthis("$uname in $udom attempted to change their password despite ".
                   1094: 		 "not being locally or internally authenticated on $server.");
                   1095:     } elsif ($answer =~ "^unknown_user") {
                   1096:         &logthis("$uname in $udom attempted to change their password ".
                   1097: 		 "on $server but were unable to because $server is not ".
                   1098: 		 "their home server.");
                   1099:     } elsif ($answer =~ "^refused") {
                   1100: 	&logthis("$server refused to change $uname in $udom password because ".
                   1101: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1102:     } elsif ($answer =~ "invalid_client") {
                   1103:         &logthis("$server refused to change $uname in $udom password because ".
                   1104:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1105:     }
                   1106:     return $answer;
1.1       albertel 1107: }
                   1108: 
1.169     harris41 1109: # ----------------------- Try to determine user's current authentication scheme
                   1110: 
                   1111: sub queryauthenticate {
                   1112:     my ($uname,$udom)=@_;
1.456     albertel 1113:     my $uhome=&homeserver($uname,$udom);
                   1114:     if (!$uhome) {
                   1115: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1116: 	return 'no_host';
                   1117:     }
                   1118:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1119:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1120: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1121:     }
1.456     albertel 1122:     return $answer;
1.169     harris41 1123: }
                   1124: 
1.1       albertel 1125: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1126: 
1.1       albertel 1127: sub authenticate {
1.1073    raeburn  1128:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1129:     $upass=&escape($upass);
                   1130:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1131:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1132:     my $newhome;
1.836     www      1133:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1134: # Maybe the machine was offline and only re-appeared again recently?
                   1135:         &reconlonc();
                   1136: # One more
1.952     raeburn  1137: 	$uhome=&homeserver($uname,$udom,1);
                   1138:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1139:             if (defined(&domain($udom,'primary'))) {
                   1140:                 $newhome=&domain($udom,'primary');
                   1141:             }
                   1142:             if ($newhome ne '') {
                   1143:                 $uhome = $newhome;
                   1144:             }
                   1145:         }
1.836     www      1146: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1147: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1148: 	    return 'no_host';
                   1149:         }
1.1       albertel 1150:     }
1.1073    raeburn  1151:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1152:     if ($answer eq 'authorized') {
1.952     raeburn  1153:         if ($newhome) {
                   1154:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1155:             return 'no_account_on_host'; 
                   1156:         } else {
                   1157:             &logthis("User $uname at $udom authorized by $uhome");
                   1158:             return $uhome;
                   1159:         }
1.471     albertel 1160:     }
                   1161:     if ($answer eq 'non_authorized') {
                   1162: 	&logthis("User $uname at $udom rejected by $uhome");
                   1163: 	return 'no_host'; 
1.9       www      1164:     }
1.471     albertel 1165:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1166:     return 'no_host';
                   1167: }
                   1168: 
1.1073    raeburn  1169: sub can_host_session {
1.1074    raeburn  1170:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1171:     my $canhost = 1;
1.1074    raeburn  1172:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1173:     if (ref($remotesessions) eq 'HASH') {
                   1174:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1175:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1176:                 $canhost = 0;
                   1177:             } else {
                   1178:                 $canhost = 1;
                   1179:             }
                   1180:         }
                   1181:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1182:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1183:                 $canhost = 1;
                   1184:             } else {
                   1185:                 $canhost = 0;
                   1186:             }
                   1187:         }
                   1188:         if ($canhost) {
                   1189:             if ($remotesessions->{'version'} ne '') {
                   1190:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1191:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1192:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1193:                         my $major = $1;
                   1194:                         my $minor = $2;
                   1195:                         if (($major < $reqmajor ) ||
                   1196:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1197:                             $canhost = 0;
                   1198:                         }
                   1199:                     } else {
                   1200:                         $canhost = 0;
                   1201:                     }
                   1202:                 }
                   1203:             }
                   1204:         }
                   1205:     }
                   1206:     if ($canhost) {
                   1207:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1208:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1209:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1210:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1211:                 if (($uint_dom ne '') && 
                   1212:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1213:                     $canhost = 0;
                   1214:                 } else {
                   1215:                     $canhost = 1;
                   1216:                 }
                   1217:             }
                   1218:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1219:                 if (($uint_dom ne '') && 
                   1220:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1221:                     $canhost = 1;
                   1222:                 } else {
                   1223:                     $canhost = 0;
                   1224:                 }
                   1225:             }
                   1226:         }
                   1227:     }
                   1228:     return $canhost;
                   1229: }
                   1230: 
1.1083    raeburn  1231: sub spare_can_host {
                   1232:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1233:     my $canhost=1;
1.1279    raeburn  1234:     my $try_server_hostname = &hostname($try_server);
                   1235:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1236:     my $serverhomedom = &host_domain($serverhomeID);
                   1237:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1238:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1239:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1240:             $canhost = 0;
                   1241:         }
                   1242:     }
                   1243:     if (($canhost) && ($uint_dom)) {
                   1244:         my @intdoms;
                   1245:         my $internet_names = &get_internet_names($try_server);
                   1246:         if (ref($internet_names) eq 'ARRAY') {
                   1247:             @intdoms = @{$internet_names};
                   1248:         }
                   1249:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1250:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1251:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1252:                                          $remotesessions,
                   1253:                                          $defdomdefaults{'hostedsessions'});
                   1254:         }
1.1083    raeburn  1255:     }
                   1256:     return $canhost;
                   1257: }
                   1258: 
1.1123    raeburn  1259: sub this_host_spares {
                   1260:     my ($dom) = @_;
1.1126    raeburn  1261:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1262:     my @hosts = &current_machine_ids();
                   1263:     foreach my $lonhost (@hosts) {
                   1264:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1265:             $dom_in_use = $dom;
                   1266:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1267:             last;
                   1268:         }
                   1269:     }
1.1126    raeburn  1270:     if ($dom_in_use ne '') {
                   1271:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1272:     }
                   1273:     if (ref($result) ne 'HASH') {
                   1274:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1275:         $dom_in_use = &host_domain($lonhost_in_use);
                   1276:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1277:         if (ref($result) ne 'HASH') {
                   1278:             $result = \%spareid;
                   1279:         }
                   1280:     }
                   1281:     return $result;
                   1282: }
                   1283: 
                   1284: sub spares_for_offload  {
                   1285:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1286:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1287:     if (defined($cached)) {
                   1288:         return $result;
                   1289:     } else {
1.1126    raeburn  1290:         my $cachetime = 60*60*24;
                   1291:         my %domconfig =
                   1292:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1293:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1294:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1295:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1296:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1297:                 }
                   1298:             }
                   1299:         }
                   1300:     }
1.1126    raeburn  1301:     return;
1.1123    raeburn  1302: }
                   1303: 
1.1129    raeburn  1304: sub get_lonbalancer_config {
                   1305:     my ($servers) = @_;
                   1306:     my ($currbalancer,$currtargets);
                   1307:     if (ref($servers) eq 'HASH') {
                   1308:         foreach my $server (keys(%{$servers})) {
                   1309:             my %what = (
                   1310:                          spareid => 1,
                   1311:                          perlvar => 1,
                   1312:                        );
                   1313:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1314:             if ($result eq 'ok') {
                   1315:                 if (ref($returnhash) eq 'HASH') {
                   1316:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1317:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1318:                             $currbalancer = $server;
                   1319:                             $currtargets = {};
                   1320:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1321:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1322:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1323:                                 }
                   1324:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1325:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1326:                                 }
                   1327:                             }
                   1328:                             last;
                   1329:                         }
                   1330:                     }
                   1331:                 }
                   1332:             }
                   1333:         }
                   1334:     }
                   1335:     return ($currbalancer,$currtargets);
                   1336: }
                   1337: 
                   1338: sub check_loadbalancing {
1.1331    raeburn  1339:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1340:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1341:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1342:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1343:     my @hosts = &current_machine_ids();
1.1129    raeburn  1344:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1345:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1346:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1347:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1348:     my $domneedscache;
1.1129    raeburn  1349:     my $cachetime = 60*60*24;
                   1350: 
                   1351:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1352:         $dom_in_use = $udom;
                   1353:         $homeintdom = 1;
                   1354:     } else {
                   1355:         $dom_in_use = $serverhomedom;
                   1356:     }
                   1357:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1358:     unless (defined($cached)) {
                   1359:         my %domconfig =
                   1360:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1361:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1362:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1363:         } else {
                   1364:             $domneedscache = $dom_in_use;
1.1129    raeburn  1365:         }
                   1366:     }
                   1367:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1368:         ($is_balancer,$currtargets,$currrules) = 
                   1369:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1370:         if ($is_balancer) {
                   1371:             if (ref($currrules) eq 'HASH') {
                   1372:                 if ($homeintdom) {
                   1373:                     if ($uname ne '') {
                   1374:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1375:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1376:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1377:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1378:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1379:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1380:                             }
                   1381:                         }
                   1382:                         if ($rule_in_effect eq '') {
                   1383:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1384:                             if ($userenv{'inststatus'} ne '') {
                   1385:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1386:                                 my ($othertitle,$usertypes,$types) =
                   1387:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1388:                                 if (ref($types) eq 'ARRAY') {
                   1389:                                     foreach my $type (@{$types}) {
                   1390:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1391:                                             if (exists($currrules->{$type})) {
                   1392:                                                 $rule_in_effect = $currrules->{$type};
                   1393:                                             }
                   1394:                                         }
                   1395:                                     }
                   1396:                                 }
                   1397:                             } else {
                   1398:                                 if (exists($currrules->{'default'})) {
                   1399:                                     $rule_in_effect = $currrules->{'default'};
                   1400:                                 }
                   1401:                             }
                   1402:                         }
                   1403:                     } else {
                   1404:                         if (exists($currrules->{'default'})) {
                   1405:                             $rule_in_effect = $currrules->{'default'};
                   1406:                         }
                   1407:                     }
                   1408:                 } else {
                   1409:                     if ($currrules->{'_LC_external'} ne '') {
                   1410:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1411:                     }
                   1412:                 }
                   1413:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1414:                                                        $uname,$udom);
                   1415:             }
                   1416:         }
                   1417:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1418:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1419:         unless (defined($cached)) {
                   1420:             my %domconfig =
                   1421:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1422:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1423:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1424:             } else {
                   1425:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1426:             }
                   1427:         }
                   1428:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1429:             ($is_balancer,$currtargets,$currrules) = 
                   1430:                 &check_balancer_result($result,@hosts);
                   1431:             if ($is_balancer) {
1.1129    raeburn  1432:                 if (ref($currrules) eq 'HASH') {
                   1433:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1434:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1435:                     }
                   1436:                 }
                   1437:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1438:                                                        $uname,$udom);
                   1439:             }
                   1440:         } else {
                   1441:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1442:                 $is_balancer = 1;
                   1443:                 $offloadto = &this_host_spares($dom_in_use);
                   1444:             }
1.1307    raeburn  1445:             unless (defined($cached)) {
                   1446:                 $domneedscache = $serverhomedom;
                   1447:             }
1.1129    raeburn  1448:         }
                   1449:     } else {
                   1450:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1451:             $is_balancer = 1;
                   1452:             $offloadto = &this_host_spares($dom_in_use);
                   1453:         }
1.1307    raeburn  1454:         unless (defined($cached)) {
                   1455:             $domneedscache = $serverhomedom;
                   1456:         }
                   1457:     }
                   1458:     if ($domneedscache) {
                   1459:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1460:     }
1.1176    raeburn  1461:     if ($is_balancer) {
                   1462:         my $lowest_load = 30000;
                   1463:         if (ref($offloadto) eq 'HASH') {
                   1464:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1465:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1466:                     ($otherserver,$lowest_load) =
                   1467:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1468:                 }
1.1129    raeburn  1469:             }
1.1176    raeburn  1470:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1471: 
1.1176    raeburn  1472:             if (!$found_server) {
                   1473:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1474:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1475:                         ($otherserver,$lowest_load) =
                   1476:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1477:                     }
                   1478:                 }
                   1479:             }
                   1480:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1481:             if (@{$offloadto} == 1) {
                   1482:                 $otherserver = $offloadto->[0];
                   1483:             } elsif (@{$offloadto} > 1) {
                   1484:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1485:                     ($otherserver,$lowest_load) =
                   1486:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1487:                 }
                   1488:             }
                   1489:         }
1.1331    raeburn  1490:         unless ($caller eq 'login') {
                   1491:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1492:                 $is_balancer = 0;
                   1493:                 if ($uname ne '' && $udom ne '') {
                   1494:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1495:                     
1.1331    raeburn  1496:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1497:                                  'user.loadbalcheck.time' => time});
                   1498:                     }
1.1176    raeburn  1499:                 }
1.1129    raeburn  1500:             }
                   1501:         }
                   1502:     }
                   1503:     return ($is_balancer,$otherserver);
                   1504: }
                   1505: 
1.1191    raeburn  1506: sub check_balancer_result {
                   1507:     my ($result,@hosts) = @_;
                   1508:     my ($is_balancer,$currtargets,$currrules);
                   1509:     if (ref($result) eq 'HASH') {
                   1510:         if ($result->{'lonhost'} ne '') {
                   1511:             my $currbalancer = $result->{'lonhost'};
                   1512:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1513:                 $is_balancer = 1;
                   1514:                 $currtargets = $result->{'targets'};
                   1515:                 $currrules = $result->{'rules'};
                   1516:             }
                   1517:         } else {
                   1518:             foreach my $key (keys(%{$result})) {
                   1519:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1520:                     (ref($result->{$key}) eq 'HASH')) {
                   1521:                     $is_balancer = 1;
                   1522:                     $currrules = $result->{$key}{'rules'};
                   1523:                     $currtargets = $result->{$key}{'targets'};
                   1524:                     last;
                   1525:                 }
                   1526:             }
                   1527:         }
                   1528:     }
                   1529:     return ($is_balancer,$currtargets,$currrules);
                   1530: }
                   1531: 
1.1129    raeburn  1532: sub get_loadbalancer_targets {
                   1533:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1534:     my $offloadto;
1.1175    raeburn  1535:     if ($rule_in_effect eq 'none') {
                   1536:         return [$perlvar{'lonHostID'}];
                   1537:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1538:         $offloadto = $currtargets;
                   1539:     } else {
                   1540:         if ($rule_in_effect eq 'homeserver') {
                   1541:             my $homeserver = &homeserver($uname,$udom);
                   1542:             if ($homeserver ne 'no_host') {
                   1543:                 $offloadto = [$homeserver];
                   1544:             }
                   1545:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1546:             my %domconfig =
                   1547:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1548:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1549:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1550:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1551:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1552:                     }
                   1553:                 }
                   1554:             } else {
1.1178    raeburn  1555:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1556:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1557:                 if (&hostname($remotebalancer) ne '') {
                   1558:                     $offloadto = [$remotebalancer];
                   1559:                 }
                   1560:             }
                   1561:         } elsif (&hostname($rule_in_effect) ne '') {
                   1562:             $offloadto = [$rule_in_effect];
                   1563:         }
                   1564:     }
                   1565:     return $offloadto;
                   1566: }
                   1567: 
1.1127    raeburn  1568: sub internet_dom_servers {
                   1569:     my ($dom) = @_;
                   1570:     my (%uniqservers,%servers);
                   1571:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1572:     my @machinedoms = &machine_domains($primaryserver);
                   1573:     foreach my $mdom (@machinedoms) {
                   1574:         my %currservers = %servers;
                   1575:         my %server = &get_servers($mdom);
                   1576:         %servers = (%currservers,%server);
                   1577:     }
                   1578:     my %by_hostname;
                   1579:     foreach my $id (keys(%servers)) {
                   1580:         push(@{$by_hostname{$servers{$id}}},$id);
                   1581:     }
                   1582:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1583:         if (@{$by_hostname{$hostname}} > 1) {
                   1584:             my $match = 0;
                   1585:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1586:                 if (&host_domain($id) eq $dom) {
                   1587:                     $uniqservers{$id} = $hostname;
                   1588:                     $match = 1;
                   1589:                 }
                   1590:             }
                   1591:             unless ($match) {
                   1592:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1593:             }
                   1594:         } else {
                   1595:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1596:         }
                   1597:     }
                   1598:     return %uniqservers;
                   1599: }
                   1600: 
1.1       albertel 1601: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1602: 
1.599     albertel 1603: my %homecache;
1.1       albertel 1604: sub homeserver {
1.230     stredwic 1605:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1606:     my $index="$uname:$udom";
1.426     albertel 1607: 
1.599     albertel 1608:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1609: 
                   1610:     my %servers = &get_servers($udom,'library');
                   1611:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1612:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1613: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1614: 
                   1615: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1616: 	if ($answer eq 'found') {
                   1617: 	    delete($badServerCache{$tryserver}); 
                   1618: 	    return $homecache{$index}=$tryserver;
                   1619: 	} elsif ($answer eq 'no_host') {
                   1620: 	    $badServerCache{$tryserver}=1;
                   1621: 	}
1.1       albertel 1622:     }    
                   1623:     return 'no_host';
1.70      www      1624: }
                   1625: 
1.1300    raeburn  1626: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1627: 
                   1628: sub idget {
1.1300    raeburn  1629:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1630:     my %returnhash=();
1.1300    raeburn  1631:     my @ids=(); 
                   1632:     if (ref($idsref) eq 'ARRAY') {
                   1633:         @ids = @{$idsref};
                   1634:     } else {
                   1635:         return %returnhash; 
                   1636:     }
                   1637:     if ($namespace eq '') {
                   1638:         $namespace = 'ids';
                   1639:     }
1.70      www      1640:     
1.841     albertel 1641:     my %servers = &get_servers($udom,'library');
                   1642:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1643: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1644: 	if ($namespace eq 'ids') {
                   1645: 	    $idlist=~tr/A-Z/a-z/;
                   1646: 	}
                   1647: 	my $reply;
                   1648: 	if ($namespace eq 'ids') {
                   1649: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1650: 	} else {
                   1651: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1652: 	}
1.841     albertel 1653: 	my @answer=();
                   1654: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1655: 	    @answer=split(/\&/,$reply);
                   1656: 	}                    ;
                   1657: 	my $i;
                   1658: 	for ($i=0;$i<=$#ids;$i++) {
                   1659: 	    if ($answer[$i]) {
1.1299    raeburn  1660: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1661: 	    }
1.841     albertel 1662: 	}
1.1300    raeburn  1663:     }
1.70      www      1664:     return %returnhash;
                   1665: }
                   1666: 
                   1667: # ------------------------------------- Find the IDs behind a list of usernames
                   1668: 
                   1669: sub idrget {
                   1670:     my ($udom,@unames)=@_;
                   1671:     my %returnhash=();
1.800     albertel 1672:     foreach my $uname (@unames) {
                   1673:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1674:     }
1.70      www      1675:     return %returnhash;
                   1676: }
                   1677: 
1.1300    raeburn  1678: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1679: 
                   1680: sub idput {
1.1300    raeburn  1681:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1682:     my %servers=();
1.1300    raeburn  1683:     my %ids=();
                   1684:     my %byid = ();
                   1685:     if (ref($idsref) eq 'HASH') {
                   1686:         %ids=%{$idsref};
                   1687:     }
                   1688:     if ($namespace eq '') {
                   1689:         $namespace = 'ids'; 
                   1690:     }
1.800     albertel 1691:     foreach my $uname (keys(%ids)) {
                   1692: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1693:         if ($uhom eq '') {
                   1694:             $uhom=&homeserver($uname,$udom);
                   1695:         }
1.70      www      1696:         if ($uhom ne 'no_host') {
1.800     albertel 1697:             my $esc_unam=&escape($uname);
1.1300    raeburn  1698:             if ($namespace eq 'ids') {
                   1699:                 my $id=&escape($ids{$uname});
                   1700:                 $id=~tr/A-Z/a-z/;
                   1701:                 my $esc_unam=&escape($uname);
                   1702:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1703:             } else {
1.1300    raeburn  1704:                 my @currids = split(/,/,$ids{$uname});
                   1705:                 foreach my $id (@currids) {
                   1706:                     $byid{$uhom}{$id} .= $uname.',';
                   1707:                 }
                   1708:             }
                   1709:         }
                   1710:     }
                   1711:     if ($namespace eq 'clickers') {
                   1712:         foreach my $server (keys(%byid)) {
                   1713:             if (ref($byid{$server}) eq 'HASH') {
                   1714:                 foreach my $id (keys(%{$byid{$server}})) {
                   1715:                     $byid{$server} =~ s/,$//;
                   1716:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1717:                 }
1.70      www      1718:             }
                   1719:         }
1.191     harris41 1720:     }
1.800     albertel 1721:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1722:         $servers{$server} =~ s/\&$//;
                   1723:         if ($namespace eq 'ids') {     
                   1724:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1725:         } else {
                   1726:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1727:         }
1.191     harris41 1728:     }
1.344     www      1729: }
                   1730: 
1.1300    raeburn  1731: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1732: 
                   1733: sub iddel {
1.1300    raeburn  1734:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1735:     my %result=();
1.1300    raeburn  1736:     my %ids=();
                   1737:     my %byid = ();
                   1738:     if (ref($idshashref) eq 'HASH') {
                   1739:         %ids=%{$idshashref};
                   1740:     } else {
1.1231    raeburn  1741:         return %result;
                   1742:     }
1.1300    raeburn  1743:     if ($namespace eq '') {
                   1744:         $namespace = 'ids';
                   1745:     }
1.1231    raeburn  1746:     my %servers=();
1.1300    raeburn  1747:     while (my ($id,$unamestr) = each(%ids)) {
                   1748:         if ($namespace eq 'ids') {
                   1749:             my $uhom = $uhome;
                   1750:             if ($uhom eq '') { 
                   1751:                 $uhom=&homeserver($unamestr,$udom);
                   1752:             }
                   1753:             if ($uhom ne 'no_host') {
                   1754:                 $servers{$uhom}.='&'.&escape($id);
                   1755:             }
                   1756:          } else {
                   1757:             my @curritems = split(/,/,$ids{$id});
                   1758:             foreach my $uname (@curritems) {
                   1759:                 my $uhom = $uhome;
                   1760:                 if ($uhom eq '') {
                   1761:                     $uhom=&homeserver($uname,$udom);
                   1762:                 }
                   1763:                 if ($uhom ne 'no_host') { 
                   1764:                     $byid{$uhom}{$id} .= $uname.',';
                   1765:                 }
                   1766:             }
1.1231    raeburn  1767:         }
1.1300    raeburn  1768:     }
                   1769:     if ($namespace eq 'clickers') {
                   1770:         foreach my $server (keys(%byid)) {
                   1771:             if (ref($byid{$server}) eq 'HASH') {
                   1772:                 foreach my $id (keys(%{$byid{$server}})) {
                   1773:                     $byid{$server}{$id} =~ s/,$//;
                   1774:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1775:                 }
1.1231    raeburn  1776:             }
                   1777:         }
                   1778:     }
                   1779:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1780:         $servers{$server} =~ s/\&$//;
                   1781:         if ($namespace eq 'ids') {
                   1782:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1783:         } elsif ($namespace eq 'clickers') {
                   1784:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1785:         }
1.1231    raeburn  1786:     }
                   1787:     return %result;
                   1788: }
                   1789: 
1.1300    raeburn  1790: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1791: 
                   1792: sub updateclickers {
                   1793:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1794:     my %clickers;
                   1795:     if (ref($idshashref) eq 'HASH') {
                   1796:         %clickers=%{$idshashref};
                   1797:     } else {
                   1798:         return;
                   1799:     }
                   1800:     my $items='';
                   1801:     foreach my $item (keys(%clickers)) {
                   1802:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1803:     }
                   1804:     $items=~s/\&$//;
                   1805:     my $request = "updateclickers:$udom:$action:$items";
                   1806:     if ($critical) {
                   1807:         return &critical($request,$uhome);
                   1808:     } else {
                   1809:         return &reply($request,$uhome);
                   1810:     }
                   1811: }
                   1812: 
1.1023    raeburn  1813: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1814: sub dump_dom {
1.1165    droeschl 1815:     my ($namespace, $udom, $regexp) = @_;
                   1816: 
                   1817:     $udom ||= $env{'user.domain'};
                   1818: 
                   1819:     return () unless $udom;
                   1820: 
                   1821:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1822: }
                   1823: 
1.1023    raeburn  1824: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1825: 
                   1826: sub get_dom {
1.860     raeburn  1827:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1828:     return if ($udom eq 'public');
1.806     raeburn  1829:     my $items='';
                   1830:     foreach my $item (@$storearr) {
                   1831:         $items.=&escape($item).'&';
                   1832:     }
                   1833:     $items=~s/\&$//;
1.860     raeburn  1834:     if (!$udom) {
                   1835:         $udom=$env{'user.domain'};
1.1267    raeburn  1836:         return if ($udom eq 'public');
1.860     raeburn  1837:         if (defined(&domain($udom,'primary'))) {
                   1838:             $uhome=&domain($udom,'primary');
                   1839:         } else {
1.874     albertel 1840:             undef($uhome);
1.860     raeburn  1841:         }
                   1842:     } else {
                   1843:         if (!$uhome) {
                   1844:             if (defined(&domain($udom,'primary'))) {
                   1845:                 $uhome=&domain($udom,'primary');
                   1846:             }
                   1847:         }
                   1848:     }
                   1849:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  1850:         my $rep;
                   1851:         if ($namespace =~ /^enc/) {
                   1852:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1853:         } else {
                   1854:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1855:         }
1.866     raeburn  1856:         my %returnhash;
1.875     albertel 1857:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1858:             return %returnhash;
                   1859:         }
1.806     raeburn  1860:         my @pairs=split(/\&/,$rep);
                   1861:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1862:             return @pairs;
                   1863:         }
                   1864:         my $i=0;
                   1865:         foreach my $item (@$storearr) {
                   1866:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1867:             $i++;
                   1868:         }
                   1869:         return %returnhash;
                   1870:     } else {
1.880     banghart 1871:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1872:     }
                   1873: }
                   1874: 
                   1875: # -------------------------------------------- put items in domain db files 
                   1876: 
                   1877: sub put_dom {
1.860     raeburn  1878:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1879:     if (!$udom) {
                   1880:         $udom=$env{'user.domain'};
                   1881:         if (defined(&domain($udom,'primary'))) {
                   1882:             $uhome=&domain($udom,'primary');
                   1883:         } else {
1.874     albertel 1884:             undef($uhome);
1.860     raeburn  1885:         }
                   1886:     } else {
                   1887:         if (!$uhome) {
                   1888:             if (defined(&domain($udom,'primary'))) {
                   1889:                 $uhome=&domain($udom,'primary');
                   1890:             }
                   1891:         }
                   1892:     } 
                   1893:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1894:         my $items='';
                   1895:         foreach my $item (keys(%$storehash)) {
                   1896:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1897:         }
                   1898:         $items=~s/\&$//;
1.1344    raeburn  1899:         if ($namespace =~ /^enc/) {
                   1900:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   1901:         } else {
                   1902:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1903:         }
1.806     raeburn  1904:     } else {
1.860     raeburn  1905:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1906:     }
                   1907: }
                   1908: 
1.1023    raeburn  1909: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1910: sub newput_dom {
1.1023    raeburn  1911:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1912:     my $result;
                   1913:     if (!$udom) {
                   1914:         $udom=$env{'user.domain'};
                   1915:     }
1.1023    raeburn  1916:     if ($udom) {
                   1917:         my $uname = &get_domainconfiguser($udom);
                   1918:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1919:     }
                   1920:     return $result;
                   1921: }
                   1922: 
1.1023    raeburn  1923: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1924: sub del_dom {
1.1023    raeburn  1925:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1926:     if (ref($storearr) eq 'ARRAY') {
                   1927:         if (!$udom) {
                   1928:             $udom=$env{'user.domain'};
                   1929:         }
1.1023    raeburn  1930:         if ($udom) {
                   1931:             my $uname = &get_domainconfiguser($udom); 
                   1932:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1933:         }
                   1934:     }
                   1935: }
                   1936: 
1.1023    raeburn  1937: # ----------------------------------construct domainconfig user for a domain 
                   1938: sub get_domainconfiguser {
                   1939:     my ($udom) = @_;
                   1940:     return $udom.'-domainconfig';
                   1941: }
                   1942: 
1.837     raeburn  1943: sub retrieve_inst_usertypes {
                   1944:     my ($udom) = @_;
                   1945:     my (%returnhash,@order);
1.989     raeburn  1946:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1947:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1948:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  1949:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  1950:     } else {
                   1951:         if (defined(&domain($udom,'primary'))) {
                   1952:             my $uhome=&domain($udom,'primary');
                   1953:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1954:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  1955:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  1956:                 return (\%returnhash,\@order);
                   1957:             }
                   1958:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1959:             my @pairs=split(/\&/,$hashitems);
                   1960:             foreach my $item (@pairs) {
                   1961:                 my ($key,$value)=split(/=/,$item,2);
                   1962:                 $key = &unescape($key);
                   1963:                 next if ($key =~ /^error: 2 /);
                   1964:                 $returnhash{$key}=&thaw_unescape($value);
                   1965:             }
                   1966:             my @esc_order = split(/\&/,$orderitems);
                   1967:             foreach my $item (@esc_order) {
                   1968:                 push(@order,&unescape($item));
                   1969:             }
                   1970:         } else {
1.1256    raeburn  1971:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  1972:         }
1.1256    raeburn  1973:         return (\%returnhash,\@order);
1.837     raeburn  1974:     }
                   1975: }
                   1976: 
1.868     raeburn  1977: sub is_domainimage {
                   1978:     my ($url) = @_;
1.1306    raeburn  1979:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  1980:         if (&domain($1) ne '') {
                   1981:             return '1';
                   1982:         }
                   1983:     }
                   1984:     return;
                   1985: }
                   1986: 
1.899     raeburn  1987: sub inst_directory_query {
                   1988:     my ($srch) = @_;
                   1989:     my $udom = $srch->{'srchdomain'};
                   1990:     my %results;
                   1991:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1992:     my $outcome;
1.899     raeburn  1993:     if ($homeserver ne '') {
1.904     albertel 1994: 	my $queryid=&reply("querysend:instdirsearch:".
                   1995: 			   &escape($srch->{'srchby'}).':'.
                   1996: 			   &escape($srch->{'srchterm'}).':'.
                   1997: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1998: 	my $host=&hostname($homeserver);
                   1999: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2000: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2001: 	    return;
                   2002: 	}
                   2003: 	my $response = &get_query_reply($queryid);
                   2004: 	my $maxtries = 5;
                   2005: 	my $tries = 1;
                   2006: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2007: 	    $response = &get_query_reply($queryid);
                   2008: 	    $tries ++;
                   2009: 	}
                   2010: 
                   2011:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2012:             if ($response eq 'unavailable') {
                   2013:                 $outcome = $response;
                   2014:             } else {
                   2015:                 $outcome = 'ok';
                   2016:                 my @matches = split(/\n/,$response);
                   2017:                 foreach my $match (@matches) {
                   2018:                     my ($key,$value) = split(/=/,$match);
                   2019:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2020:                 }
1.899     raeburn  2021:             }
                   2022:         }
                   2023:     }
1.909     raeburn  2024:     return ($outcome,%results);
1.899     raeburn  2025: }
                   2026: 
                   2027: sub usersearch {
                   2028:     my ($srch) = @_;
                   2029:     my $dom = $srch->{'srchdomain'};
                   2030:     my %results;
                   2031:     my %libserv = &all_library();
                   2032:     my $query = 'usersearch';
                   2033:     foreach my $tryserver (keys(%libserv)) {
                   2034:         if (&host_domain($tryserver) eq $dom) {
                   2035:             my $host=&hostname($tryserver);
                   2036:             my $queryid=
1.911     raeburn  2037:                 &reply("querysend:".&escape($query).':'.
                   2038:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2039:                        &escape($srch->{'srchtype'}).':'.
                   2040:                        &escape($srch->{'srchterm'}),$tryserver);
                   2041:             if ($queryid !~/^\Q$host\E\_/) {
                   2042:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2043:                 next;
1.899     raeburn  2044:             }
                   2045:             my $reply = &get_query_reply($queryid);
                   2046:             my $maxtries = 1;
                   2047:             my $tries = 1;
                   2048:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2049:                 $reply = &get_query_reply($queryid);
                   2050:                 $tries ++;
                   2051:             }
                   2052:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2053:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2054:             } else {
1.911     raeburn  2055:                 my @matches;
                   2056:                 if ($reply =~ /\n/) {
                   2057:                     @matches = split(/\n/,$reply);
                   2058:                 } else {
                   2059:                     @matches = split(/\&/,$reply);
                   2060:                 }
1.899     raeburn  2061:                 foreach my $match (@matches) {
                   2062:                     my ($uname,$udom,%userhash);
1.911     raeburn  2063:                     foreach my $entry (split(/:/,$match)) {
                   2064:                         my ($key,$value) =
                   2065:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2066:                         $userhash{$key} = $value;
                   2067:                         if ($key eq 'username') {
                   2068:                             $uname = $value;
                   2069:                         } elsif ($key eq 'domain') {
                   2070:                             $udom = $value;
1.911     raeburn  2071:                         }
1.899     raeburn  2072:                     }
                   2073:                     $results{$uname.':'.$udom} = \%userhash;
                   2074:                 }
                   2075:             }
                   2076:         }
                   2077:     }
                   2078:     return %results;
                   2079: }
                   2080: 
1.912     raeburn  2081: sub get_instuser {
                   2082:     my ($udom,$uname,$id) = @_;
                   2083:     my $homeserver = &domain($udom,'primary');
                   2084:     my ($outcome,%results);
                   2085:     if ($homeserver ne '') {
                   2086:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2087:                            &escape($id).':'.&escape($udom),$homeserver);
                   2088:         my $host=&hostname($homeserver);
                   2089:         if ($queryid !~/^\Q$host\E\_/) {
                   2090:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2091:             return;
                   2092:         }
                   2093:         my $response = &get_query_reply($queryid);
                   2094:         my $maxtries = 5;
                   2095:         my $tries = 1;
                   2096:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2097:             $response = &get_query_reply($queryid);
                   2098:             $tries ++;
                   2099:         }
                   2100:         if (!&error($response) && $response ne 'refused') {
                   2101:             if ($response eq 'unavailable') {
                   2102:                 $outcome = $response;
                   2103:             } else {
                   2104:                 $outcome = 'ok';
                   2105:                 my @matches = split(/\n/,$response);
                   2106:                 foreach my $match (@matches) {
                   2107:                     my ($key,$value) = split(/=/,$match);
                   2108:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2109:                 }
                   2110:             }
                   2111:         }
                   2112:     }
                   2113:     my %userinfo;
                   2114:     if (ref($results{$uname}) eq 'HASH') {
                   2115:         %userinfo = %{$results{$uname}};
                   2116:     } 
                   2117:     return ($outcome,%userinfo);
                   2118: }
                   2119: 
1.1290    raeburn  2120: sub get_multiple_instusers {
                   2121:     my ($udom,$users,$caller) = @_;
                   2122:     my ($outcome,$results);
                   2123:     if (ref($users) eq 'HASH') {
                   2124:         my $count = keys(%{$users}); 
                   2125:         my $requested = &freeze_escape($users);
                   2126:         my $homeserver = &domain($udom,'primary');
                   2127:         if ($homeserver ne '') {
                   2128:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2129:             my $host=&hostname($homeserver);
                   2130:             if ($queryid !~/^\Q$host\E\_/) {
                   2131:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2132:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2133:                 return ($outcome,$results);
                   2134:             }
                   2135:             my $response = &get_query_reply($queryid);
                   2136:             my $maxtries = 5;
                   2137:             if ($count > 100) {
                   2138:                 $maxtries = 1+int($count/20);
                   2139:             }
                   2140:             my $tries = 1;
                   2141:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2142:                 $response = &get_query_reply($queryid);
                   2143:                 $tries ++;
                   2144:             }
                   2145:             if ($response eq '') {
                   2146:                 $results = {};
                   2147:                 foreach my $key (keys(%{$users})) {
                   2148:                     my ($uname,$id);
                   2149:                     if ($caller eq 'id') {
                   2150:                         $id = $key;
                   2151:                     } else {
                   2152:                         $uname = $key;
                   2153:                     }
                   2154:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2155:                     $outcome = $resp;
1.1290    raeburn  2156:                     if ($resp eq 'ok') {
                   2157:                         %{$results} = (%{$results}, %info);
                   2158:                     } else {
                   2159:                         last;
                   2160:                     }
                   2161:                 }
                   2162:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2163:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2164:                     $outcome = $response;
                   2165:                 } else {
1.1291    raeburn  2166:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2167:                     if ($outcome eq 'ok') {
                   2168:                         $results = &thaw_unescape($userdata); 
                   2169:                     }
                   2170:                 }
                   2171:             }
                   2172:         }
                   2173:     }
                   2174:     return ($outcome,$results);
                   2175: }
                   2176: 
1.912     raeburn  2177: sub inst_rulecheck {
1.923     raeburn  2178:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2179:     my %returnhash;
                   2180:     if ($udom ne '') {
                   2181:         if (ref($rules) eq 'ARRAY') {
                   2182:             @{$rules} = map {&escape($_);} (@{$rules});
                   2183:             my $rulestr = join(':',@{$rules});
                   2184:             my $homeserver=&domain($udom,'primary');
                   2185:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2186:                 my $response;
                   2187:                 if ($item eq 'username') {                
                   2188:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2189:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2190:                                               $homeserver));
1.923     raeburn  2191:                 } elsif ($item eq 'id') {
                   2192:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2193:                                               ':'.&escape($id).':'.$rulestr,
                   2194:                                               $homeserver));
1.945     raeburn  2195:                 } elsif ($item eq 'selfcreate') {
                   2196:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2197:                                                &escape($udom).':'.&escape($uname).
                   2198:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2199:                 }
1.912     raeburn  2200:                 if ($response ne 'refused') {
                   2201:                     my @pairs=split(/\&/,$response);
                   2202:                     foreach my $item (@pairs) {
                   2203:                         my ($key,$value)=split(/=/,$item,2);
                   2204:                         $key = &unescape($key);
                   2205:                         next if ($key =~ /^error: 2 /);
                   2206:                         $returnhash{$key}=&thaw_unescape($value);
                   2207:                     }
                   2208:                 }
                   2209:             }
                   2210:         }
                   2211:     }
                   2212:     return %returnhash;
                   2213: }
                   2214: 
                   2215: sub inst_userrules {
1.923     raeburn  2216:     my ($udom,$check) = @_;
1.912     raeburn  2217:     my (%ruleshash,@ruleorder);
                   2218:     if ($udom ne '') {
                   2219:         my $homeserver=&domain($udom,'primary');
                   2220:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2221:             my $response;
                   2222:             if ($check eq 'id') {
                   2223:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2224:                                  $homeserver);
1.943     raeburn  2225:             } elsif ($check eq 'email') {
                   2226:                 $response=&reply('instemailrules:'.&escape($udom),
                   2227:                                  $homeserver);
1.923     raeburn  2228:             } else {
                   2229:                 $response=&reply('instuserrules:'.&escape($udom),
                   2230:                                  $homeserver);
                   2231:             }
1.912     raeburn  2232:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2233:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2234:                 ($response ne 'no_such_host')) {
                   2235:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2236:                 my @pairs=split(/\&/,$hashitems);
                   2237:                 foreach my $item (@pairs) {
                   2238:                     my ($key,$value)=split(/=/,$item,2);
                   2239:                     $key = &unescape($key);
                   2240:                     next if ($key =~ /^error: 2 /);
                   2241:                     $ruleshash{$key}=&thaw_unescape($value);
                   2242:                 }
                   2243:                 my @esc_order = split(/\&/,$orderitems);
                   2244:                 foreach my $item (@esc_order) {
                   2245:                     push(@ruleorder,&unescape($item));
                   2246:                 }
                   2247:             }
                   2248:         }
                   2249:     }
                   2250:     return (\%ruleshash,\@ruleorder);
                   2251: }
                   2252: 
1.976     raeburn  2253: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2254: 
                   2255: sub get_domain_defaults {
1.1240    raeburn  2256:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2257:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2258:     my $cachetime = 60*60*24;
1.1240    raeburn  2259:     unless ($ignore_cache) {
                   2260:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2261:         if (defined($cached)) {
                   2262:             if (ref($result) eq 'HASH') {
                   2263:                 return %{$result};
                   2264:             }
1.943     raeburn  2265:         }
                   2266:     }
                   2267:     my %domdefaults;
                   2268:     my %domconfig =
1.989     raeburn  2269:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2270:                                   'requestcourses','inststatus',
1.1183    raeburn  2271:                                   'coursedefaults','usersessions',
1.1258    raeburn  2272:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2273:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2274:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2275:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2276:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2277:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2278:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2279:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2280:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2281:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2282:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2283:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2284:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2285:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2286:     } else {
                   2287:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2288:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2289:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2290:     }
1.976     raeburn  2291:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2292:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2293:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2294:         } else {
                   2295:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2296:         }
1.1177    raeburn  2297:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2298:         foreach my $item (@usertools) {
                   2299:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2300:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2301:             }
                   2302:         }
1.1229    raeburn  2303:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2304:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2305:         }
1.976     raeburn  2306:     }
1.985     raeburn  2307:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2308:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2309:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2310:         }
                   2311:     }
1.1183    raeburn  2312:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2313:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2314:     }
1.989     raeburn  2315:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2316:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2317:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2318:         }
                   2319:     }
1.1047    raeburn  2320:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2321:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2322:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2323:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2324:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2325:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2326:         }
1.1254    raeburn  2327:         foreach my $type (@coursetypes) {
                   2328:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2329:                 unless ($type eq 'community') {
                   2330:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2331:                 }
                   2332:             }
                   2333:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2334:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2335:             }
1.1277    raeburn  2336:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2337:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2338:                     $domdefaults{$type.'postsubtimeout'} = 
                   2339:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2340:                 }
                   2341:             }
1.1230    raeburn  2342:         }
1.1286    raeburn  2343:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2344:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2345:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2346:                 if (@clonecodes) {
                   2347:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2348:                 }
                   2349:             }
                   2350:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2351:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2352:         }
1.1047    raeburn  2353:     }
1.1073    raeburn  2354:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2355:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2356:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2357:         }
                   2358:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2359:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2360:         }
1.1279    raeburn  2361:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2362:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2363:         }
1.1073    raeburn  2364:     }
1.1254    raeburn  2365:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2366:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2367:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2368:                             'approval','limit');
                   2369:             foreach my $type (@coursetypes) {
                   2370:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2371:                     my @mgrdc = ();
                   2372:                     foreach my $item (@settings) {
                   2373:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2374:                             push(@mgrdc,$item);
                   2375:                         }
                   2376:                     }
                   2377:                     if (@mgrdc) {
                   2378:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2379:                     }
                   2380:                 }
                   2381:             }
                   2382:         }
                   2383:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2384:             foreach my $type (@coursetypes) {
                   2385:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2386:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2387:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2388:                     }
                   2389:                 }
                   2390:             }
                   2391:         }
                   2392:     }
1.1258    raeburn  2393:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2394:         $domdefaults{'catauth'} = 'std';
                   2395:         $domdefaults{'catunauth'} = 'std';
                   2396:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2397:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2398:         }
                   2399:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2400:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2401:         }
                   2402:     }
1.1315    raeburn  2403:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2404:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2405:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2406:         }
1.1338    raeburn  2407:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2408:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2409:         }
                   2410:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2411:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2412:         }
                   2413:     }
1.1320    raeburn  2414:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2415:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2416:         foreach my $prefix (@prefixes) {
                   2417:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2418:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2419:             }
                   2420:         }
                   2421:     }
1.1314    raeburn  2422:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2423:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2424:     }
1.1332    raeburn  2425:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2426:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2427:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2428:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2429:         }
                   2430:     }
1.1219    raeburn  2431:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2432:     return %domdefaults;
                   2433: }
                   2434: 
1.1311    raeburn  2435: sub course_portal_url {
                   2436:     my ($cnum,$cdom) = @_;
                   2437:     my $chome = &homeserver($cnum,$cdom);
                   2438:     my $hostname = &hostname($chome);
                   2439:     my $protocol = $protocol{$chome};
                   2440:     $protocol = 'http' if ($protocol ne 'https');
                   2441:     my %domdefaults = &get_domain_defaults($cdom);
                   2442:     my $firsturl;
                   2443:     if ($domdefaults{'portal_def'}) {
                   2444:         $firsturl = $domdefaults{'portal_def'};
                   2445:     } else {
                   2446:         $firsturl = $protocol.'://'.$hostname;
                   2447:     }
                   2448:     return $firsturl;
                   2449: }
                   2450: 
1.344     www      2451: # --------------------------------------------------- Assign a key to a student
                   2452: 
                   2453: sub assign_access_key {
1.364     www      2454: #
                   2455: # a valid key looks like uname:udom#comments
                   2456: # comments are being appended
                   2457: #
1.498     www      2458:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2459:     $kdom=
1.620     albertel 2460:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2461:     $knum=
1.620     albertel 2462:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2463:     $cdom=
1.620     albertel 2464:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2465:     $cnum=
1.620     albertel 2466:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2467:     $udom=$env{'user.name'} unless (defined($udom));
                   2468:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2469:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2470:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2471:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2472:                                                   # assigned to this person
                   2473:                                                   # - this should not happen,
1.345     www      2474:                                                   # unless something went wrong
                   2475:                                                   # the first time around
                   2476: # ready to assign
1.364     www      2477:         $logentry=$1.'; '.$logentry;
1.496     www      2478:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2479:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2480: # key now belongs to user
1.346     www      2481: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2482:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2483:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2484:                 return 'ok';
                   2485:             } else {
                   2486:                 return 
                   2487:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2488: 	    }
                   2489:         } else {
                   2490:             return 'error: Could not assign key, try again later.';
                   2491:         }
1.364     www      2492:     } elsif (!$existing{$ckey}) {
1.345     www      2493: # the key does not exist
                   2494: 	return 'error: The key does not exist';
                   2495:     } else {
                   2496: # the key is somebody else's
                   2497: 	return 'error: The key is already in use';
                   2498:     }
1.344     www      2499: }
                   2500: 
1.364     www      2501: # ------------------------------------------ put an additional comment on a key
                   2502: 
                   2503: sub comment_access_key {
                   2504: #
                   2505: # a valid key looks like uname:udom#comments
                   2506: # comments are being appended
                   2507: #
                   2508:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2509:     $cdom=
1.620     albertel 2510:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2511:     $cnum=
1.620     albertel 2512:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2513:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2514:     if ($existing{$ckey}) {
                   2515:         $existing{$ckey}.='; '.$logentry;
                   2516: # ready to assign
1.367     www      2517:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2518:                                                  $cdom,$cnum) eq 'ok') {
                   2519: 	    return 'ok';
                   2520:         } else {
                   2521: 	    return 'error: Count not store comment.';
                   2522:         }
                   2523:     } else {
                   2524: # the key does not exist
                   2525: 	return 'error: The key does not exist';
                   2526:     }
                   2527: }
                   2528: 
1.344     www      2529: # ------------------------------------------------------ Generate a set of keys
                   2530: 
                   2531: sub generate_access_keys {
1.364     www      2532:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2533:     $cdom=
1.620     albertel 2534:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2535:     $cnum=
1.620     albertel 2536:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2537:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2538:     unless (($cdom) && ($cnum)) { return 0; }
                   2539:     if ($number>10000) { return 0; }
                   2540:     sleep(2); # make sure don't get same seed twice
                   2541:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2542:     my $total=0;
                   2543:     for (my $i=1;$i<=$number;$i++) {
                   2544:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2545:                   sprintf("%lx",int(100000*rand)).'-'.
                   2546:                   sprintf("%lx",int(100000*rand));
                   2547:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2548:        $newkey=~s/0/h/g; # and also 0 and O
                   2549:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2550:        if ($existing{$newkey}) {
                   2551:            $i--;
                   2552:        } else {
1.364     www      2553: 	  if (&put('accesskeys',
                   2554:               { $newkey => '# generated '.localtime().
1.620     albertel 2555:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2556:                            '; '.$logentry },
                   2557: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2558:               $total++;
                   2559: 	  }
                   2560:        }
                   2561:     }
1.620     albertel 2562:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2563:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2564:     return $total;
                   2565: }
                   2566: 
                   2567: # ------------------------------------------------------- Validate an accesskey
                   2568: 
                   2569: sub validate_access_key {
                   2570:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2571:     $cdom=
1.620     albertel 2572:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2573:     $cnum=
1.620     albertel 2574:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2575:     $udom=$env{'user.domain'} unless (defined($udom));
                   2576:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2577:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2578:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2579: }
                   2580: 
                   2581: # ------------------------------------- Find the section of student in a course
1.652     albertel 2582: sub devalidate_getsection_cache {
                   2583:     my ($udom,$unam,$courseid)=@_;
                   2584:     my $hashid="$udom:$unam:$courseid";
                   2585:     &devalidate_cache_new('getsection',$hashid);
                   2586: }
1.298     matthew  2587: 
1.815     albertel 2588: sub courseid_to_courseurl {
                   2589:     my ($courseid) = @_;
                   2590:     #already url style courseid
                   2591:     return $courseid if ($courseid =~ m{^/});
                   2592: 
                   2593:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2594: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2595: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2596: 	return "/$cdom/$cnum";
                   2597:     }
                   2598: 
                   2599:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2600:     if (exists($courseinfo{'num'})) {
                   2601: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2602:     }
                   2603: 
                   2604:     return undef;
                   2605: }
                   2606: 
1.298     matthew  2607: sub getsection {
                   2608:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2609:     my $cachetime=1800;
1.551     albertel 2610: 
                   2611:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2612:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2613:     if (defined($cached)) { return $result; }
                   2614: 
1.298     matthew  2615:     my %Pending; 
                   2616:     my %Expired;
                   2617:     #
                   2618:     # Each role can either have not started yet (pending), be active, 
                   2619:     #    or have expired.
                   2620:     #
                   2621:     # If there is an active role, we are done.
                   2622:     #
                   2623:     # If there is more than one role which has not started yet, 
                   2624:     #     choose the one which will start sooner
                   2625:     # If there is one role which has not started yet, return it.
                   2626:     #
                   2627:     # If there is more than one expired role, choose the one which ended last.
                   2628:     # If there is a role which has expired, return it.
                   2629:     #
1.815     albertel 2630:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2631:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2632:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2633:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2634:         my $section=$1;
                   2635:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2636:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2637:         my $now=time;
1.548     albertel 2638:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2639:             $Expired{$end}=$section;
                   2640:             next;
                   2641:         }
1.548     albertel 2642:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2643:             $Pending{$start}=$section;
                   2644:             next;
                   2645:         }
1.599     albertel 2646:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2647:     }
                   2648:     #
                   2649:     # Presumedly there will be few matching roles from the above
                   2650:     # loop and the sorting time will be negligible.
                   2651:     if (scalar(keys(%Pending))) {
                   2652:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2653:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2654:     } 
                   2655:     if (scalar(keys(%Expired))) {
                   2656:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2657:         my $time = pop(@sorted);
1.599     albertel 2658:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2659:     }
1.599     albertel 2660:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2661: }
1.70      www      2662: 
1.599     albertel 2663: sub save_cache {
                   2664:     &purge_remembered();
1.722     albertel 2665:     #&Apache::loncommon::validate_page();
1.620     albertel 2666:     undef(%env);
1.780     albertel 2667:     undef($env_loaded);
1.599     albertel 2668: }
1.452     albertel 2669: 
1.599     albertel 2670: my $to_remember=-1;
                   2671: my %remembered;
                   2672: my %accessed;
                   2673: my $kicks=0;
                   2674: my $hits=0;
1.849     albertel 2675: sub make_key {
                   2676:     my ($name,$id) = @_;
1.872     albertel 2677:     if (length($id) > 65 
                   2678: 	&& length(&escape($id)) > 200) {
                   2679: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2680:     }
1.849     albertel 2681:     return &escape($name.':'.$id);
                   2682: }
                   2683: 
1.599     albertel 2684: sub devalidate_cache_new {
                   2685:     my ($name,$id,$debug) = @_;
                   2686:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2687:     my $remembered_id=$name.':'.$id;
1.849     albertel 2688:     $id=&make_key($name,$id);
1.599     albertel 2689:     $memcache->delete($id);
1.1319    damieng  2690:     delete($remembered{$remembered_id});
                   2691:     delete($accessed{$remembered_id});
1.599     albertel 2692: }
                   2693: 
                   2694: sub is_cached_new {
                   2695:     my ($name,$id,$debug) = @_;
1.1319    damieng  2696:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2697:     if (exists($remembered{$remembered_id})) {
                   2698: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2699: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2700: 	$hits++;
1.1319    damieng  2701: 	return ($remembered{$remembered_id},1);
1.599     albertel 2702:     }
1.1319    damieng  2703:     $id=&make_key($name,$id);
1.599     albertel 2704:     my $value = $memcache->get($id);
                   2705:     if (!(defined($value))) {
                   2706: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2707: 	return (undef,undef);
1.416     albertel 2708:     }
1.599     albertel 2709:     if ($value eq '__undef__') {
                   2710: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2711: 	$value=undef;
                   2712:     }
1.1319    damieng  2713:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2714:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2715:     return ($value,1);
                   2716: }
                   2717: 
                   2718: sub do_cache_new {
                   2719:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2720:     my $remembered_id=$name.':'.$id;
1.849     albertel 2721:     $id=&make_key($name,$id);
1.599     albertel 2722:     my $setvalue=$value;
                   2723:     if (!defined($setvalue)) {
                   2724: 	$setvalue='__undef__';
                   2725:     }
1.623     albertel 2726:     if (!defined($time) ) {
                   2727: 	$time=600;
                   2728:     }
1.599     albertel 2729:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2730:     my $result = $memcache->set($id,$setvalue,$time);
                   2731:     if (! $result) {
1.872     albertel 2732: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2733: 	$memcache->disconnect_all();
1.872     albertel 2734:     }
1.600     albertel 2735:     # need to make a copy of $value
1.1319    damieng  2736:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2737:     return $value;
                   2738: }
                   2739: 
                   2740: sub make_room {
1.1319    damieng  2741:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2742: 
1.1319    damieng  2743:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2744:                                     : $value;
1.599     albertel 2745:     if ($to_remember<0) { return; }
1.1319    damieng  2746:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2747:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2748:     my $to_kick;
                   2749:     my $max_time=0;
                   2750:     foreach my $other (keys(%accessed)) {
                   2751: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2752: 	    $to_kick=$other;
                   2753: 	    $max_time=&tv_interval($accessed{$other});
                   2754: 	}
                   2755:     }
                   2756:     delete($remembered{$to_kick});
                   2757:     delete($accessed{$to_kick});
                   2758:     $kicks++;
                   2759:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2760:     return;
                   2761: }
                   2762: 
1.599     albertel 2763: sub purge_remembered {
1.604     albertel 2764:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2765:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2766:     undef(%remembered);
                   2767:     undef(%accessed);
1.428     albertel 2768: }
1.70      www      2769: # ------------------------------------- Read an entry from a user's environment
                   2770: 
                   2771: sub userenvironment {
                   2772:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2773:     my $items;
                   2774:     foreach my $item (@what) {
                   2775:         $items.=&escape($item).'&';
                   2776:     }
                   2777:     $items=~s/\&$//;
1.70      www      2778:     my %returnhash=();
1.1009    raeburn  2779:     my $uhome = &homeserver($unam,$udom);
                   2780:     unless ($uhome eq 'no_host') {
                   2781:         my @answer=split(/\&/, 
                   2782:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2783:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2784:             return %returnhash;
                   2785:         }
1.1009    raeburn  2786:         my $i;
                   2787:         for ($i=0;$i<=$#what;$i++) {
                   2788: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2789:         }
1.70      www      2790:     }
                   2791:     return %returnhash;
1.1       albertel 2792: }
                   2793: 
1.617     albertel 2794: # ---------------------------------------------------------- Get a studentphoto
                   2795: sub studentphoto {
                   2796:     my ($udom,$unam,$ext) = @_;
                   2797:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2798:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2799:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2800:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2801:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2802:             } else {
                   2803:                 my ($result,$perm_reqd)=
1.707     albertel 2804: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2805:                 if ($result eq 'ok') {
                   2806:                     if (!($perm_reqd eq 'yes')) {
                   2807:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2808:                     }
                   2809:                 }
                   2810:             }
                   2811:         }
                   2812:     } else {
                   2813:         my ($result,$perm_reqd) = 
1.707     albertel 2814: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2815:         if ($result eq 'ok') {
                   2816:             if (!($perm_reqd eq 'yes')) {
                   2817:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2818:             }
                   2819:         }
                   2820:     }
                   2821:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2822: }
                   2823: 
                   2824: sub retrievestudentphoto {
                   2825:     my ($udom,$unam,$ext,$type) = @_;
                   2826:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2827:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2828:     if ($ret eq 'ok') {
                   2829:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2830:         if ($type eq 'thumbnail') {
                   2831:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2832:         }
                   2833:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2834:         return $tokenurl;
                   2835:     } else {
                   2836:         if ($type eq 'thumbnail') {
                   2837:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2838:         } else { 
                   2839:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2840:         }
1.617     albertel 2841:     }
                   2842: }
                   2843: 
1.263     www      2844: # -------------------------------------------------------------------- New chat
                   2845: 
                   2846: sub chatsend {
1.724     raeburn  2847:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2848:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2849:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2850:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2851:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2852: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2853: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2854: }
                   2855: 
                   2856: # ------------------------------------------ Find current version of a resource
                   2857: 
                   2858: sub getversion {
                   2859:     my $fname=&clutter(shift);
1.1189    raeburn  2860:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2861:     return &currentversion(&filelocation('',$fname));
                   2862: }
                   2863: 
                   2864: sub currentversion {
                   2865:     my $fname=shift;
                   2866:     my $author=$fname;
                   2867:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2868:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2869:     my $home=&homeserver($uname,$udom);
1.292     www      2870:     if ($home eq 'no_host') { 
                   2871:         return -1; 
                   2872:     }
1.1112    www      2873:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2874:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2875: 	return -1;
                   2876:     }
1.1112    www      2877:     return $answer;
1.263     www      2878: }
                   2879: 
1.1111    www      2880: #
                   2881: # Return special version number of resource if set by override, empty otherwise
                   2882: #
                   2883: sub usedversion {
                   2884:     my $fname=shift;
                   2885:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2886:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2887:     if ($urlversion) { return $urlversion; }
                   2888:     return '';
                   2889: }
                   2890: 
1.1       albertel 2891: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2892: 
1.1       albertel 2893: sub subscribe {
                   2894:     my $fname=shift;
1.761     raeburn  2895:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2896:     $fname=~s/[\n\r]//g;
1.1       albertel 2897:     my $author=$fname;
                   2898:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2899:     my ($udom,$uname)=split(/\//,$author);
                   2900:     my $home=homeserver($uname,$udom);
1.335     albertel 2901:     if ($home eq 'no_host') {
                   2902:         return 'not_found';
1.1       albertel 2903:     }
                   2904:     my $answer=reply("sub:$fname",$home);
1.64      www      2905:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2906: 	$answer.=' by '.$home;
                   2907:     }
1.1       albertel 2908:     return $answer;
                   2909: }
                   2910:     
1.8       www      2911: # -------------------------------------------------------------- Replicate file
                   2912: 
                   2913: sub repcopy {
                   2914:     my $filename=shift;
1.23      www      2915:     $filename=~s/\/+/\//g;
1.1142    raeburn  2916:     my $londocroot = $perlvar{'lonDocRoot'};
                   2917:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2918:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2919:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2920: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2921: 	return &repcopy_userfile($filename);
                   2922:     }
1.532     albertel 2923:     $filename=~s/[\n\r]//g;
1.8       www      2924:     my $transname="$filename.in.transfer";
1.828     www      2925: # FIXME: this should flock
1.607     raeburn  2926:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2927:     my $remoteurl=subscribe($filename);
1.64      www      2928:     if ($remoteurl =~ /^con_lost by/) {
                   2929: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2930:            return 'unavailable';
1.8       www      2931:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2932: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2933: 	   return 'not_found';
1.64      www      2934:     } elsif ($remoteurl =~ /^rejected by/) {
                   2935: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2936:            return 'forbidden';
1.20      www      2937:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2938:            return 'ok';
1.8       www      2939:     } else {
1.290     www      2940:         my $author=$filename;
                   2941:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2942:         my ($udom,$uname)=split(/\//,$author);
                   2943:         my $home=homeserver($uname,$udom);
                   2944:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2945:            my @parts=split(/\//,$filename);
                   2946:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2947:            if ($path ne "$londocroot/res") {
1.8       www      2948:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2949: 	       return 'bad_request';
1.8       www      2950:            }
                   2951:            my $count;
                   2952:            for ($count=5;$count<$#parts;$count++) {
                   2953:                $path.="/$parts[$count]";
                   2954:                if ((-e $path)!=1) {
                   2955: 		   mkdir($path,0777);
                   2956:                }
                   2957:            }
                   2958:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  2959:            my $response;
                   2960:            if ($remoteurl =~ m{/raw/}) {
                   2961:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   2962:            } else {
                   2963:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   2964:            }
1.8       www      2965:            if ($response->is_error()) {
                   2966: 	       unlink($transname);
                   2967:                my $message=$response->status_line;
1.672     albertel 2968:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2969:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2970:                return 'unavailable';
1.8       www      2971:            } else {
1.16      www      2972: 	       if ($remoteurl!~/\.meta$/) {
                   2973:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  2974:                   my $mresponse;
                   2975:                   if ($remoteurl =~ m{/raw/}) {
                   2976:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   2977:                   } else {
                   2978:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   2979:                   }
1.16      www      2980:                   if ($mresponse->is_error()) {
                   2981: 		      unlink($filename.'.meta');
                   2982:                       &logthis(
1.672     albertel 2983:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2984:                   }
                   2985: 	       }
1.8       www      2986:                rename($transname,$filename);
1.607     raeburn  2987:                return 'ok';
1.8       www      2988:            }
1.290     www      2989:        }
1.8       www      2990:     }
1.330     www      2991: }
                   2992: 
                   2993: # ------------------------------------------------ Get server side include body
                   2994: sub ssi_body {
1.381     albertel 2995:     my ($filelink,%form)=@_;
1.606     matthew  2996:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2997:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2998:     }
1.953     www      2999:     my $output='';
                   3000:     my $response;
1.980     raeburn  3001:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3002:        ($output,$response)=&externalssi($filelink);
1.953     www      3003:     } else {
1.1004    droeschl 3004:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3005:        $filelink .= 'inhibitmenu=yes';
1.953     www      3006:        ($output,$response)=&ssi($filelink,%form);
                   3007:     }
1.778     albertel 3008:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3009:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3010:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3011:     if (wantarray) {
                   3012:         return ($output, $response);
                   3013:     } else {
                   3014:         return $output;
                   3015:     }
1.8       www      3016: }
                   3017: 
1.15      www      3018: # --------------------------------------------------------- Server Side Include
                   3019: 
1.782     albertel 3020: sub absolute_url {
                   3021:     my ($host_name) = @_;
                   3022:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3023:     if ($host_name eq '') {
                   3024: 	$host_name = $ENV{'SERVER_NAME'};
                   3025:     }
                   3026:     return $protocol.$host_name;
                   3027: }
                   3028: 
1.942     foxr     3029: #
                   3030: #   Server side include.
                   3031: # Parameters:
                   3032: #  fn     Possibly encrypted resource name/id.
                   3033: #  form   Hash that describes how the rendering should be done
                   3034: #         and other things.
1.944     foxr     3035: # Returns:
1.950     raeburn  3036: #   Scalar context: The content of the response.
                   3037: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3038: #     
1.15      www      3039: sub ssi {
                   3040: 
1.944     foxr     3041:     my ($fn,%form)=@_;
1.23      www      3042:     my $request;
1.711     albertel 3043: 
                   3044:     $form{'no_update_last_known'}=1;
1.895     albertel 3045:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3046:     if (%form) {
1.782     albertel 3047:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3048:       $request->content(join('&',map { 
                   3049:             my $name = escape($_);
                   3050:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3051:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3052:             : &escape($form{$_}) );    
                   3053:         } keys(%form)));
1.23      www      3054:     } else {
1.782     albertel 3055:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3056:     }
                   3057: 
1.15      www      3058:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3059:     my $lonhost = $perlvar{'lonHostID'};
                   3060:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
1.1182    foxr     3061: 
1.944     foxr     3062:     if (wantarray) {
1.1345    raeburn  3063: 	return ($response->content, $response);
1.944     foxr     3064:     } else {
1.1345    raeburn  3065: 	return $response->content;
1.942     foxr     3066:     }
1.324     www      3067: }
                   3068: 
                   3069: sub externalssi {
                   3070:     my ($url)=@_;
                   3071:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3072:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3073:     if (wantarray) {
                   3074:         return ($response->content, $response);
                   3075:     } else {
                   3076:         return $response->content;
                   3077:     }
1.15      www      3078: }
1.254     www      3079: 
1.492     albertel 3080: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3081: 
                   3082: sub allowuploaded {
                   3083:     my ($srcurl,$url)=@_;
                   3084:     $url=&clutter(&declutter($url));
                   3085:     my $dir=$url;
                   3086:     $dir=~s/\/[^\/]+$//;
                   3087:     my %httpref=();
                   3088:     my $httpurl=&hreflocation('',$url);
                   3089:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3090:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3091: }
1.477     raeburn  3092: 
1.1193    raeburn  3093: #
                   3094: # Determine if the current user should be able to edit a particular resource,
                   3095: # when viewing in course context.
                   3096: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3097: #     Functions.
                   3098: # (b) When displaying folder contents in course editor, used to determine if
                   3099: #     "Edit" link will be displayed alongside resource.
                   3100: #
1.1196    raeburn  3101: #  input: six args -- filename (decluttered), course number, course domain,
                   3102: #                   url, symb (if registered) and group (if this is a group
                   3103: #                   item -- e.g., bulletin board, group page etc.).
                   3104: #  output: array of five scalars -- 
1.1193    raeburn  3105: #          $cfile -- url for file editing if editable on current server
                   3106: #          $home -- homeserver of resource (i.e., for author if published,
                   3107: #                                           or course if uploaded.).
                   3108: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3109: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3110: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3111: #
                   3112: 
                   3113: sub can_edit_resource {
1.1194    raeburn  3114:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3115:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3116: #
                   3117: # For aboutme pages user can only edit his/her own.
                   3118: #
1.1199    raeburn  3119:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3120:         my ($sdom,$sname) = ($1,$2);
                   3121:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3122:             $home = $env{'user.home'};
                   3123:             $cfile = $resurl;
                   3124:             if ($env{'form.forceedit'}) {
                   3125:                 $forceview = 1;
                   3126:             } else {
                   3127:                 $forceedit = 1;
                   3128:             }
                   3129:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3130:         } else {
                   3131:             return;
                   3132:         }
                   3133:     }
                   3134: 
                   3135:     if ($env{'request.course.id'}) {
                   3136:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3137:         if ($group ne '') {
                   3138: # if this is a group homepage or group bulletin board, check group privs
                   3139:             my $allowed = 0;
1.1197    raeburn  3140:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3141:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3142:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3143:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3144:                     $allowed = 1;
                   3145:                 }
1.1197    raeburn  3146:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3147:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3148:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3149:                     $allowed = 1;
                   3150:                 }
                   3151:             }
                   3152:             if ($allowed) {
                   3153:                 $home=&homeserver($cnum,$cdom);
                   3154:                 if ($env{'form.forceedit'}) {
                   3155:                     $forceview = 1;
                   3156:                 } else {
                   3157:                     $forceedit = 1;
                   3158:                 }
                   3159:                 $cfile = $resurl;
                   3160:             } else {
                   3161:                 return;
                   3162:             }
                   3163:         } else {
1.1208    raeburn  3164:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3165:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3166:                     return;
                   3167:                 }
                   3168:             } elsif (!$crsedit) {
1.1194    raeburn  3169: #
                   3170: # No edit allowed where CC has switched to student role.
                   3171: #
                   3172:                 return;
                   3173:             }
                   3174:         }
                   3175:     }
                   3176: 
1.1193    raeburn  3177:     if ($file ne '') {
                   3178:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3179:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3180:                 $uploaded = 1;
                   3181:                 $incourse = 1;
1.1193    raeburn  3182:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3183:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3184:                     if ($env{'form.forceedit'}) {
                   3185:                         $forceview = 1;
                   3186:                     } else {
                   3187:                         $forceedit = 1;
                   3188:                     }
1.1194    raeburn  3189:                 }
                   3190:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3191:                 $incourse = 1;
                   3192:                 if ($env{'form.forceedit'}) {
                   3193:                     $forceview = 1;
                   3194:                 } else {
                   3195:                     $forceedit = 1;
                   3196:                 }
                   3197:                 $cfile = $resurl;
                   3198:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3199:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3200:                     $incourse = 1;
                   3201:                     if ($env{'form.forceedit'}) {
                   3202:                         $forceview = 1;
                   3203:                     } else {
                   3204:                         $forceedit = 1;
                   3205:                     }
                   3206:                     $cfile = $resurl;
1.1199    raeburn  3207:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3208:                     $incourse = 1;
                   3209:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3210:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3211:                     $incourse = 1;
1.1199    raeburn  3212:                     if ($env{'form.forceedit'}) {
                   3213:                         $forceview = 1;
                   3214:                     } else {
                   3215:                         $forceedit = 1;
                   3216:                     }
                   3217:                     $cfile = $resurl;
1.1343    raeburn  3218:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3219:                     $incourse = 1;
                   3220:                     if ($env{'form.forceedit'}) {
                   3221:                         $forceview = 1;
                   3222:                     } else {
                   3223:                         $forceedit = 1;
                   3224:                     }
                   3225:                     $cfile = $resurl;
1.1208    raeburn  3226:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3227:                     $incourse = 1;
                   3228:                     if ($env{'form.forceedit'}) {
                   3229:                         $forceview = 1;
                   3230:                     } else {
                   3231:                         $forceedit = 1;
                   3232:                     }
                   3233:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3234:                 }
                   3235:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3236:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3237:                 if (&is_on_map($template)) { 
                   3238:                     $incourse = 1;
                   3239:                     $forceview = 1;
                   3240:                     $cfile = $template;
1.1193    raeburn  3241:                 }
1.1199    raeburn  3242:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3243:                     $incourse = 1;
                   3244:                     if ($env{'form.forceedit'}) {
                   3245:                         $forceview = 1;
                   3246:                     } else {
                   3247:                         $forceedit = 1;
                   3248:                     }
                   3249:                     $cfile = $resurl;
1.1343    raeburn  3250:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3251:                 $incourse = 1;
                   3252:                 if ($env{'form.forceedit'}) {
                   3253:                     $forceview = 1;
                   3254:                 } else {
                   3255:                     $forceedit = 1;
                   3256:                 }
                   3257:                 $cfile = $resurl;
1.1199    raeburn  3258:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3259:                 $incourse = 1;
                   3260:                 $forceview = 1;
                   3261:                 if ($symb) {
                   3262:                     my ($map,$id,$res)=&decode_symb($symb);
                   3263:                     $env{'request.symb'} = $symb;
                   3264:                     $cfile = &clutter($res);
                   3265:                 } else {
                   3266:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3267:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3268:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3269:                         $cfile = '/adm/wrapper'.$escfile;
                   3270:                     } else {
                   3271:                         $escfile =~ s{^http://}{};
                   3272:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3273:                     }
1.1199    raeburn  3274:                 }
1.1234    raeburn  3275:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3276:                 if ($env{'form.forceedit'}) {
                   3277:                     $forceview = 1;
                   3278:                 } else {
                   3279:                     $forceedit = 1;
                   3280:                 }
                   3281:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3282:             }
                   3283:         }
1.1194    raeburn  3284:         if ($uploaded || $incourse) {
                   3285:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3286:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3287:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3288:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3289:             # Check that the user has permission to edit this resource
                   3290:             my $setpriv = 1;
                   3291:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3292:             if (defined($cfudom)) {
                   3293:                 $home=&homeserver($cfuname,$cfudom);
                   3294:                 $cfile=$file;
                   3295:             }
                   3296:         }
1.1194    raeburn  3297:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3298:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3299:             my @ids=&current_machine_ids();
                   3300:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3301:                 $switchserver=1;
                   3302:             }
                   3303:         }
                   3304:     }
1.1194    raeburn  3305:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3306: }
                   3307: 
                   3308: sub is_course_upload {
                   3309:     my ($file,$cnum,$cdom) = @_;
                   3310:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3311:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3312:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3313:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3314:         return 1;
                   3315:     }
                   3316:     return;
                   3317: }
                   3318: 
1.1194    raeburn  3319: sub in_course {
1.1195    raeburn  3320:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3321:     if ($hideprivileged) {
                   3322:         my $skipuser;
1.1219    raeburn  3323:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3324:         my @possdoms = ($cdom);  
                   3325:         if ($coursehash{'checkforpriv'}) { 
                   3326:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3327:         }
                   3328:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3329:             $skipuser = 1;
                   3330:             if ($coursehash{'nothideprivileged'}) {
                   3331:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3332:                     my $user;
                   3333:                     if ($item =~ /:/) {
                   3334:                         $user = $item;
                   3335:                     } else {
                   3336:                         $user = join(':',split(/[\@]/,$item));
                   3337:                     }
                   3338:                     if ($user eq $uname.':'.$udom) {
                   3339:                         undef($skipuser);
                   3340:                         last;
                   3341:                     }
                   3342:                 }
                   3343:             }
                   3344:             if ($skipuser) {
                   3345:                 return 0;
                   3346:             }
                   3347:         }
                   3348:     }
1.1194    raeburn  3349:     $type ||= 'any';
                   3350:     if (!defined($cdom) || !defined($cnum)) {
                   3351:         my $cid  = $env{'request.course.id'};
                   3352:         $cdom = $env{'course.'.$cid.'.domain'};
                   3353:         $cnum = $env{'course.'.$cid.'.num'};
                   3354:     }
                   3355:     my $typesref;
1.1195    raeburn  3356:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3357:         $typesref = ['active','previous','future'];
                   3358:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3359:         $typesref = [$type];
                   3360:     }
                   3361:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3362:                               $typesref,undef,[$cdom]);
                   3363:     my ($tmp) = keys(%roles);
                   3364:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3365:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3366:     if (@course_roles > 0) {
                   3367:         return 1;
                   3368:     }
                   3369:     return 0;
                   3370: }
                   3371: 
1.478     albertel 3372: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3373: # input: action, courseID, current domain, intended
1.637     raeburn  3374: #        path to file, source of file, instruction to parse file for objects,
                   3375: #        ref to hash for embedded objects,
                   3376: #        ref to hash for codebase of java objects.
1.1095    raeburn  3377: #        reference to scalar to accommodate mime type determined
                   3378: #          from File::MMagic if $parser = parse.
1.637     raeburn  3379: #
1.485     raeburn  3380: # output: url to file (if action was uploaddoc), 
                   3381: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3382: #
1.478     albertel 3383: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3384: # course.
1.477     raeburn  3385: #
1.478     albertel 3386: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3387: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3388: #          course's home server.
1.477     raeburn  3389: #
1.478     albertel 3390: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3391: #          be copied from $source (current location) to 
                   3392: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3393: #         and will then be copied to
                   3394: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3395: #         course's home server.
1.485     raeburn  3396: #
1.481     raeburn  3397: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3398: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3399: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3400: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3401: #         in course's home server.
1.637     raeburn  3402: #
1.477     raeburn  3403: 
                   3404: sub process_coursefile {
1.1095    raeburn  3405:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3406:         $mimetype)=@_;
1.477     raeburn  3407:     my $fetchresult;
1.638     albertel 3408:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3409:     if ($action eq 'propagate') {
1.638     albertel 3410:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3411: 			     $home);
1.481     raeburn  3412:     } else {
1.477     raeburn  3413:         my $fpath = '';
                   3414:         my $fname = $file;
1.478     albertel 3415:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3416:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3417:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3418:         if ($action eq 'copy') {
                   3419:             if ($source eq '') {
                   3420:                 $fetchresult = 'no source file';
                   3421:                 return $fetchresult;
                   3422:             } else {
                   3423:                 my $destination = $filepath.'/'.$fname;
                   3424:                 rename($source,$destination);
                   3425:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3426:                                  $home);
1.481     raeburn  3427:             }
                   3428:         } elsif ($action eq 'uploaddoc') {
                   3429:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 3430:             print $fh $env{'form.'.$source};
1.481     raeburn  3431:             close($fh);
1.637     raeburn  3432:             if ($parser eq 'parse') {
1.1024    raeburn  3433:                 my $mm = new File::MMagic;
1.1095    raeburn  3434:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3435:                 if ($type eq 'text/html') {
1.1024    raeburn  3436:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3437:                     unless ($parse_result eq 'ok') {
                   3438:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3439:                     }
1.637     raeburn  3440:                 }
1.1095    raeburn  3441:                 if (ref($mimetype)) {
                   3442:                     $$mimetype = $type;
                   3443:                 } 
1.637     raeburn  3444:             }
1.477     raeburn  3445:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3446:                                  $home);
1.481     raeburn  3447:             if ($fetchresult eq 'ok') {
                   3448:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3449:             } else {
                   3450:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3451:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3452:                 return '/adm/notfound.html';
                   3453:             }
1.477     raeburn  3454:         }
                   3455:     }
1.485     raeburn  3456:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3457:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3458:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3459:     }
                   3460:     return $fetchresult;
                   3461: }
                   3462: 
1.637     raeburn  3463: sub build_filepath {
                   3464:     my ($fpath) = @_;
                   3465:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3466:     unless ($fpath eq '') {
                   3467:         my @parts=split('/',$fpath);
                   3468:         foreach my $part (@parts) {
                   3469:             $filepath.= '/'.$part;
                   3470:             if ((-e $filepath)!=1) {
                   3471:                 mkdir($filepath,0777);
                   3472:             }
                   3473:         }
                   3474:     }
                   3475:     return $filepath;
                   3476: }
                   3477: 
                   3478: sub store_edited_file {
1.638     albertel 3479:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3480:     my $file = $primary_url;
                   3481:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3482:     my $fpath = '';
                   3483:     my $fname = $file;
                   3484:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3485:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3486:     my $filepath = &build_filepath($fpath);
                   3487:     open(my $fh,'>'.$filepath.'/'.$fname);
                   3488:     print $fh $content;
                   3489:     close($fh);
1.638     albertel 3490:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3491:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3492: 			  $home);
1.637     raeburn  3493:     if ($$fetchresult eq 'ok') {
                   3494:         return '/uploaded/'.$fpath.'/'.$fname;
                   3495:     } else {
1.638     albertel 3496:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3497: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3498:         return '/adm/notfound.html';
                   3499:     }
                   3500: }
                   3501: 
1.531     albertel 3502: sub clean_filename {
1.831     albertel 3503:     my ($fname,$args)=@_;
1.315     www      3504: # Replace Windows backslashes by forward slashes
1.257     www      3505:     $fname=~s/\\/\//g;
1.831     albertel 3506:     if (!$args->{'keep_path'}) {
                   3507:         # Get rid of everything but the actual filename
                   3508: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3509:     }
1.315     www      3510: # Replace spaces by underscores
                   3511:     $fname=~s/\s+/\_/g;
                   3512: # Replace all other weird characters by nothing
1.831     albertel 3513:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3514: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3515: # numbers
                   3516:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3517:     return $fname;
                   3518: }
1.1051    raeburn  3519: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3520: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3521: # image with the same aspect ratio as the original, but with dimensions which do 
                   3522: # not exceed $resizewidth and $resizeheight.
                   3523:  
1.984     neumanie 3524: sub resizeImage {
1.1051    raeburn  3525:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3526:     my $ima = Image::Magick->new;
                   3527:     my $resized;
                   3528:     if (-e $img_path) {
                   3529:         $ima->Read($img_path);
                   3530:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3531:             my $width = $ima->Get('width');
                   3532:             my $height = $ima->Get('height');
                   3533:             if ($width > $resizewidth) {
                   3534: 	        my $factor = $width/$resizewidth;
                   3535:                 my $newheight = $height/$factor;
                   3536:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3537:                 $resized = 1;
                   3538:             }
                   3539:         }
                   3540:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3541:             my $width = $ima->Get('width');
                   3542:             my $height = $ima->Get('height');
                   3543:             if ($height > $resizeheight) {
                   3544:                 my $factor = $height/$resizeheight;
                   3545:                 my $newwidth = $width/$factor;
                   3546:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3547:                 $resized = 1;
                   3548:             }
                   3549:         }
                   3550:         if ($resized) {
                   3551:             $ima->Write($img_path);
                   3552:         }
                   3553:     }
                   3554:     return;
1.977     amueller 3555: }
                   3556: 
1.608     albertel 3557: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3558: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3559: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3560: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3561: #                                    canceloverwrite, or ''. 
                   3562: #                   if 'coursedoc': upload to the current course
                   3563: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3564: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3565: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3566: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3567: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3568: #        $allfiles - reference to hash for embedded objects
                   3569: #        $codebase - reference to hash for codebase of java objects
                   3570: #        $desuname - username for permanent storage of uploaded file
                   3571: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3572: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3573: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3574: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3575: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3576: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3577: #                    from File::MMagic.
1.858     raeburn  3578: # 
1.686     albertel 3579: # output: url of file in userspace, or error: <message> 
                   3580: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3581: 
1.531     albertel 3582: sub userfileupload {
1.1090    raeburn  3583:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3584:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3585:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3586:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3587:     $fname=&clean_filename($fname);
1.1090    raeburn  3588:     # See if there is anything left
1.257     www      3589:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3590:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3591:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3592:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3593:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3594:         my $now = time;
1.1090    raeburn  3595:         my $filepath;
1.1095    raeburn  3596:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3597:              $filepath = 'tmp/helprequests/'.$now;
                   3598:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3599:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3600:                          '_'.$env{'user.domain'}.'/pending';
                   3601:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3602:             my ($docuname,$docudom);
                   3603:             if ($destudom) {
                   3604:                 $docudom = $destudom;
                   3605:             } else {
                   3606:                 $docudom = $env{'user.domain'};
                   3607:             }
                   3608:             if ($destuname) {
                   3609:                 $docuname = $destuname;
                   3610:             } else {
                   3611:                 $docuname = $env{'user.name'};
                   3612:             }
                   3613:             if (exists($env{'form.group'})) {
                   3614:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3615:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3616:             }
                   3617:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3618:             if ($context eq 'canceloverwrite') {
                   3619:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3620:                 if (-e  $tempfile) {
                   3621:                     my @info = stat($tempfile);
                   3622:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3623:                         unlink($tempfile);
                   3624:                     }
                   3625:                 }
                   3626:                 return;
1.523     raeburn  3627:             }
                   3628:         }
1.1090    raeburn  3629:         # Create the directory if not present
1.741     raeburn  3630:         my @parts=split(/\//,$filepath);
                   3631:         my $fullpath = $perlvar{'lonDaemons'};
                   3632:         for (my $i=0;$i<@parts;$i++) {
                   3633:             $fullpath .= '/'.$parts[$i];
                   3634:             if ((-e $fullpath)!=1) {
                   3635:                 mkdir($fullpath,0777);
                   3636:             }
                   3637:         }
                   3638:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   3639:         print $fh $env{'form.'.$formname};
                   3640:         close($fh);
1.1090    raeburn  3641:         if ($context eq 'existingfile') {
                   3642:             my @info = stat($fullpath.'/'.$fname);
                   3643:             return ($fullpath.'/'.$fname,$info[9]);
                   3644:         } else {
                   3645:             return $fullpath.'/'.$fname;
                   3646:         }
1.523     raeburn  3647:     }
1.995     raeburn  3648:     if ($subdir eq 'scantron') {
                   3649:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3650:     } else {
1.995     raeburn  3651:         $fname="$subdir/$fname";
                   3652:     }
1.1090    raeburn  3653:     if ($context eq 'coursedoc') {
1.638     albertel 3654: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3655: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3656:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3657:             return &finishuserfileupload($docuname,$docudom,
                   3658: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3659: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3660:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3661:         } else {
1.1218    raeburn  3662:             if ($env{'form.folder'}) {
                   3663:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3664:             }
1.638     albertel 3665:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3666: 				       $fname,$formname,$parser,
1.1095    raeburn  3667: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3668:         }
1.719     banghart 3669:     } elsif (defined($destuname)) {
                   3670:         my $docuname=$destuname;
                   3671:         my $docudom=$destudom;
1.860     raeburn  3672: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3673: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3674:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3675:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3676:     } else {
1.638     albertel 3677:         my $docuname=$env{'user.name'};
                   3678:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3679:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3680:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3681:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3682:         }
1.860     raeburn  3683: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3684: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3685:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3686:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3687:     }
1.271     www      3688: }
                   3689: 
                   3690: sub finishuserfileupload {
1.860     raeburn  3691:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3692:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3693:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3694:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3695:   
1.860     raeburn  3696:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3697:     $file=$fname;
                   3698:     if ($fname=~m|/|) {
                   3699:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3700: 	$path.=$fnamepath.'/';
                   3701:     }
1.259     www      3702:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3703:     my $count;
                   3704:     for ($count=4;$count<=$#parts;$count++) {
                   3705:         $filepath.="/$parts[$count]";
                   3706:         if ((-e $filepath)!=1) {
                   3707: 	    mkdir($filepath,0777);
                   3708:         }
                   3709:     }
1.984     neumanie 3710: 
1.258     www      3711: # Save the file
                   3712:     {
1.701     albertel 3713: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   3714: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3715: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3716: 	    return '/adm/notfound.html';
                   3717: 	}
1.1090    raeburn  3718:         if ($context eq 'overwrite') {
1.1117    foxr     3719:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3720:             my $target = $filepath.'/'.$file;
                   3721:             if (-e $source) {
                   3722:                 my @info = stat($source);
                   3723:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3724:                     unless (&File::Copy::move($source,$target)) {
                   3725:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3726:                         return "Moving from $source failed";
                   3727:                     }
                   3728:                 } else {
                   3729:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3730:                 }
                   3731:             } else {
                   3732:                 return "Temporary file: $source missing";
                   3733:             }
                   3734:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3735: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3736: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3737: 	    return '/adm/notfound.html';
                   3738: 	}
1.570     albertel 3739: 	close(FH);
1.1051    raeburn  3740:         if ($resizewidth && $resizeheight) {
                   3741:             my $mm = new File::MMagic;
                   3742:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3743:             if ($mime_type =~ m{^image/}) {
                   3744: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3745:             }  
1.977     amueller 3746: 	}
1.258     www      3747:     }
1.1152    raeburn  3748:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3749:         if (ref($mimetype)) {
                   3750:             if ($$mimetype eq '') {
                   3751:                 my $mm = new File::MMagic;
                   3752:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3753:                 $$mimetype = $type;
                   3754:             }
                   3755:         }
                   3756:     }
1.637     raeburn  3757:     if ($parser eq 'parse') {
1.1152    raeburn  3758:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3759:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3760:                                                        $allfiles,$codebase);
                   3761:             unless ($parse_result eq 'ok') {
                   3762:                 &logthis('Failed to parse '.$filepath.$file.
                   3763: 	   	         ' for embedded media: '.$parse_result); 
                   3764:             }
1.637     raeburn  3765:         }
                   3766:     }
1.860     raeburn  3767:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3768:         my $input = $filepath.'/'.$file;
                   3769:         my $output = $filepath.'/'.'tn-'.$file;
                   3770:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3771:         system("convert -sample $thumbsize $input $output");
                   3772:         if (-e $filepath.'/'.'tn-'.$file) {
                   3773:             $fetchthumb  = 1; 
                   3774:         }
                   3775:     }
1.858     raeburn  3776:  
1.259     www      3777: # Notify homeserver to grep it
                   3778: #
1.984     neumanie 3779:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3780:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3781:     if ($fetchresult eq 'ok') {
1.860     raeburn  3782:         if ($fetchthumb) {
                   3783:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3784:             if ($thumbresult ne 'ok') {
                   3785:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3786:                          $docuhome.': '.$thumbresult);
                   3787:             }
                   3788:         }
1.259     www      3789: #
1.258     www      3790: # Return the URL to it
1.494     albertel 3791:         return '/uploaded/'.$path.$file;
1.263     www      3792:     } else {
1.494     albertel 3793:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3794: 		 ': '.$fetchresult);
1.263     www      3795:         return '/adm/notfound.html';
1.858     raeburn  3796:     }
1.493     albertel 3797: }
                   3798: 
1.637     raeburn  3799: sub extract_embedded_items {
1.961     raeburn  3800:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3801:     my @state = ();
1.1164    raeburn  3802:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3803:     my %javafiles = (
                   3804:                       codebase => '',
                   3805:                       code => '',
                   3806:                       archive => ''
                   3807:                     );
                   3808:     my %mediafiles = (
                   3809:                       src => '',
                   3810:                       movie => '',
                   3811:                      );
1.648     raeburn  3812:     my $p;
                   3813:     if ($content) {
                   3814:         $p = HTML::LCParser->new($content);
                   3815:     } else {
1.961     raeburn  3816:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3817:     }
1.641     albertel 3818:     while (my $t=$p->get_token()) {
1.640     albertel 3819: 	if ($t->[0] eq 'S') {
                   3820: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3821: 	    push(@state, $tagname);
1.648     raeburn  3822:             if (lc($tagname) eq 'allow') {
                   3823:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3824:             }
1.640     albertel 3825: 	    if (lc($tagname) eq 'img') {
                   3826: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3827: 	    }
1.886     albertel 3828: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  3829:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  3830:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3831:                 }
1.886     albertel 3832: 	    }
1.645     raeburn  3833:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3834:                 my $src;
1.645     raeburn  3835:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3836:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3837:                 } else {
1.1164    raeburn  3838:                     if ($attr->{'src'} ne '') {
                   3839:                         $src = $attr->{'src'};
                   3840:                         &add_filetype($allfiles,$src,'src');
                   3841:                     }
                   3842:                 }
                   3843:                 my $text = $p->get_trimmed_text();
                   3844:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3845:                     my @swfargs = split(/,/,$1);
                   3846:                     foreach my $item (@swfargs) {
                   3847:                         $item =~ s/["']//g;
                   3848:                         $item =~ s/^\s+//;
                   3849:                         $item =~ s/\s+$//;
                   3850:                     }
                   3851:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3852:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3853:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3854:                         } else {
                   3855:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3856:                         }
                   3857:                     }
1.645     raeburn  3858:                 }
                   3859:             }
                   3860:             if (lc($tagname) eq 'link') {
                   3861:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3862:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3863:                 }
                   3864:             }
1.640     albertel 3865: 	    if (lc($tagname) eq 'object' ||
                   3866: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3867: 		foreach my $item (keys(%javafiles)) {
                   3868: 		    $javafiles{$item} = '';
                   3869: 		}
1.1164    raeburn  3870:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3871:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3872:                 }
1.640     albertel 3873: 	    }
                   3874: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3875: 		my $name = lc($attr->{'name'});
                   3876: 		foreach my $item (keys(%javafiles)) {
                   3877: 		    if ($name eq $item) {
                   3878: 			$javafiles{$item} = $attr->{'value'};
                   3879: 			last;
                   3880: 		    }
                   3881: 		}
1.1164    raeburn  3882:                 my $pathfrom;
1.640     albertel 3883: 		foreach my $item (keys(%mediafiles)) {
                   3884: 		    if ($name eq $item) {
1.1164    raeburn  3885:                         $pathfrom = $attr->{'value'};
                   3886:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3887: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3888: 			last;
                   3889: 		    }
                   3890: 		}
1.1164    raeburn  3891:                 if ($name eq 'flashvars') {
                   3892:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3893:                 }
                   3894:                 if ($pathfrom ne '') {
                   3895:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3896:                                          $pathfrom);
                   3897:                 }
1.640     albertel 3898: 	    }
                   3899: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3900: 		foreach my $item (keys(%javafiles)) {
                   3901: 		    if ($attr->{$item}) {
                   3902: 			$javafiles{$item} = $attr->{$item};
                   3903: 			last;
                   3904: 		    }
                   3905: 		}
                   3906: 		foreach my $item (keys(%mediafiles)) {
                   3907: 		    if ($attr->{$item}) {
                   3908: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3909: 			last;
                   3910: 		    }
                   3911: 		}
1.1164    raeburn  3912:                 if (lc($tagname) eq 'embed') {
                   3913:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3914:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3915:                                              $attr->{'src'});
                   3916:                     }
                   3917:                 }
1.640     albertel 3918: 	    }
1.1243    raeburn  3919:             if (lc($tagname) eq 'iframe') {
                   3920:                 my $src = $attr->{'src'} ;
                   3921:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   3922:                     &add_filetype($allfiles,$src,'src');
                   3923:                 } elsif ($src =~ m{^/}) {
                   3924:                     if ($env{'request.course.id'}) {
                   3925:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3926:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   3927:                         my $url = &hreflocation('',$fullpath);
                   3928:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   3929:                             my $relpath = $1;
                   3930:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   3931:                                 &add_filetype($allfiles,$1,'src');
                   3932:                             }
                   3933:                         }
                   3934:                     }
                   3935:                 }
                   3936:             }
1.1164    raeburn  3937:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  3938:                 pop(@state);
1.1164    raeburn  3939:             }
1.640     albertel 3940: 	} elsif ($t->[0] eq 'E') {
                   3941: 	    my ($tagname) = ($t->[1]);
                   3942: 	    if ($javafiles{'codebase'} ne '') {
                   3943: 		$javafiles{'codebase'} .= '/';
                   3944: 	    }  
                   3945: 	    if (lc($tagname) eq 'applet' ||
                   3946: 		lc($tagname) eq 'object' ||
                   3947: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3948: 		) {
                   3949: 		foreach my $item (keys(%javafiles)) {
                   3950: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3951: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3952: 			&add_filetype($allfiles,$file,$item);
                   3953: 		    }
                   3954: 		}
                   3955: 	    } 
                   3956: 	    pop @state;
                   3957: 	}
                   3958:     }
1.1164    raeburn  3959:     foreach my $id (sort(keys(%flashvars))) {
                   3960:         if ($shockwave{$id} ne '') {
                   3961:             my @pairs = split(/\&/,$flashvars{$id});
                   3962:             foreach my $pair (@pairs) {
                   3963:                 my ($key,$value) = split(/\=/,$pair);
                   3964:                 if ($key eq 'thumb') {
                   3965:                     &add_filetype($allfiles,$value,$key);
                   3966:                 } elsif ($key eq 'content') {
                   3967:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3968:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3969:                     if ($ext ne '') {
                   3970:                         &add_filetype($allfiles,$path.$value,$ext);
                   3971:                     }
                   3972:                 }
                   3973:             }
                   3974:         }
                   3975:     }
1.637     raeburn  3976:     return 'ok';
                   3977: }
                   3978: 
1.639     albertel 3979: sub add_filetype {
                   3980:     my ($allfiles,$file,$type)=@_;
                   3981:     if (exists($allfiles->{$file})) {
                   3982: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3983: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3984: 	}
                   3985:     } else {
                   3986: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3987:     }
                   3988: }
                   3989: 
1.1164    raeburn  3990: sub embedded_dependency {
                   3991:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3992:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3993:         if (($identifier ne '') &&
                   3994:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3995:             ($pathfrom ne '')) {
                   3996:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3997:             foreach my $dep (@{$related->{$identifier}}) {
                   3998:                 &add_filetype($allfiles,$path.$dep,'object');
                   3999:             }
                   4000:         }
                   4001:     }
                   4002:     return;
                   4003: }
                   4004: 
1.493     albertel 4005: sub removeuploadedurl {
1.984     neumanie 4006:     my ($url)=@_;	
                   4007:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4008:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4009: }
                   4010: 
                   4011: sub removeuserfile {
                   4012:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4013:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4014:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4015:     if ($result eq 'ok') {	
1.798     raeburn  4016:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4017:             my $metafile = $fname.'.meta';
                   4018:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4019: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4020:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4021:             my $sqlresult = 
1.823     albertel 4022:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4023:                                         'portfolio_metadata',$group,
                   4024:                                         'delete');
1.798     raeburn  4025:         }
                   4026:     }
                   4027:     return $result;
1.257     www      4028: }
1.15      www      4029: 
1.530     albertel 4030: sub mkdiruserfile {
                   4031:     my ($docuname,$docudom,$dir)=@_;
                   4032:     my $home=&homeserver($docuname,$docudom);
                   4033:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4034: }
                   4035: 
1.531     albertel 4036: sub renameuserfile {
                   4037:     my ($docuname,$docudom,$old,$new)=@_;
                   4038:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4039:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4040:                         &escape("$old").':'.&escape("$new"),$home);
                   4041:     if ($result eq 'ok') {
                   4042:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4043:             my $oldmeta = $old.'.meta';
                   4044:             my $newmeta = $new.'.meta';
                   4045:             my $metaresult = 
                   4046:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4047: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4048:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4049:             my $sqlresult = 
1.823     albertel 4050:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4051:                                         'portfolio_metadata',$group,
                   4052:                                         'delete');
1.798     raeburn  4053:         }
                   4054:     }
                   4055:     return $result;
1.531     albertel 4056: }
                   4057: 
1.14      www      4058: # ------------------------------------------------------------------------- Log
                   4059: 
                   4060: sub log {
                   4061:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4062:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4063: }
                   4064: 
                   4065: # ------------------------------------------------------------------ Course Log
1.352     www      4066: #
                   4067: # This routine flushes several buffers of non-mission-critical nature
                   4068: #
1.157     www      4069: 
                   4070: sub flushcourselogs {
1.352     www      4071:     &logthis('Flushing log buffers');
                   4072: #
                   4073: # course logs
                   4074: # This is a log of all transactions in a course, which can be used
                   4075: # for data mining purposes
                   4076: #
                   4077: # It also collects the courseid database, which lists last transaction
                   4078: # times and course titles for all courseids
                   4079: #
                   4080:     my %courseidbuffer=();
1.921     raeburn  4081:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4082:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4083: 		          &escape($courselogs{$crsid}),
                   4084: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4085: 	    delete $courselogs{$crsid};
                   4086:         } else {
                   4087:             &logthis('Failed to flush log buffer for '.$crsid);
                   4088:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4089:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4090:                         " exceeded maximum size, deleting.</font>");
                   4091:                delete $courselogs{$crsid};
                   4092:             }
1.352     www      4093:         }
1.920     raeburn  4094:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4095:             'description' => $coursedescrbuf{$crsid},
                   4096:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4097:             'type'        => $coursetypebuf{$crsid},
                   4098:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4099:         };
1.191     harris41 4100:     }
1.352     www      4101: #
                   4102: # Write course id database (reverse lookup) to homeserver of courses 
                   4103: # Is used in pickcourse
                   4104: #
1.840     albertel 4105:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4106:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4107:                                     $courseidbuffer{$crs_home},
                   4108:                                     $crs_home,'timeonly');
1.352     www      4109:     }
                   4110: #
                   4111: # File accesses
                   4112: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4113: #
1.449     matthew  4114:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4115:         if ($entry =~ /___count$/) {
                   4116:             my ($dom,$name);
1.807     albertel 4117:             ($dom,$name,undef)=
1.811     albertel 4118: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4119:             if (! defined($dom) || $dom eq '' || 
                   4120:                 ! defined($name) || $name eq '') {
1.620     albertel 4121:                 my $cid = $env{'request.course.id'};
                   4122:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4123:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4124:             }
1.450     matthew  4125:             my $value = $accesshash{$entry};
                   4126:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4127:             my %temphash=($url => $value);
1.449     matthew  4128:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4129:             if ($result eq 'ok') {
                   4130:                 delete $accesshash{$entry};
                   4131:             }
                   4132:         } else {
1.811     albertel 4133:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4134:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4135:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4136:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4137:                 delete $accesshash{$entry};
                   4138:             }
1.185     www      4139:         }
1.191     harris41 4140:     }
1.352     www      4141: #
                   4142: # Roles
                   4143: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4144: #
1.800     albertel 4145:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4146:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4147: 	    split(/\:/,$entry);
                   4148:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4149:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4150:                 $rudom,$runame) eq 'ok') {
                   4151: 	    delete $userrolehash{$entry};
                   4152:         }
                   4153:     }
1.662     raeburn  4154: #
1.1334    raeburn  4155: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4156: #
                   4157:     my %domrolebuffer = ();
1.1000    raeburn  4158:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4159:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4160:         if ($domrolebuffer{$rudom}) {
                   4161:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4162:                       '='.&escape($domainrolehash{$entry});
                   4163:         } else {
                   4164:             $domrolebuffer{$rudom}.=&escape($entry).
                   4165:                       '='.&escape($domainrolehash{$entry});
                   4166:         }
                   4167:         delete $domainrolehash{$entry};
                   4168:     }
                   4169:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4170: 	my %servers;
                   4171: 	if (defined(&domain($dom,'primary'))) {
                   4172: 	    my $primary=&domain($dom,'primary');
                   4173: 	    my $hostname=&hostname($primary);
                   4174: 	    $servers{$primary} = $hostname;
                   4175: 	} else { 
                   4176: 	    %servers = &get_servers($dom,'library');
                   4177: 	}
1.841     albertel 4178: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4179: 	    if (&reply('domroleput:'.$dom.':'.
                   4180: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4181: 		last;
                   4182: 	    } else {  
1.841     albertel 4183: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4184: 	    }
1.662     raeburn  4185:         }
                   4186:     }
1.186     www      4187:     $dumpcount++;
1.157     www      4188: }
                   4189: 
                   4190: sub courselog {
                   4191:     my $what=shift;
1.158     www      4192:     $what=time.':'.$what;
1.620     albertel 4193:     unless ($env{'request.course.id'}) { return ''; }
                   4194:     $coursedombuf{$env{'request.course.id'}}=
                   4195:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4196:     $coursenumbuf{$env{'request.course.id'}}=
                   4197:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4198:     $coursehombuf{$env{'request.course.id'}}=
                   4199:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4200:     $coursedescrbuf{$env{'request.course.id'}}=
                   4201:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4202:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4203:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4204:     $courseownerbuf{$env{'request.course.id'}}=
                   4205:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4206:     $coursetypebuf{$env{'request.course.id'}}=
                   4207:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4208:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4209: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4210:     } else {
1.620     albertel 4211: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4212:     }
1.620     albertel 4213:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4214: 	&flushcourselogs();
                   4215:     }
1.158     www      4216: }
                   4217: 
                   4218: sub courseacclog {
                   4219:     my $fnsymb=shift;
1.620     albertel 4220:     unless ($env{'request.course.id'}) { return ''; }
                   4221:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4222:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4223:         $what.=':POST';
1.583     matthew  4224:         # FIXME: Probably ought to escape things....
1.800     albertel 4225: 	foreach my $key (keys(%env)) {
                   4226:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4227:                 my $formitem = $1;
                   4228:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4229:                     $what.=':'.$formitem.'='.$env{$key};
                   4230:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4231:                     $what.=':'.$formitem.'='.$env{$key};
                   4232:                 }
1.158     www      4233:             }
1.191     harris41 4234:         }
1.583     matthew  4235:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4236:         # FIXME: We should not be depending on a form parameter that someone
                   4237:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4238:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4239:             $what.= ':POST';
                   4240:             # FIXME: Probably ought to escape things....
                   4241:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4242:                                  'crsdiscuss') {
1.620     albertel 4243:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4244:             }
                   4245:         }
1.158     www      4246:     }
                   4247:     &courselog($what);
1.149     www      4248: }
                   4249: 
1.185     www      4250: sub countacc {
                   4251:     my $url=&declutter(shift);
1.458     matthew  4252:     return if (! defined($url) || $url eq '');
1.620     albertel 4253:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4254: #
                   4255: # Mark that this url was used in this course
                   4256: #
1.620     albertel 4257:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4258: #
                   4259: # Increase the access count for this resource in this child process
                   4260: #
1.281     www      4261:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4262:     $accesshash{$key}++;
1.185     www      4263: }
1.349     www      4264: 
1.361     www      4265: sub linklog {
                   4266:     my ($from,$to)=@_;
                   4267:     $from=&declutter($from);
                   4268:     $to=&declutter($to);
                   4269:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4270:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4271: }
1.1160    www      4272: 
                   4273: sub statslog {
                   4274:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4275:     if ($users<2) { return; }
                   4276:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4277:             'course'       => $env{'request.course.id'},
                   4278:             'sections'     => '"all"',
                   4279:             'num_students' => $users,
                   4280:             'part'         => $part,
                   4281:             'symb'         => $symb,
                   4282:             'mean_tries'   => $av_attempts,
                   4283:             'deg_of_diff'  => $degdiff});
                   4284:     foreach my $key (keys(%dynstore)) {
                   4285:         $accesshash{$key}=$dynstore{$key};
                   4286:     }
                   4287: }
1.361     www      4288:   
1.349     www      4289: sub userrolelog {
                   4290:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4291:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4292:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4293:        $userrolehash
                   4294:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4295:                     =$tend.':'.$tstart;
1.662     raeburn  4296:     }
1.1169    droeschl 4297:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4298:        $userrolehash
                   4299:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4300:                     =$tend.':'.$tstart;
                   4301:     }
1.1334    raeburn  4302:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4303:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4304:        $domainrolehash
                   4305:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4306:                     = $tend.':'.$tstart;
                   4307:     }
1.351     www      4308: }
                   4309: 
1.957     raeburn  4310: sub courserolelog {
                   4311:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4312:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4313:         my $cdom = $1;
                   4314:         my $cnum = $2;
                   4315:         my $sec = $3;
                   4316:         my $namespace = 'rolelog';
                   4317:         my %storehash = (
                   4318:                            role    => $trole,
                   4319:                            start   => $tstart,
                   4320:                            end     => $tend,
                   4321:                            selfenroll => $selfenroll,
                   4322:                            context    => $context,
                   4323:                         );
                   4324:         if ($trole eq 'gr') {
                   4325:             $namespace = 'groupslog';
                   4326:             $storehash{'group'} = $sec;
                   4327:         } else {
                   4328:             $storehash{'section'} = $sec;
                   4329:         }
1.1188    raeburn  4330:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4331:                    $domain,$cnum,$cdom);
1.1184    raeburn  4332:         if (($trole ne 'st') || ($sec ne '')) {
                   4333:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4334:         }
                   4335:     }
                   4336:     return;
                   4337: }
                   4338: 
1.1184    raeburn  4339: sub domainrolelog {
                   4340:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4341:     if ($area =~ m{^/($match_domain)/$}) {
                   4342:         my $cdom = $1;
                   4343:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4344:         my $namespace = 'rolelog';
                   4345:         my %storehash = (
                   4346:                            role    => $trole,
                   4347:                            start   => $tstart,
                   4348:                            end     => $tend,
                   4349:                            context => $context,
                   4350:                         );
1.1188    raeburn  4351:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4352:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4353:     }
                   4354:     return;
                   4355: 
                   4356: }
                   4357: 
                   4358: sub coauthorrolelog {
                   4359:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4360:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4361:         my $audom = $1;
                   4362:         my $auname = $2;
                   4363:         my $namespace = 'rolelog';
                   4364:         my %storehash = (
                   4365:                            role    => $trole,
                   4366:                            start   => $tstart,
                   4367:                            end     => $tend,
                   4368:                            context => $context,
                   4369:                         );
1.1188    raeburn  4370:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4371:                    $domain,$auname,$audom);
1.1184    raeburn  4372:     }
                   4373:     return;
                   4374: }
                   4375: 
1.351     www      4376: sub get_course_adv_roles {
1.948     raeburn  4377:     my ($cid,$codes) = @_;
1.620     albertel 4378:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4379:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4380:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4381:     my %nothide=();
1.800     albertel 4382:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4383:         if ($user !~ /:/) {
                   4384: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4385:         } else {
                   4386:             $nothide{$user}=1;
                   4387:         }
1.470     www      4388:     }
1.1219    raeburn  4389:     my @possdoms = ($coursehash{'domain'});
                   4390:     if ($coursehash{'checkforpriv'}) {
                   4391:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4392:     }
1.351     www      4393:     my %returnhash=();
                   4394:     my %dumphash=
                   4395:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4396:     my $now=time;
1.997     raeburn  4397:     my %privileged;
1.1000    raeburn  4398:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4399: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4400:         if (($tstart) && ($tstart<0)) { next; }
                   4401:         if (($tend) && ($tend<$now)) { next; }
                   4402:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4403:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4404: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4405:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4406:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4407: 	if ($role eq 'cr') { next; }
1.948     raeburn  4408:         if ($codes) {
                   4409:             if ($section) { $role .= ':'.$section; }
                   4410:             if ($returnhash{$role}) {
                   4411:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4412:             } else {
                   4413:                 $returnhash{$role}=$username.':'.$domain;
                   4414:             }
1.351     www      4415:         } else {
1.988     raeburn  4416:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4417:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4418:             if ($returnhash{$key}) {
                   4419: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4420:             } else {
                   4421:                 $returnhash{$key}=$username.':'.$domain;
                   4422:             }
1.351     www      4423:         }
1.948     raeburn  4424:     }
1.400     www      4425:     return %returnhash;
                   4426: }
                   4427: 
                   4428: sub get_my_roles {
1.937     raeburn  4429:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4430:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4431:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4432:     my (%dumphash,%nothide);
1.1086    raeburn  4433:     if ($context eq 'userroles') {
1.1166    raeburn  4434:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4435:     } else {
1.1219    raeburn  4436:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4437:         if ($hidepriv) {
                   4438:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4439:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4440:                 if ($user !~ /:/) {
                   4441:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4442:                 } else {
                   4443:                     $nothide{$user} = 1;
                   4444:                 }
                   4445:             }
                   4446:         }
1.858     raeburn  4447:     }
1.400     www      4448:     my %returnhash=();
                   4449:     my $now=time;
1.999     raeburn  4450:     my %privileged;
1.800     albertel 4451:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4452:         my ($role,$tend,$tstart);
                   4453:         if ($context eq 'userroles') {
1.1149    raeburn  4454:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4455: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4456:         } else {
                   4457:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4458:         }
1.400     www      4459:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4460:         my $status = 'active';
1.939     raeburn  4461:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4462:             $status = 'previous';
                   4463:         } 
                   4464:         if (($tstart) && ($now<$tstart)) {
                   4465:             $status = 'future';
                   4466:         }
                   4467:         if (ref($types) eq 'ARRAY') {
                   4468:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4469:                 next;
                   4470:             } 
                   4471:         } else {
                   4472:             if ($status ne 'active') {
                   4473:                 next;
                   4474:             }
                   4475:         }
1.867     raeburn  4476:         my ($rolecode,$username,$domain,$section,$area);
                   4477:         if ($context eq 'userroles') {
1.1186    raeburn  4478:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4479:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4480:         } else {
                   4481:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4482:         }
1.832     raeburn  4483:         if (ref($roledoms) eq 'ARRAY') {
                   4484:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4485:                 next;
                   4486:             }
                   4487:         }
                   4488:         if (ref($roles) eq 'ARRAY') {
                   4489:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4490:                 if ($role =~ /^cr\//) {
                   4491:                     if (!grep(/^cr$/,@{$roles})) {
                   4492:                         next;
                   4493:                     }
1.1104    raeburn  4494:                 } elsif ($role =~ /^gr\//) {
                   4495:                     if (!grep(/^gr$/,@{$roles})) {
                   4496:                         next;
                   4497:                     }
1.922     raeburn  4498:                 } else {
                   4499:                     next;
                   4500:                 }
1.832     raeburn  4501:             }
1.867     raeburn  4502:         }
1.937     raeburn  4503:         if ($hidepriv) {
1.1219    raeburn  4504:             my @privroles = ('dc','su');
1.999     raeburn  4505:             if ($context eq 'userroles') {
1.1219    raeburn  4506:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4507:             } else {
1.1219    raeburn  4508:                 my $possdoms = [$domain];
                   4509:                 if (ref($roledoms) eq 'ARRAY') {
                   4510:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4511:                 }
1.1219    raeburn  4512:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4513:                     if (!$nothide{$username.':'.$domain}) {
                   4514:                         next;
                   4515:                     }
                   4516:                 }
1.937     raeburn  4517:             }
                   4518:         }
1.933     raeburn  4519:         if ($withsec) {
                   4520:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4521:                 $tstart.':'.$tend;
                   4522:         } else {
                   4523:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4524:         }
1.832     raeburn  4525:     }
1.373     www      4526:     return %returnhash;
1.399     www      4527: }
                   4528: 
1.1333    raeburn  4529: sub get_all_adhocroles {
                   4530:     my ($dom) = @_;
                   4531:     my @roles_by_num = ();
                   4532:     my %domdefaults = &get_domain_defaults($dom);
                   4533:     my (%description,%access_in_dom,%access_info);
                   4534:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4535:         my $count = 0;
                   4536:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4537:         my %ordered;
                   4538:         foreach my $role (sort(keys(%domcurrent))) {
                   4539:             my ($order,$desc,$access_in_dom);
                   4540:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4541:                 $order = $domcurrent{$role}{'order'};
                   4542:                 $desc = $domcurrent{$role}{'desc'};
                   4543:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4544:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4545:             }
                   4546:             if ($order eq '') {
                   4547:                 $order = $count;
                   4548:             }
                   4549:             $ordered{$order} = $role;
                   4550:             if ($desc ne '') {
                   4551:                 $description{$role} = $desc;
                   4552:             } else {
                   4553:                 $description{$role}= $role;
                   4554:             }
                   4555:             $count++;
                   4556:         }
                   4557:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4558:             push(@roles_by_num,$ordered{$item});
                   4559:         }
                   4560:     }
                   4561:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4562: }
                   4563: 
1.1332    raeburn  4564: sub get_my_adhocroles {
1.1333    raeburn  4565:     my ($cid,$checkreg) = @_;
                   4566:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4567:     if ($env{'request.course.id'} eq $cid) {
                   4568:         $cdom = $env{'course.'.$cid.'.domain'};
                   4569:         $cnum = $env{'course.'.$cid.'.num'};
                   4570:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4571:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4572:         $cdom = $1;
                   4573:         $cnum = $2;
                   4574:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4575:                                      $cdom,$cnum);
                   4576:     }
                   4577:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4578:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4579:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4580:         if ($rosterhash{$user} ne '') {
                   4581:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4582:             return ([],{}) if ($type eq 'auto');
                   4583:         }
                   4584:     }
                   4585:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4586:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4587:             my $then=$env{'user.login.time'};
                   4588:             my $update=$env{'user.update.time'};
1.1335    raeburn  4589:             if (!$update) {
                   4590:                 $update = $then;
                   4591:             }
                   4592:             my @liveroles;
1.1334    raeburn  4593:             foreach my $role ('dh','da') {
                   4594:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4595:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4596:                     my $limit = $update;
                   4597:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4598:                         $limit = $then;
                   4599:                     }
1.1335    raeburn  4600:                     my $activerole = 1;
                   4601:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4602:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4603:                     if ($activerole) {
                   4604:                         push(@liveroles,$role);
                   4605:                     }
1.1334    raeburn  4606:                 }
1.1332    raeburn  4607:             }
1.1335    raeburn  4608:             if (@liveroles) {
1.1332    raeburn  4609:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4610:                     my ($accessref,$accessinfo,%access_in_dom);
                   4611:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4612:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4613:                         if (@{$roles_by_num}) {
1.1332    raeburn  4614:                             my %settings;
                   4615:                             if ($env{'request.course.id'} eq $cid) {
                   4616:                                 foreach my $envkey (keys(%env)) {
                   4617:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4618:                                         $settings{$1} = $env{$envkey};
                   4619:                                     }
                   4620:                                 }
                   4621:                             } else {
                   4622:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4623:                             }
                   4624:                             my %setincrs;
                   4625:                             if ($settings{'internal.adhocaccess'}) {
                   4626:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4627:                             }
                   4628:                             my @statuses;
                   4629:                             if ($env{'environment.inststatus'}) {
                   4630:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4631:                             }
                   4632:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4633:                             if (ref($accessref) eq 'HASH') {
                   4634:                                 %access_in_dom = %{$accessref};
                   4635:                             }
                   4636:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4637:                                 my ($curraccess,@okstatus,@personnel);
                   4638:                                 if ($setincrs{$role}) {
                   4639:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4640:                                     if ($curraccess eq 'status') {
                   4641:                                         @okstatus = split(/\&/,$rest);
                   4642:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4643:                                         @personnel = split(/\&/,$rest);
                   4644:                                     }
                   4645:                                 } else {
                   4646:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4647:                                     if (ref($accessinfo) eq 'HASH') {
                   4648:                                         if ($curraccess eq 'status') {
                   4649:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4650:                                                 @okstatus = @{$accessinfo->{$role}};
                   4651:                                             }
                   4652:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4653:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4654:                                                 @personnel = @{$accessinfo->{$role}};
                   4655:                                             }
1.1332    raeburn  4656:                                         }
                   4657:                                     }
                   4658:                                 }
                   4659:                                 if ($curraccess eq 'none') {
                   4660:                                     next;
                   4661:                                 } elsif ($curraccess eq 'all') {
                   4662:                                     push(@possroles,$role);
1.1336    raeburn  4663:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4664:                                     if (grep(/^dh$/,@liveroles)) {
                   4665:                                         push(@possroles,$role);
                   4666:                                     } else {
                   4667:                                         next;
                   4668:                                     }
1.1336    raeburn  4669:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4670:                                     if (grep(/^da$/,@liveroles)) {
                   4671:                                         push(@possroles,$role);
                   4672:                                     } else {
                   4673:                                         next;
                   4674:                                     }
1.1332    raeburn  4675:                                 } elsif ($curraccess eq 'status') {
                   4676:                                     if (@okstatus) {
                   4677:                                         if (!@statuses) {
                   4678:                                             if (grep(/^default$/,@okstatus)) {
                   4679:                                                 push(@possroles,$role);
                   4680:                                             }
                   4681:                                         } else {
                   4682:                                             foreach my $status (@okstatus) {
                   4683:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4684:                                                     push(@possroles,$role);
                   4685:                                                     last;
                   4686:                                                 }
                   4687:                                             }
                   4688:                                         }
                   4689:                                     }
                   4690:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4691:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4692:                                         if ($curraccess eq 'exc') {
                   4693:                                             push(@possroles,$role);
                   4694:                                         }
                   4695:                                     } elsif ($curraccess eq 'inc') {
                   4696:                                         push(@possroles,$role);
                   4697:                                     }
                   4698:                                 }
                   4699:                             }
                   4700:                         }
                   4701:                     }
                   4702:                 }
                   4703:             }
                   4704:         }
                   4705:     }
1.1333    raeburn  4706:     unless (ref($description) eq 'HASH') {
                   4707:         if (ref($roles_by_num) eq 'ARRAY') {
                   4708:             my %desc;
                   4709:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4710:             $description = \%desc;
                   4711:         } else {
                   4712:             $description = {};
                   4713:         }
                   4714:     }
                   4715:     return (\@possroles,$description);
1.1332    raeburn  4716: }
                   4717: 
1.399     www      4718: # ----------------------------------------------------- Frontpage Announcements
                   4719: #
                   4720: #
                   4721: 
                   4722: sub postannounce {
                   4723:     my ($server,$text)=@_;
1.844     albertel 4724:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4725:     unless ($text=~/\w/) { $text=''; }
                   4726:     return &reply('setannounce:'.&escape($text),$server);
                   4727: }
                   4728: 
                   4729: sub getannounce {
1.448     albertel 4730: 
                   4731:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4732: 	my $announcement='';
1.800     albertel 4733: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4734: 	close($fh);
1.399     www      4735: 	if ($announcement=~/\w/) { 
                   4736: 	    return 
                   4737:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4738:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4739: 	} else {
                   4740: 	    return '';
                   4741: 	}
                   4742:     } else {
                   4743: 	return '';
                   4744:     }
1.351     www      4745: }
1.353     www      4746: 
                   4747: # ---------------------------------------------------------- Course ID routines
                   4748: # Deal with domain's nohist_courseid.db files
                   4749: #
                   4750: 
                   4751: sub courseidput {
1.921     raeburn  4752:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4753:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4754:     my $outcome;
                   4755:     if ($caller eq 'timeonly') {
                   4756:         my $cids = '';
                   4757:         foreach my $item (keys(%$storehash)) {
                   4758:             $cids.=&escape($item).'&';
                   4759:         }
                   4760:         $cids=~s/\&$//;
                   4761:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4762:                           $coursehome);       
                   4763:     } else {
                   4764:         my $items = '';
                   4765:         foreach my $item (keys(%$storehash)) {
                   4766:             $items.= &escape($item).'='.
                   4767:                      &freeze_escape($$storehash{$item}).'&';
                   4768:         }
                   4769:         $items=~s/\&$//;
                   4770:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4771:                           $coursehome);
1.918     raeburn  4772:     }
                   4773:     if ($outcome eq 'unknown_cmd') {
                   4774:         my $what;
                   4775:         foreach my $cid (keys(%$storehash)) {
                   4776:             $what .= &escape($cid).'=';
1.921     raeburn  4777:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4778:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4779:             }
                   4780:             $what =~ s/\:$/&/;
                   4781:         }
                   4782:         $what =~ s/\&$//;  
                   4783:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4784:     } else {
                   4785:         return $outcome;
                   4786:     }
1.353     www      4787: }
                   4788: 
                   4789: sub courseiddump {
1.921     raeburn  4790:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4791:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4792:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4793:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4794:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4795:     my $as_hash = 1;
                   4796:     my %returnhash;
                   4797:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4798:     my %libserv = &all_library();
                   4799:     foreach my $tryserver (keys(%libserv)) {
                   4800:         if ( (  $hostidflag == 1 
                   4801: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4802: 	     || (!defined($hostidflag)) ) {
                   4803: 
1.918     raeburn  4804: 	    if (($domfilter eq '') ||
                   4805: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 4806:                 my $rep;
                   4807:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   4808:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   4809:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   4810:                                 &escape($descfilter), &escape($instcodefilter), 
                   4811:                                 &escape($ownerfilter), &escape($coursefilter),
                   4812:                                 &escape($typefilter), &escape($regexp_ok), 
                   4813:                                 $as_hash, &escape($selfenrollonly), 
                   4814:                                 &escape($catfilter), $showhidden, $caller, 
                   4815:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   4816:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  4817:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   4818:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 4819:                 } else {
                   4820:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   4821:                              $sincefilter.':'.&escape($descfilter).':'.
                   4822:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   4823:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   4824:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   4825:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   4826:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   4827:                              &escape($cc_clone).':'.$cloneonly.':'.
                   4828:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  4829:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   4830:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 4831:                 }
                   4832:                      
1.918     raeburn  4833:                 my @pairs=split(/\&/,$rep);
                   4834:                 foreach my $item (@pairs) {
                   4835:                     my ($key,$value)=split(/\=/,$item,2);
                   4836:                     $key = &unescape($key);
                   4837:                     next if ($key =~ /^error: 2 /);
                   4838:                     my $result = &thaw_unescape($value);
                   4839:                     if (ref($result) eq 'HASH') {
                   4840:                         $returnhash{$key}=$result;
                   4841:                     } else {
1.921     raeburn  4842:                         my @responses = split(/:/,$value);
                   4843:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  4844:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  4845:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  4846:                         }
1.1008    raeburn  4847:                     }
1.353     www      4848:                 }
                   4849:             }
                   4850:         }
                   4851:     }
                   4852:     return %returnhash;
                   4853: }
                   4854: 
1.1055    raeburn  4855: sub courselastaccess {
                   4856:     my ($cdom,$cnum,$hostidref) = @_;
                   4857:     my %returnhash;
                   4858:     if ($cdom && $cnum) {
                   4859:         my $chome = &homeserver($cnum,$cdom);
                   4860:         if ($chome ne 'no_host') {
                   4861:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   4862:             &extract_lastaccess(\%returnhash,$rep);
                   4863:         }
                   4864:     } else {
                   4865:         if (!$cdom) { $cdom=''; }
                   4866:         my %libserv = &all_library();
                   4867:         foreach my $tryserver (keys(%libserv)) {
                   4868:             if (ref($hostidref) eq 'ARRAY') {
                   4869:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   4870:             } 
                   4871:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   4872:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   4873:                 &extract_lastaccess(\%returnhash,$rep);
                   4874:             }
                   4875:         }
                   4876:     }
                   4877:     return %returnhash;
                   4878: }
                   4879: 
                   4880: sub extract_lastaccess {
                   4881:     my ($returnhash,$rep) = @_;
                   4882:     if (ref($returnhash) eq 'HASH') {
                   4883:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   4884:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   4885:                  $rep eq '') {
                   4886:             my @pairs=split(/\&/,$rep);
                   4887:             foreach my $item (@pairs) {
                   4888:                 my ($key,$value)=split(/\=/,$item,2);
                   4889:                 $key = &unescape($key);
                   4890:                 next if ($key =~ /^error: 2 /);
                   4891:                 $returnhash->{$key} = &thaw_unescape($value);
                   4892:             }
                   4893:         }
                   4894:     }
                   4895:     return;
                   4896: }
                   4897: 
1.658     raeburn  4898: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  4899: 
                   4900: sub dcmailput {
1.685     raeburn  4901:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  4902:     my $status = &Apache::lonnet::critical(
1.740     www      4903:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   4904:        &escape($message),$server);
1.662     raeburn  4905:     return $status;
                   4906: }
                   4907: 
1.658     raeburn  4908: sub dcmaildump {
                   4909:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  4910:     my %returnhash=();
1.846     albertel 4911: 
                   4912:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  4913:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   4914:                                                          &escape($enddate).':';
                   4915: 	my @esc_senders=map { &escape($_)} @$senders;
                   4916: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 4917: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 4918:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  4919:             if (($key) && ($value)) {
                   4920:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  4921:             }
                   4922:         }
                   4923:     }
                   4924:     return %returnhash;
                   4925: }
1.662     raeburn  4926: # ---------------------------------------------------------- Domain roles
                   4927: 
                   4928: sub get_domain_roles {
                   4929:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  4930:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  4931:         $startdate = '.';
                   4932:     }
1.1018    raeburn  4933:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  4934:         $enddate = '.';
                   4935:     }
1.922     raeburn  4936:     my $rolelist;
                   4937:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  4938:         $rolelist = join('&',@{$roles});
1.922     raeburn  4939:     }
1.662     raeburn  4940:     my %personnel = ();
1.841     albertel 4941: 
                   4942:     my %servers = &get_servers($dom,'library');
                   4943:     foreach my $tryserver (keys(%servers)) {
                   4944: 	%{$personnel{$tryserver}}=();
                   4945: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   4946: 					    &escape($startdate).':'.
                   4947: 					    &escape($enddate).':'.
                   4948: 					    &escape($rolelist), $tryserver))) {
                   4949: 	    my ($key,$value) = split(/\=/,$line,2);
                   4950: 	    if (($key) && ($value)) {
                   4951: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   4952: 	    }
                   4953: 	}
1.662     raeburn  4954:     }
                   4955:     return %personnel;
                   4956: }
1.658     raeburn  4957: 
1.1332    raeburn  4958: sub get_active_domroles {
                   4959:     my ($dom,$roles) = @_;
                   4960:     return () unless (ref($roles) eq 'ARRAY');
                   4961:     my $now = time;
                   4962:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   4963:     my %domroles;
                   4964:     foreach my $server (keys(%dompersonnel)) {
                   4965:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   4966:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   4967:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   4968:         }
                   4969:     }
                   4970:     return %domroles;
                   4971: }
                   4972: 
1.1057    www      4973: # ----------------------------------------------------------- Interval timing 
1.149     www      4974: 
1.1153    www      4975: {
                   4976: # Caches needed for speedup of navmaps
                   4977: # We don't want to cache this for very long at all (5 seconds at most)
                   4978: # 
                   4979: # The user for whom we cache
                   4980: my $cachedkey='';
                   4981: # The cached times for this user
                   4982: my %cachedtimes=();
                   4983: # When this was last done
1.1282    raeburn  4984: my $cachedtime='';
1.1153    www      4985: 
                   4986: sub load_all_first_access {
1.1308    raeburn  4987:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      4988:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  4989:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   4990:         (!$ignorecache)) {
1.1154    raeburn  4991:         return;
                   4992:     }
                   4993:     $cachedtime=time;
                   4994:     $cachedkey=$uname.':'.$udom;
                   4995:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      4996: }
                   4997: 
1.504     albertel 4998: sub get_first_access {
1.1308    raeburn  4999:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5000:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5001:     if ($argsymb) { $symb=$argsymb; }
                   5002:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5003:     if ($argmap) { $map = $argmap; }
1.926     albertel 5004:     if ($type eq 'course') {
                   5005: 	$res='course';
                   5006:     } elsif ($type eq 'map') {
1.588     albertel 5007: 	$res=&symbread($map);
                   5008:     } else {
                   5009: 	$res=$symb;
                   5010:     }
1.1308    raeburn  5011:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5012:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5013: }
                   5014: 
                   5015: sub set_first_access {
1.1162    raeburn  5016:     my ($type,$interval)=@_;
1.790     albertel 5017:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5018:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5019:     if ($type eq 'course') {
                   5020: 	$res='course';
                   5021:     } elsif ($type eq 'map') {
1.588     albertel 5022: 	$res=&symbread($map);
                   5023:     } else {
                   5024: 	$res=$symb;
                   5025:     }
1.1153    www      5026:     $cachedkey='';
1.1162    raeburn  5027:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 5028:     if (!$firstaccess) {
1.1162    raeburn  5029:         my $start = time;
                   5030: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5031:                           $udom,$uname);
                   5032:         if ($putres eq 'ok') {
                   5033:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5034:                  $udom,$uname); 
                   5035:             &appenv(
                   5036:                      {
                   5037:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5038:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5039:                      }
                   5040:                   );
                   5041:         }
                   5042:         return $putres;
1.505     albertel 5043:     }
                   5044:     return 'already_set';
1.504     albertel 5045: }
1.1153    www      5046: }
1.1282    raeburn  5047: 
1.110     www      5048: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5049: 
                   5050: sub expirespread {
                   5051:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5052:     my $cid=$env{'request.course.id'}; 
1.110     www      5053:     if ($cid) {
                   5054:        my $now=time;
                   5055:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5056:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5057:                             $env{'course.'.$cid.'.num'}.
1.110     www      5058: 	        	    ':nohist_expirationdates:'.
                   5059:                             &escape($key).'='.$now,
1.620     albertel 5060:                             $env{'course.'.$cid.'.home'})
1.110     www      5061:     }
                   5062:     return 'ok';
1.14      www      5063: }
                   5064: 
1.109     www      5065: # ----------------------------------------------------- Devalidate Spreadsheets
                   5066: 
                   5067: sub devalidate {
1.325     www      5068:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5069:     my $cid=$env{'request.course.id'}; 
1.109     www      5070:     if ($cid) {
1.391     matthew  5071:         # delete the stored spreadsheets for
                   5072:         # - the student level sheet of this user in course's homespace
                   5073:         # - the assessment level sheet for this resource 
                   5074:         #   for this user in user's homespace
1.553     albertel 5075: 	# - current conditional state info
1.325     www      5076: 	my $key=$uname.':'.$udom.':';
1.109     www      5077:         my $status=
1.299     matthew  5078: 	    &del('nohist_calculatedsheets',
1.391     matthew  5079: 		 [$key.'studentcalc:'],
1.620     albertel 5080: 		 $env{'course.'.$cid.'.domain'},
                   5081: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5082: 		.' '.
                   5083: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5084: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5085:         unless ($status eq 'ok ok') {
                   5086:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5087:                     $uname.' at '.$udom.' for '.
1.109     www      5088: 		    $symb.': '.$status);
1.133     albertel 5089:         }
1.553     albertel 5090: 	&delenv('user.state.'.$cid);
1.109     www      5091:     }
                   5092: }
                   5093: 
1.265     albertel 5094: sub get_scalar {
                   5095:     my ($string,$end) = @_;
                   5096:     my $value;
                   5097:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5098: 	$value = $1;
                   5099:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5100: 	$value = $1;
                   5101:     }
                   5102:     return &unescape($value);
                   5103: }
                   5104: 
                   5105: sub array2str {
                   5106:   my (@array) = @_;
                   5107:   my $result=&arrayref2str(\@array);
                   5108:   $result=~s/^__ARRAY_REF__//;
                   5109:   $result=~s/__END_ARRAY_REF__$//;
                   5110:   return $result;
                   5111: }
                   5112: 
1.204     albertel 5113: sub arrayref2str {
                   5114:   my ($arrayref) = @_;
1.265     albertel 5115:   my $result='__ARRAY_REF__';
1.204     albertel 5116:   foreach my $elem (@$arrayref) {
1.265     albertel 5117:     if(ref($elem) eq 'ARRAY') {
                   5118:       $result.=&arrayref2str($elem).'&';
                   5119:     } elsif(ref($elem) eq 'HASH') {
                   5120:       $result.=&hashref2str($elem).'&';
                   5121:     } elsif(ref($elem)) {
                   5122:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5123:     } else {
                   5124:       $result.=&escape($elem).'&';
                   5125:     }
                   5126:   }
                   5127:   $result=~s/\&$//;
1.265     albertel 5128:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5129:   return $result;
                   5130: }
                   5131: 
1.168     albertel 5132: sub hash2str {
1.204     albertel 5133:   my (%hash) = @_;
                   5134:   my $result=&hashref2str(\%hash);
1.265     albertel 5135:   $result=~s/^__HASH_REF__//;
                   5136:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5137:   return $result;
                   5138: }
                   5139: 
                   5140: sub hashref2str {
                   5141:   my ($hashref)=@_;
1.265     albertel 5142:   my $result='__HASH_REF__';
1.800     albertel 5143:   foreach my $key (sort(keys(%$hashref))) {
                   5144:     if (ref($key) eq 'ARRAY') {
                   5145:       $result.=&arrayref2str($key).'=';
                   5146:     } elsif (ref($key) eq 'HASH') {
                   5147:       $result.=&hashref2str($key).'=';
                   5148:     } elsif (ref($key)) {
1.265     albertel 5149:       $result.='=';
1.800     albertel 5150:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5151:     } else {
1.1132    raeburn  5152: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5153:     }
                   5154: 
1.800     albertel 5155:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5156:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5157:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5158:       $result.=&hashref2str($hashref->{$key}).'&';
                   5159:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5160:        $result.='&';
1.800     albertel 5161:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5162:     } else {
1.800     albertel 5163:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5164:     }
                   5165:   }
1.168     albertel 5166:   $result=~s/\&$//;
1.265     albertel 5167:   $result .= '__END_HASH_REF__';
1.168     albertel 5168:   return $result;
                   5169: }
                   5170: 
                   5171: sub str2hash {
1.265     albertel 5172:     my ($string)=@_;
                   5173:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5174:     return %$hash;
                   5175: }
                   5176: 
                   5177: sub str2hashref {
1.168     albertel 5178:   my ($string) = @_;
1.265     albertel 5179: 
                   5180:   my %hash;
                   5181: 
                   5182:   if($string !~ /^__HASH_REF__/) {
                   5183:       if (! ($string eq '' || !defined($string))) {
                   5184: 	  $hash{'error'}='Not hash reference';
                   5185:       }
                   5186:       return (\%hash, $string);
                   5187:   }
                   5188: 
                   5189:   $string =~ s/^__HASH_REF__//;
                   5190: 
                   5191:   while($string !~ /^__END_HASH_REF__/) {
                   5192:       #key
                   5193:       my $key='';
                   5194:       if($string =~ /^__HASH_REF__/) {
                   5195:           ($key, $string)=&str2hashref($string);
                   5196:           if(defined($key->{'error'})) {
                   5197:               $hash{'error'}='Bad data';
                   5198:               return (\%hash, $string);
                   5199:           }
                   5200:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5201:           ($key, $string)=&str2arrayref($string);
                   5202:           if($key->[0] eq 'Array reference error') {
                   5203:               $hash{'error'}='Bad data';
                   5204:               return (\%hash, $string);
                   5205:           }
                   5206:       } else {
                   5207:           $string =~ s/^(.*?)=//;
1.267     albertel 5208: 	  $key=&unescape($1);
1.265     albertel 5209:       }
                   5210:       $string =~ s/^=//;
                   5211: 
                   5212:       #value
                   5213:       my $value='';
                   5214:       if($string =~ /^__HASH_REF__/) {
                   5215:           ($value, $string)=&str2hashref($string);
                   5216:           if(defined($value->{'error'})) {
                   5217:               $hash{'error'}='Bad data';
                   5218:               return (\%hash, $string);
                   5219:           }
                   5220:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5221:           ($value, $string)=&str2arrayref($string);
                   5222:           if($value->[0] eq 'Array reference error') {
                   5223:               $hash{'error'}='Bad data';
                   5224:               return (\%hash, $string);
                   5225:           }
                   5226:       } else {
                   5227: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5228:       }
                   5229:       $string =~ s/^&//;
                   5230: 
                   5231:       $hash{$key}=$value;
1.204     albertel 5232:   }
1.265     albertel 5233: 
                   5234:   $string =~ s/^__END_HASH_REF__//;
                   5235: 
                   5236:   return (\%hash, $string);
1.204     albertel 5237: }
                   5238: 
                   5239: sub str2array {
1.265     albertel 5240:     my ($string)=@_;
                   5241:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5242:     return @$array;
                   5243: }
                   5244: 
                   5245: sub str2arrayref {
1.204     albertel 5246:   my ($string) = @_;
1.265     albertel 5247:   my @array;
                   5248: 
                   5249:   if($string !~ /^__ARRAY_REF__/) {
                   5250:       if (! ($string eq '' || !defined($string))) {
                   5251: 	  $array[0]='Array reference error';
                   5252:       }
                   5253:       return (\@array, $string);
                   5254:   }
                   5255: 
                   5256:   $string =~ s/^__ARRAY_REF__//;
                   5257: 
                   5258:   while($string !~ /^__END_ARRAY_REF__/) {
                   5259:       my $value='';
                   5260:       if($string =~ /^__HASH_REF__/) {
                   5261:           ($value, $string)=&str2hashref($string);
                   5262:           if(defined($value->{'error'})) {
                   5263:               $array[0] ='Array reference error';
                   5264:               return (\@array, $string);
                   5265:           }
                   5266:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5267:           ($value, $string)=&str2arrayref($string);
                   5268:           if($value->[0] eq 'Array reference error') {
                   5269:               $array[0] ='Array reference error';
                   5270:               return (\@array, $string);
                   5271:           }
                   5272:       } else {
                   5273: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5274:       }
                   5275:       $string =~ s/^&//;
                   5276: 
                   5277:       push(@array, $value);
1.191     harris41 5278:   }
1.265     albertel 5279: 
                   5280:   $string =~ s/^__END_ARRAY_REF__//;
                   5281: 
                   5282:   return (\@array, $string);
1.168     albertel 5283: }
                   5284: 
1.167     albertel 5285: # -------------------------------------------------------------------Temp Store
                   5286: 
1.168     albertel 5287: sub tmpreset {
                   5288:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5289:   if (!$symb) {
                   5290:     $symb=&symbread();
1.620     albertel 5291:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5292:   }
                   5293:   $symb=escape($symb);
                   5294: 
1.620     albertel 5295:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5296:   $namespace=~s/\//\_/g;
                   5297:   $namespace=~s/\W//g;
                   5298: 
1.620     albertel 5299:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5300:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5301:   if ($domain eq 'public' && $stuname eq 'public') {
                   5302:       $stuname=$ENV{'REMOTE_ADDR'};
                   5303:   }
1.1117    foxr     5304:   my $path=LONCAPA::tempdir();
1.168     albertel 5305:   my %hash;
                   5306:   if (tie(%hash,'GDBM_File',
                   5307: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5308: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5309:     foreach my $key (keys(%hash)) {
1.180     albertel 5310:       if ($key=~ /:$symb/) {
1.168     albertel 5311: 	delete($hash{$key});
                   5312:       }
                   5313:     }
                   5314:   }
                   5315: }
                   5316: 
1.167     albertel 5317: sub tmpstore {
1.168     albertel 5318:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5319: 
                   5320:   if (!$symb) {
                   5321:     $symb=&symbread();
1.620     albertel 5322:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5323:   }
                   5324:   $symb=escape($symb);
                   5325: 
                   5326:   if (!$namespace) {
                   5327:     # I don't think we would ever want to store this for a course.
                   5328:     # it seems this will only be used if we don't have a course.
1.620     albertel 5329:     #$namespace=$env{'request.course.id'};
1.168     albertel 5330:     #if (!$namespace) {
1.620     albertel 5331:       $namespace=$env{'request.state'};
1.168     albertel 5332:     #}
                   5333:   }
                   5334:   $namespace=~s/\//\_/g;
                   5335:   $namespace=~s/\W//g;
1.620     albertel 5336:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5337:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5338:   if ($domain eq 'public' && $stuname eq 'public') {
                   5339:       $stuname=$ENV{'REMOTE_ADDR'};
                   5340:   }
1.168     albertel 5341:   my $now=time;
                   5342:   my %hash;
1.1117    foxr     5343:   my $path=LONCAPA::tempdir();
1.168     albertel 5344:   if (tie(%hash,'GDBM_File',
                   5345: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5346: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5347:     $hash{"version:$symb"}++;
                   5348:     my $version=$hash{"version:$symb"};
                   5349:     my $allkeys=''; 
                   5350:     foreach my $key (keys(%$storehash)) {
                   5351:       $allkeys.=$key.':';
1.591     albertel 5352:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5353:     }
                   5354:     $hash{"$version:$symb:timestamp"}=$now;
                   5355:     $allkeys.='timestamp';
                   5356:     $hash{"$version:keys:$symb"}=$allkeys;
                   5357:     if (untie(%hash)) {
                   5358:       return 'ok';
                   5359:     } else {
                   5360:       return "error:$!";
                   5361:     }
                   5362:   } else {
                   5363:     return "error:$!";
                   5364:   }
                   5365: }
1.167     albertel 5366: 
1.168     albertel 5367: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5368: 
1.168     albertel 5369: sub tmprestore {
                   5370:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5371: 
1.168     albertel 5372:   if (!$symb) {
                   5373:     $symb=&symbread();
1.620     albertel 5374:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5375:   }
                   5376:   $symb=escape($symb);
                   5377: 
1.620     albertel 5378:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5379: 
1.620     albertel 5380:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5381:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5382:   if ($domain eq 'public' && $stuname eq 'public') {
                   5383:       $stuname=$ENV{'REMOTE_ADDR'};
                   5384:   }
1.168     albertel 5385:   my %returnhash;
                   5386:   $namespace=~s/\//\_/g;
                   5387:   $namespace=~s/\W//g;
                   5388:   my %hash;
1.1117    foxr     5389:   my $path=LONCAPA::tempdir();
1.168     albertel 5390:   if (tie(%hash,'GDBM_File',
                   5391: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5392: 	  &GDBM_READER(),0640)) {
1.168     albertel 5393:     my $version=$hash{"version:$symb"};
                   5394:     $returnhash{'version'}=$version;
                   5395:     my $scope;
                   5396:     for ($scope=1;$scope<=$version;$scope++) {
                   5397:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5398:       my @keys=split(/:/,$vkeys);
                   5399:       my $key;
                   5400:       $returnhash{"$scope:keys"}=$vkeys;
                   5401:       foreach $key (@keys) {
1.591     albertel 5402: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5403: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5404:       }
                   5405:     }
1.168     albertel 5406:     if (!(untie(%hash))) {
                   5407:       return "error:$!";
                   5408:     }
                   5409:   } else {
                   5410:     return "error:$!";
                   5411:   }
                   5412:   return %returnhash;
1.167     albertel 5413: }
                   5414: 
1.9       www      5415: # ----------------------------------------------------------------------- Store
                   5416: 
                   5417: sub store {
1.1269    raeburn  5418:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5419:     my $home='';
                   5420: 
1.168     albertel 5421:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5422: 
1.213     www      5423:     $symb=&symbclean($symb);
1.122     albertel 5424:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5425: 
1.620     albertel 5426:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5427:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5428: 
                   5429:     &devalidate($symb,$stuname,$domain);
1.109     www      5430: 
                   5431:     $symb=escape($symb);
1.187     www      5432:     if (!$namespace) { 
1.620     albertel 5433:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5434:           return ''; 
                   5435:        } 
                   5436:     }
1.620     albertel 5437:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5438: 
                   5439:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5440:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5441: 
1.12      www      5442:     my $namevalue='';
1.800     albertel 5443:     foreach my $key (keys(%$storehash)) {
                   5444:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5445:     }
1.12      www      5446:     $namevalue=~s/\&$//;
1.187     www      5447:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5448:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5449: }
                   5450: 
1.47      www      5451: # -------------------------------------------------------------- Critical Store
                   5452: 
                   5453: sub cstore {
1.1269    raeburn  5454:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5455:     my $home='';
                   5456: 
1.168     albertel 5457:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5458: 
1.213     www      5459:     $symb=&symbclean($symb);
1.122     albertel 5460:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5461: 
1.620     albertel 5462:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5463:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5464: 
                   5465:     &devalidate($symb,$stuname,$domain);
1.109     www      5466: 
                   5467:     $symb=escape($symb);
1.187     www      5468:     if (!$namespace) { 
1.620     albertel 5469:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5470:           return ''; 
                   5471:        } 
                   5472:     }
1.620     albertel 5473:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5474: 
                   5475:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5476:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5477: 
1.47      www      5478:     my $namevalue='';
1.800     albertel 5479:     foreach my $key (keys(%$storehash)) {
                   5480:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5481:     }
1.47      www      5482:     $namevalue=~s/\&$//;
1.187     www      5483:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5484:     return critical
1.1269    raeburn  5485:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5486: }
                   5487: 
1.9       www      5488: # --------------------------------------------------------------------- Restore
                   5489: 
                   5490: sub restore {
1.124     www      5491:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5492:     my $home='';
                   5493: 
1.168     albertel 5494:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5495: 
1.122     albertel 5496:     if (!$symb) {
1.1224    raeburn  5497:         return if ($namespace eq 'courserequests');
                   5498:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5499:     } else {
1.1224    raeburn  5500:         unless ($namespace eq 'courserequests') {
                   5501:             $symb=&escape(&symbclean($symb));
                   5502:         }
1.122     albertel 5503:     }
1.188     www      5504:     if (!$namespace) { 
1.620     albertel 5505:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5506:           return ''; 
                   5507:        } 
                   5508:     }
1.620     albertel 5509:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5510:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5511:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5512:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5513: 
1.12      www      5514:     my %returnhash=();
1.800     albertel 5515:     foreach my $line (split(/\&/,$answer)) {
                   5516: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5517:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5518:     }
1.75      www      5519:     my $version;
                   5520:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5521:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5522:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5523:        }
1.75      www      5524:     }
1.13      www      5525:     return %returnhash;
1.34      www      5526: }
                   5527: 
                   5528: # ---------------------------------------------------------- Course Description
1.1118    foxr     5529: #
                   5530: #  
1.34      www      5531: 
                   5532: sub coursedescription {
1.731     albertel 5533:     my ($courseid,$args)=@_;
1.34      www      5534:     $courseid=~s/^\///;
1.49      www      5535:     $courseid=~s/\_/\//g;
1.34      www      5536:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5537:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5538:     my $normalid=$cdomain.'_'.$cnum;
                   5539:     # need to always cache even if we get errors otherwise we keep 
                   5540:     # trying and trying and trying to get the course description.
                   5541:     my %envhash=();
                   5542:     my %returnhash=();
1.731     albertel 5543:     
                   5544:     my $expiretime=600;
                   5545:     if ($env{'request.course.id'} eq $normalid) {
                   5546: 	$expiretime=120;
                   5547:     }
                   5548: 
                   5549:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5550:     if (!$args->{'freshen_cache'}
                   5551: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5552: 	foreach my $key (keys(%env)) {
                   5553: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5554: 	    my ($setting) = $1;
                   5555: 	    $returnhash{$setting} = $env{$key};
                   5556: 	}
                   5557: 	return %returnhash;
                   5558:     }
                   5559: 
1.1118    foxr     5560:     # get the data again
                   5561: 
1.731     albertel 5562:     if (!$args->{'one_time'}) {
                   5563: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5564:     }
1.811     albertel 5565: 
1.34      www      5566:     if ($chome ne 'no_host') {
1.302     albertel 5567:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5568:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5569: 	   my $username = $env{'user.name'}; # Defult username
                   5570: 	   if(defined $args->{'user'}) {
                   5571: 	       $username = $args->{'user'};
                   5572: 	   }
1.129     albertel 5573:            $returnhash{'home'}= $chome;
                   5574: 	   $returnhash{'domain'} = $cdomain;
                   5575: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5576:            if (!defined($returnhash{'type'})) {
                   5577:                $returnhash{'type'} = 'Course';
                   5578:            }
1.130     albertel 5579:            while (my ($name,$value) = each %returnhash) {
1.53      www      5580:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5581:            }
1.270     www      5582:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5583:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5584: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5585:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5586:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5587:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5588:        }
                   5589:     }
1.731     albertel 5590:     if (!$args->{'one_time'}) {
1.949     raeburn  5591: 	&appenv(\%envhash);
1.731     albertel 5592:     }
1.302     albertel 5593:     return %returnhash;
1.461     www      5594: }
                   5595: 
1.1080    raeburn  5596: sub update_released_required {
                   5597:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5598:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5599:         $cid = $env{'request.course.id'};
                   5600:         $cdom = $env{'course.'.$cid.'.domain'};
                   5601:         $cnum = $env{'course.'.$cid.'.num'};
                   5602:         $chome = $env{'course.'.$cid.'.home'};
                   5603:     }
                   5604:     if ($needsrelease) {
                   5605:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5606:         my $needsupdate;
                   5607:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5608:             $needsupdate = 1;
                   5609:         } else {
                   5610:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5611:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5612:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5613:                 $needsupdate = 1;
                   5614:             }
                   5615:         }
                   5616:         if ($needsupdate) {
                   5617:             my %needshash = (
                   5618:                              'internal.releaserequired' => $needsrelease,
                   5619:                             );
                   5620:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5621:             if ($putresult eq 'ok') {
                   5622:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5623:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5624:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5625:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5626:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5627:                 }
                   5628:             }
                   5629:         }
                   5630:     }
                   5631:     return;
                   5632: }
                   5633: 
1.461     www      5634: # -------------------------------------------------See if a user is privileged
                   5635: 
                   5636: sub privileged {
1.1219    raeburn  5637:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5638:     my $now = time;
1.1219    raeburn  5639:     my $roles;
                   5640:     if (ref($possroles) eq 'ARRAY') {
                   5641:         $roles = $possroles; 
                   5642:     } else {
                   5643:         $roles = ['dc','su'];
                   5644:     }
                   5645:     if (ref($possdomains) eq 'ARRAY') {
                   5646:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5647:         foreach my $dom (@{$possdomains}) {
                   5648:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5649:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5650:                 foreach my $role (@{$roles}) {
                   5651:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5652:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5653:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5654:                             return 1 unless (($end && $end < $now) ||
                   5655:                                              ($start && $start > $now));
                   5656:                         }
                   5657:                     }
                   5658:                 }
                   5659:             }
                   5660:         }
                   5661:     } else {
                   5662:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5663:         my $now = time;
1.1170    droeschl 5664: 
1.1275    musolffc 5665:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5666:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5667:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5668:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5669:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5670:             }
1.1219    raeburn  5671:         }
                   5672:     }
                   5673:     return 0;
                   5674: }
1.1170    droeschl 5675: 
1.1219    raeburn  5676: sub privileged_by_domain {
                   5677:     my ($domains,$roles) = @_;
                   5678:     my %privileged = ();
                   5679:     my $cachetime = 60*60*24;
                   5680:     my $now = time;
                   5681:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5682:         return %privileged;
                   5683:     }
                   5684:     foreach my $dom (@{$domains}) {
                   5685:         next if (ref($privileged{$dom}) eq 'HASH');
                   5686:         my $needroles;
                   5687:         foreach my $role (@{$roles}) {
                   5688:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5689:             if (defined($cached)) {
                   5690:                 if (ref($result) eq 'HASH') {
                   5691:                     $privileged{$dom}{$role} = $result;
                   5692:                 }
                   5693:             } else {
                   5694:                 $needroles = 1;
                   5695:             }
                   5696:         }
                   5697:         if ($needroles) {
                   5698:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5699:             $privileged{$dom} = {};
                   5700:             foreach my $server (keys(%dompersonnel)) {
                   5701:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5702:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5703:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5704:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5705:                         next if ($end && $end < $now);
                   5706:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5707:                             $dompersonnel{$server}{$item};
                   5708:                     }
                   5709:                 }
                   5710:             }
                   5711:             if (ref($privileged{$dom}) eq 'HASH') {
                   5712:                 foreach my $role (@{$roles}) {
                   5713:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5714:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5715:                     } else {
                   5716:                         my %hash = ();
                   5717:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5718:                     }
                   5719:                 }
                   5720:             }
                   5721:         }
                   5722:     }
                   5723:     return %privileged;
1.9       www      5724: }
1.1       albertel 5725: 
1.103     harris41 5726: # -------------------------------------------------------- Get user privileges
1.11      www      5727: 
                   5728: sub rolesinit {
1.1169    droeschl 5729:     my ($domain, $username) = @_;
                   5730:     my %userroles = ('user.login.time' => time);
                   5731:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5732: 
                   5733:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5734:     # also, blocking can be triggered by an activating timer
                   5735:     # it's saved in the user's %env.
                   5736:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5737:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5738:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5739:         %timerintchk, %timerintenv);
                   5740: 
1.1162    raeburn  5741:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5742:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5743:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5744:     }
1.1169    droeschl 5745: 
1.1162    raeburn  5746:     foreach my $key (keys(%timerinterval)) {
                   5747:         my ($cid,$rest) = split(/\0/,$key);
                   5748:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5749:     }
1.1169    droeschl 5750: 
1.11      www      5751:     my %allroles=();
1.1162    raeburn  5752:     my %allgroups=();
1.11      www      5753: 
1.1274    raeburn  5754:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5755:         my $role = $rolesdump{$area};
                   5756:         $area =~ s/\_\w\w$//;
                   5757: 
                   5758:         my ($trole, $tend, $tstart, $group_privs);
                   5759: 
                   5760:         if ($role =~ /^cr/) {
                   5761:         # Custom role, defined by a user 
                   5762:         # e.g., user.role.cr/msu/smith/mynewrole
                   5763:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5764:                 $trole = $1;
                   5765:                 ($tend, $tstart) = split('_', $2);
                   5766:             } else {
                   5767:                 $trole = $role;
                   5768:             }
                   5769:         } elsif ($role =~ m|^gr/|) {
                   5770:         # Role of member in a group, defined within a course/community
                   5771:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5772:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5773:             next if $tstart eq '-1';
                   5774:             ($trole, $group_privs) = split(/\//, $trole);
                   5775:             $group_privs = &unescape($group_privs);
                   5776:         } else {
                   5777:         # Just a normal role, defined in roles.tab
                   5778:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5779:         }
                   5780: 
                   5781:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5782:                  $username);
                   5783:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5784: 
                   5785:         # role expired or not available yet?
                   5786:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5787:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5788: 
                   5789:         next if $area eq '' or $trole eq '';
                   5790: 
                   5791:         my $spec = "$trole.$area";
                   5792:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5793: 
                   5794:         if ($trole =~ /^cr\//) {
                   5795:         # Custom role, defined by a user
                   5796:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5797:         } elsif ($trole eq 'gr') {
                   5798:         # Role of a member in a group, defined within a course/community
                   5799:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5800:             next;
                   5801:         } else {
                   5802:         # Normal role, defined in roles.tab
                   5803:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5804:         }
                   5805: 
                   5806:         my $cid = $tdomain.'_'.$trest;
                   5807:         unless ($firstaccchk{$cid}) {
                   5808:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   5809:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   5810:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   5811:                         $coursetimerstarts{$cid}{$item}; 
                   5812:                 }
                   5813:             }
                   5814:             $firstaccchk{$cid} = 1;
                   5815:         }
                   5816:         unless ($timerintchk{$cid}) {
                   5817:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   5818:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   5819:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   5820:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  5821:                 }
1.12      www      5822:             }
1.1169    droeschl 5823:             $timerintchk{$cid} = 1;
1.191     harris41 5824:         }
1.11      www      5825:     }
1.1169    droeschl 5826: 
1.1341    raeburn  5827:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   5828:                                                           \%allroles, \%allgroups);
1.1169    droeschl 5829:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  5830:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 5831: 
1.1162    raeburn  5832:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      5833: }
                   5834: 
1.567     raeburn  5835: sub set_arearole {
1.1215    raeburn  5836:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   5837:     unless ($nolog) {
1.567     raeburn  5838: # log the associated role with the area
1.1215    raeburn  5839:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   5840:     }
1.743     albertel 5841:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  5842: }
                   5843: 
                   5844: sub custom_roleprivs {
                   5845:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   5846:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  5847:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 5848:     if (&hostname($homsvr) ne '') {
1.567     raeburn  5849:         my ($rdummy,$roledef)=
                   5850:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   5851:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   5852:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   5853:             if (defined($syspriv)) {
1.1043    raeburn  5854:                 if ($trest =~ /^$match_community$/) {
                   5855:                     $syspriv =~ s/bre\&S//; 
                   5856:                 }
1.567     raeburn  5857:                 $$allroles{'cm./'}.=':'.$syspriv;
                   5858:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   5859:             }
                   5860:             if ($tdomain ne '') {
                   5861:                 if (defined($dompriv)) {
                   5862:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   5863:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   5864:                 }
                   5865:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  5866:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   5867:                         my $rolename = $1;
                   5868:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   5869:                     }
1.567     raeburn  5870:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   5871:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   5872:                 }
                   5873:             }
                   5874:         }
                   5875:     }
                   5876: }
                   5877: 
1.1332    raeburn  5878: sub course_adhocrole_privs {
                   5879:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   5880:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   5881:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   5882:         my (%currprivs,%storeprivs);
                   5883:         foreach my $item (split(/:/,$coursepriv)) {
                   5884:             my ($priv,$restrict) = split(/\&/,$item);
                   5885:             $currprivs{$priv} = $restrict;
                   5886:         }
                   5887:         my (%possadd,%possremove,%full);
                   5888:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   5889:             my ($priv,$restrict)=split(/\&/,$item);
                   5890:             $full{$priv} = $restrict;
                   5891:         }
                   5892:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   5893:              next if ($item eq '');
                   5894:              my ($rule,$rest) = split(/=/,$item);
                   5895:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   5896:              foreach my $priv (split(/:/,$rest)) {
                   5897:                  if ($priv ne '') {
                   5898:                      if ($rule eq 'off') {
                   5899:                          $possremove{$priv} = 1;
                   5900:                      } else {
                   5901:                          $possadd{$priv} = 1;
                   5902:                      }
                   5903:                  }
                   5904:              }
                   5905:          }
                   5906:          foreach my $priv (sort(keys(%full))) {
                   5907:              if (exists($currprivs{$priv})) {
                   5908:                  unless (exists($possremove{$priv})) {
                   5909:                      $storeprivs{$priv} = $currprivs{$priv};
                   5910:                  }
                   5911:              } elsif (exists($possadd{$priv})) {
                   5912:                  $storeprivs{$priv} = $full{$priv};
                   5913:              }
                   5914:          }
                   5915:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   5916:      }
                   5917:      return $coursepriv;
                   5918: }
                   5919: 
1.678     raeburn  5920: sub group_roleprivs {
                   5921:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   5922:     my $access = 1;
                   5923:     my $now = time;
                   5924:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   5925:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   5926:     if ($access) {
1.811     albertel 5927:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  5928:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   5929:     }
                   5930: }
1.567     raeburn  5931: 
                   5932: sub standard_roleprivs {
                   5933:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   5934:     if (defined($pr{$trole.':s'})) {
                   5935:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   5936:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   5937:     }
                   5938:     if ($tdomain ne '') {
                   5939:         if (defined($pr{$trole.':d'})) {
                   5940:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5941:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   5942:         }
                   5943:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   5944:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   5945:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   5946:         }
                   5947:     }
                   5948: }
                   5949: 
                   5950: sub set_userprivs {
1.1064    raeburn  5951:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  5952:     my $author=0;
                   5953:     my $adv=0;
1.1341    raeburn  5954:     my $rar=0;
1.678     raeburn  5955:     my %grouproles = ();
                   5956:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  5957:         my @groupkeys; 
1.1000    raeburn  5958:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  5959:             push(@groupkeys,$role);
                   5960:         }
                   5961:         if (ref($groups_roles) eq 'HASH') {
                   5962:             foreach my $key (keys(%{$groups_roles})) {
                   5963:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   5964:                     push(@groupkeys,$key);
                   5965:                 }
                   5966:             }
                   5967:         }
                   5968:         if (@groupkeys > 0) {
                   5969:             foreach my $role (@groupkeys) {
                   5970:                 my ($trole,$area,$sec,$extendedarea);
                   5971:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   5972:                     $trole = $1;
                   5973:                     $area = $2;
                   5974:                     $sec = $3;
                   5975:                     $extendedarea = $area.$sec;
                   5976:                     if (exists($$allgroups{$area})) {
                   5977:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   5978:                             my $spec = $trole.'.'.$extendedarea;
                   5979:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  5980:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  5981:                         }
1.678     raeburn  5982:                     }
                   5983:                 }
                   5984:             }
                   5985:         }
                   5986:     }
1.800     albertel 5987:     foreach my $group (keys(%grouproles)) {
                   5988:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  5989:     }
1.800     albertel 5990:     foreach my $role (keys(%{$allroles})) {
                   5991:         my %thesepriv;
1.941     raeburn  5992:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 5993:         foreach my $item (split(/:/,$$allroles{$role})) {
                   5994:             if ($item ne '') {
                   5995:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  5996:                 if ($restrictions eq '') {
                   5997:                     $thesepriv{$privilege}='F';
                   5998:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   5999:                     $thesepriv{$privilege}.=$restrictions;
                   6000:                 }
                   6001:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6002:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6003:             }
                   6004:         }
                   6005:         my $thesestr='';
1.1104    raeburn  6006:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6007: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6008: 	}
                   6009:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6010:     }
1.1341    raeburn  6011:     return ($author,$adv,$rar);
1.567     raeburn  6012: }
                   6013: 
1.994     raeburn  6014: sub role_status {
1.1104    raeburn  6015:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6016:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6017:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6018:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6019:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6020:             $$where = '/'.$two;
1.994     raeburn  6021:             $$trolecode=$$role.'.'.$$where;
                   6022:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6023:             $$tstatus='is';
1.1104    raeburn  6024:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6025:                 $$tstatus='future';
1.1034    raeburn  6026:                 if ($$tstart<$now) {
                   6027:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6028:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6029:                             my (%allroles,%allgroups,$group_privs,
                   6030:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6031:                             my %userroles = (
                   6032:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6033:                             );
1.1064    raeburn  6034:                             @rolecodes = ('cm'); 
1.1002    raeburn  6035:                             my $spec=$$role.'.'.$$where;
                   6036:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6037:                             if ($$role =~ /^cr\//) {
                   6038:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6039:                                 push(@rolecodes,'cr');
1.1002    raeburn  6040:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6041:                                 push(@rolecodes,$$role);
1.1002    raeburn  6042:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6043:                                                     $env{'user.name'});
1.1064    raeburn  6044:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6045:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6046:                                 $group_privs = &unescape($group_privs);
                   6047:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6048:                                 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  6049:                                 &get_groups_roles($tdomain,$trest,
                   6050:                                                   \%course_roles,\@rolecodes,
                   6051:                                                   \%groups_roles);
1.1002    raeburn  6052:                             } else {
1.1064    raeburn  6053:                                 push(@rolecodes,$$role);
1.1002    raeburn  6054:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6055:                             }
1.1341    raeburn  6056:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6057:                                                                    \%groups_roles);
1.1064    raeburn  6058:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6059:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6060:                         }
                   6061:                     }
1.1034    raeburn  6062:                     $$tstatus = 'is';
1.1002    raeburn  6063:                 }
1.994     raeburn  6064:             }
                   6065:             if ($$tend) {
1.1104    raeburn  6066:                 if ($$tend<$update) {
1.994     raeburn  6067:                     $$tstatus='expired';
                   6068:                 } elsif ($$tend<$now) {
                   6069:                     $$tstatus='will_not';
                   6070:                 }
                   6071:             }
                   6072:         }
                   6073:     }
                   6074: }
                   6075: 
1.1104    raeburn  6076: sub get_groups_roles {
                   6077:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6078:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6079:                   (ref($rolecodes) eq 'ARRAY') && 
                   6080:                   (ref($groups_roles) eq 'HASH')); 
                   6081:     if (keys(%{$cdom_courseroles}) > 0) {
                   6082:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6083:         if ($cdom ne '' && $cnum ne '') {
                   6084:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6085:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6086:                     my $crsrole = $1;
                   6087:                     my $crssec = $2;
                   6088:                     if ($crsrole =~ /^cr/) {
                   6089:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6090:                             push(@{$rolecodes},'cr');
                   6091:                         }
                   6092:                     } else {
                   6093:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6094:                             push(@{$rolecodes},$crsrole);
                   6095:                         }
                   6096:                     }
                   6097:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6098:                     if ($crssec ne '') {
                   6099:                         $rolekey .= "/$crssec";
                   6100:                     }
                   6101:                     $rolekey .= './';
                   6102:                     $groups_roles->{$rolekey} = $rolecodes;
                   6103:                 }
                   6104:             }
                   6105:         }
                   6106:     }
                   6107:     return;
                   6108: }
                   6109: 
                   6110: sub delete_env_groupprivs {
                   6111:     my ($where,$courseroles,$possroles) = @_;
                   6112:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6113:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6114:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6115:         %{$courseroles->{$udom}} =
                   6116:             &get_my_roles('','','userroles',['active'],
                   6117:                           $possroles,[$udom],1);
                   6118:     }
                   6119:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6120:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6121:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6122:             my $area = '/'.$cdom.'/'.$cnum;
                   6123:             my $privkey = "user.priv.$crsrole.$area";
                   6124:             if ($crssec ne '') {
                   6125:                 $privkey .= '/'.$crssec;
                   6126:             }
                   6127:             $privkey .= ".$area/$group";
                   6128:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6129:         }
                   6130:     }
                   6131:     return;
                   6132: }
                   6133: 
1.994     raeburn  6134: sub check_adhoc_privs {
1.1329    raeburn  6135:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6136:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6137:     if ($sec) {
                   6138:         $cckey .= '/'.$sec;
                   6139:     } 
1.1185    raeburn  6140:     my $setprivs;
1.994     raeburn  6141:     if ($env{$cckey}) {
                   6142:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6143:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6144:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6145:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6146:             $setprivs = 1;
1.994     raeburn  6147:         }
                   6148:     } else {
1.1330    raeburn  6149:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6150:         $setprivs = 1;
1.994     raeburn  6151:     }
1.1185    raeburn  6152:     return $setprivs;
1.994     raeburn  6153: }
                   6154: 
                   6155: sub set_adhoc_privileges {
1.1326    raeburn  6156: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6157:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6158:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6159:     if ($sec ne '') {
                   6160:         $area .= '/'.$sec;
                   6161:     }
1.994     raeburn  6162:     my $spec = $role.'.'.$area;
                   6163:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6164:                                   $env{'user.name'},1);
1.1326    raeburn  6165:     my %rolehash = ();
1.1332    raeburn  6166:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6167:         my $rolename = $1;
1.1326    raeburn  6168:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6169:         my %domdef = &get_domain_defaults($dcdom);
                   6170:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6171:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6172:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6173:             }
                   6174:         }
1.1326    raeburn  6175:     } else {
                   6176:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6177:     }
1.1341    raeburn  6178:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6179:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6180:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6181:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6182:         &appenv( {'request.role'        => $spec,
                   6183:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6184:                   'request.course.sec'  => $sec,
1.1088    raeburn  6185:                  }
                   6186:                );
                   6187:         my $tadv=0;
                   6188:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6189:         &appenv({'request.role.adv'    => $tadv});
                   6190:     }
1.994     raeburn  6191: }
                   6192: 
1.12      www      6193: # --------------------------------------------------------------- get interface
                   6194: 
                   6195: sub get {
1.131     albertel 6196:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6197:    my $items='';
1.800     albertel 6198:    foreach my $item (@$storearr) {
                   6199:        $items.=&escape($item).'&';
1.191     harris41 6200:    }
1.12      www      6201:    $items=~s/\&$//;
1.620     albertel 6202:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6203:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6204:    my $uhome=&homeserver($uname,$udomain);
                   6205: 
1.133     albertel 6206:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6207:    my @pairs=split(/\&/,$rep);
1.273     albertel 6208:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6209:      return @pairs;
                   6210:    }
1.15      www      6211:    my %returnhash=();
1.42      www      6212:    my $i=0;
1.800     albertel 6213:    foreach my $item (@$storearr) {
                   6214:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6215:       $i++;
1.191     harris41 6216:    }
1.15      www      6217:    return %returnhash;
1.27      www      6218: }
                   6219: 
                   6220: # --------------------------------------------------------------- del interface
                   6221: 
                   6222: sub del {
1.133     albertel 6223:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6224:    my $items='';
1.800     albertel 6225:    foreach my $item (@$storearr) {
                   6226:        $items.=&escape($item).'&';
1.191     harris41 6227:    }
1.984     neumanie 6228: 
1.27      www      6229:    $items=~s/\&$//;
1.620     albertel 6230:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6231:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6232:    my $uhome=&homeserver($uname,$udomain);
                   6233:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6234: }
                   6235: 
                   6236: # -------------------------------------------------------------- dump interface
                   6237: 
1.1180    droeschl 6238: sub unserialize {
                   6239:     my ($rep, $escapedkeys) = @_;
                   6240: 
                   6241:     return {} if $rep =~ /^error/;
                   6242: 
                   6243:     my %returnhash=();
1.1252    raeburn  6244: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6245: 	    my ($key, $value) = split(/=/, $item, 2);
                   6246: 	    $key = unescape($key) unless $escapedkeys;
                   6247: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6248: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6249: 	}
                   6250:     #return %returnhash;
                   6251:     return \%returnhash;
                   6252: }        
                   6253: 
                   6254: # see Lond::dump_with_regexp
                   6255: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6256: sub dump {
1.1180    droeschl 6257:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6258:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6259:     if (!$uname) { $uname=$env{'user.name'}; }
                   6260:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6261: 
1.1266    raeburn  6262:     if ($regexp) {
                   6263:         $regexp=&escape($regexp);
                   6264:     } else {
                   6265:         $regexp='.';
                   6266:     }
1.1180    droeschl 6267:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6268:         # user is hosted on this machine
1.1266    raeburn  6269:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6270:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6271:         return %{unserialize($reply, $escapedkeys)};
                   6272:     }
1.1166    raeburn  6273:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6274:     my @pairs=split(/\&/,$rep);
                   6275:     my %returnhash=();
1.1098    foxr     6276:     if (!($rep =~ /^error/ )) {
                   6277: 	foreach my $item (@pairs) {
                   6278: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6279:         $key = unescape($key) unless $escapedkeys;
                   6280:         #$key = &unescape($key);
1.1098    foxr     6281: 	    next if ($key =~ /^error: 2 /);
                   6282: 	    $returnhash{$key}=&thaw_unescape($value);
                   6283: 	}
1.755     albertel 6284:     }
                   6285:     return %returnhash;
1.407     www      6286: }
                   6287: 
1.1098    foxr     6288: 
1.717     albertel 6289: # --------------------------------------------------------- dumpstore interface
                   6290: 
                   6291: sub dumpstore {
                   6292:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6293:    # same as dump but keys must be escaped. They may contain colon separated
                   6294:    # lists of values that may themself contain colons (e.g. symbs).
                   6295:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6296: }
                   6297: 
1.407     www      6298: # -------------------------------------------------------------- keys interface
                   6299: 
                   6300: sub getkeys {
                   6301:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6302:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6303:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6304:    my $uhome=&homeserver($uname,$udomain);
                   6305:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6306:    my @keyarray=();
1.800     albertel 6307:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6308:       next if ($key =~ /^error: 2 /);
1.800     albertel 6309:       push(@keyarray,&unescape($key));
1.407     www      6310:    }
                   6311:    return @keyarray;
1.318     matthew  6312: }
                   6313: 
1.319     matthew  6314: # --------------------------------------------------------------- currentdump
                   6315: sub currentdump {
1.328     matthew  6316:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6317:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6318:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6319:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6320:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6321:    my $rep;
                   6322: 
                   6323:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6324:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6325:                    $courseid)));
                   6326:    } else {
                   6327:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6328:    }
                   6329: 
1.318     matthew  6330:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6331:    #
1.318     matthew  6332:    my %returnhash=();
1.319     matthew  6333:    #
1.1343    raeburn  6334:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6335:        # an old lond will not know currentdump
                   6336:        # Do a dump and make it look like a currentdump
1.822     albertel 6337:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6338:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6339:        my %hash = @tmp;
                   6340:        @tmp=();
1.424     matthew  6341:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6342:    } else {
                   6343:        my @pairs=split(/\&/,$rep);
1.800     albertel 6344:        foreach my $pair (@pairs) {
                   6345:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6346:            my ($symb,$param) = split(/:/,$key);
                   6347:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6348:                                                         &thaw_unescape($value);
1.319     matthew  6349:        }
1.191     harris41 6350:    }
1.12      www      6351:    return %returnhash;
1.424     matthew  6352: }
                   6353: 
                   6354: sub convert_dump_to_currentdump{
                   6355:     my %hash = %{shift()};
                   6356:     my %returnhash;
                   6357:     # Code ripped from lond, essentially.  The only difference
                   6358:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6359:     # we might run in to problems with parameter names =~ /^v\./
                   6360:     while (my ($key,$value) = each(%hash)) {
                   6361:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6362: 	$symb  = &unescape($symb);
                   6363: 	$param = &unescape($param);
1.424     matthew  6364:         next if ($v eq 'version' || $symb eq 'keys');
                   6365:         next if (exists($returnhash{$symb}) &&
                   6366:                  exists($returnhash{$symb}->{$param}) &&
                   6367:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6368:         $returnhash{$symb}->{$param}=$value;
                   6369:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6370:     }
                   6371:     #
                   6372:     # Remove all of the keys in the hashes which keep track of
                   6373:     # the version of the parameter.
                   6374:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6375:         # use a foreach because we are going to delete from the hash.
                   6376:         foreach my $key (keys(%$param_hash)) {
                   6377:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6378:         }
                   6379:     }
                   6380:     return \%returnhash;
1.12      www      6381: }
                   6382: 
1.627     albertel 6383: # ------------------------------------------------------ critical inc interface
                   6384: 
                   6385: sub cinc {
                   6386:     return &inc(@_,'critical');
                   6387: }
                   6388: 
1.449     matthew  6389: # --------------------------------------------------------------- inc interface
                   6390: 
                   6391: sub inc {
1.627     albertel 6392:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6393:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6394:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6395:     my $uhome=&homeserver($uname,$udomain);
                   6396:     my $items='';
                   6397:     if (! ref($store)) {
                   6398:         # got a single value, so use that instead
                   6399:         $items = &escape($store).'=&';
                   6400:     } elsif (ref($store) eq 'SCALAR') {
                   6401:         $items = &escape($$store).'=&';        
                   6402:     } elsif (ref($store) eq 'ARRAY') {
                   6403:         $items = join('=&',map {&escape($_);} @{$store});
                   6404:     } elsif (ref($store) eq 'HASH') {
                   6405:         while (my($key,$value) = each(%{$store})) {
                   6406:             $items.= &escape($key).'='.&escape($value).'&';
                   6407:         }
                   6408:     }
                   6409:     $items=~s/\&$//;
1.627     albertel 6410:     if ($critical) {
                   6411: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6412:     } else {
                   6413: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6414:     }
1.449     matthew  6415: }
                   6416: 
1.12      www      6417: # --------------------------------------------------------------- put interface
                   6418: 
                   6419: sub put {
1.134     albertel 6420:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6421:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6422:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6423:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6424:    my $items='';
1.800     albertel 6425:    foreach my $item (keys(%$storehash)) {
                   6426:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6427:    }
1.12      www      6428:    $items=~s/\&$//;
1.134     albertel 6429:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6430: }
                   6431: 
1.631     albertel 6432: # ------------------------------------------------------------ newput interface
                   6433: 
                   6434: sub newput {
                   6435:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6436:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6437:    if (!$uname) { $uname=$env{'user.name'}; }
                   6438:    my $uhome=&homeserver($uname,$udomain);
                   6439:    my $items='';
                   6440:    foreach my $key (keys(%$storehash)) {
                   6441:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6442:    }
                   6443:    $items=~s/\&$//;
                   6444:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6445: }
                   6446: 
                   6447: # ---------------------------------------------------------  putstore interface
                   6448: 
1.524     raeburn  6449: sub putstore {
1.1269    raeburn  6450:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6451:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6452:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6453:    my $uhome=&homeserver($uname,$udomain);
                   6454:    my $items='';
1.715     albertel 6455:    foreach my $key (keys(%$storehash)) {
                   6456:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6457:    }
1.715     albertel 6458:    $items=~s/\&$//;
1.716     albertel 6459:    my $esc_symb=&escape($symb);
                   6460:    my $esc_v=&escape($version);
1.715     albertel 6461:    my $reply =
1.716     albertel 6462:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6463: 	      $uhome);
1.1269    raeburn  6464:    if (($tolog) && ($reply eq 'ok')) {
                   6465:        my $namevalue='';
                   6466:        foreach my $key (keys(%{$storehash})) {
                   6467:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6468:        }
                   6469:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6470:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6471:                      '&version='.$esc_v.
                   6472:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6473:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6474:    }
1.715     albertel 6475:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6476:        # gfall back to way things use to be done
1.715     albertel 6477:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6478: 			    $uname);
1.524     raeburn  6479:    }
1.715     albertel 6480:    return $reply;
                   6481: }
                   6482: 
                   6483: sub old_putstore {
1.716     albertel 6484:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6485:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6486:     if (!$uname) { $uname=$env{'user.name'}; }
                   6487:     my $uhome=&homeserver($uname,$udomain);
                   6488:     my %newstorehash;
1.800     albertel 6489:     foreach my $item (keys(%$storehash)) {
                   6490: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6491: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6492:     }
                   6493:     my $items='';
                   6494:     my %allitems = ();
1.800     albertel 6495:     foreach my $item (keys(%newstorehash)) {
                   6496: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6497: 	    my $key = $1.':keys:'.$2;
                   6498: 	    $allitems{$key} .= $3.':';
                   6499: 	}
1.800     albertel 6500: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6501:     }
1.800     albertel 6502:     foreach my $item (keys(%allitems)) {
                   6503: 	$allitems{$item} =~ s/\:$//;
                   6504: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6505:     }
                   6506:     $items=~s/\&$//;
                   6507:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6508: }
                   6509: 
1.47      www      6510: # ------------------------------------------------------ critical put interface
                   6511: 
                   6512: sub cput {
1.134     albertel 6513:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6514:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6515:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6516:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6517:    my $items='';
1.800     albertel 6518:    foreach my $item (keys(%$storehash)) {
                   6519:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6520:    }
1.47      www      6521:    $items=~s/\&$//;
1.134     albertel 6522:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6523: }
                   6524: 
                   6525: # -------------------------------------------------------------- eget interface
                   6526: 
                   6527: sub eget {
1.133     albertel 6528:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6529:    my $items='';
1.800     albertel 6530:    foreach my $item (@$storearr) {
                   6531:        $items.=&escape($item).'&';
1.191     harris41 6532:    }
1.12      www      6533:    $items=~s/\&$//;
1.620     albertel 6534:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6535:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6536:    my $uhome=&homeserver($uname,$udomain);
                   6537:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6538:    my @pairs=split(/\&/,$rep);
                   6539:    my %returnhash=();
1.42      www      6540:    my $i=0;
1.800     albertel 6541:    foreach my $item (@$storearr) {
                   6542:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6543:       $i++;
1.191     harris41 6544:    }
1.12      www      6545:    return %returnhash;
                   6546: }
                   6547: 
1.667     albertel 6548: # ------------------------------------------------------------ tmpput interface
                   6549: sub tmpput {
1.802     raeburn  6550:     my ($storehash,$server,$context)=@_;
1.667     albertel 6551:     my $items='';
1.800     albertel 6552:     foreach my $item (keys(%$storehash)) {
                   6553: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6554:     }
                   6555:     $items=~s/\&$//;
1.802     raeburn  6556:     if (defined($context)) {
                   6557:         $items .= ':'.&escape($context);
                   6558:     }
1.667     albertel 6559:     return &reply("tmpput:$items",$server);
                   6560: }
                   6561: 
                   6562: # ------------------------------------------------------------ tmpget interface
                   6563: sub tmpget {
1.688     albertel 6564:     my ($token,$server)=@_;
                   6565:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6566:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6567:     my %returnhash;
1.1328    raeburn  6568:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6569:         return %returnhash;
                   6570:     }
1.667     albertel 6571:     foreach my $item (split(/\&/,$rep)) {
                   6572: 	my ($key,$value)=split(/=/,$item);
                   6573: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6574:     }
                   6575:     return %returnhash;
                   6576: }
                   6577: 
1.1113    raeburn  6578: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6579: sub tmpdel {
                   6580:     my ($token,$server)=@_;
                   6581:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6582:     return &reply("tmpdel:$token",$server);
                   6583: }
                   6584: 
1.1198    raeburn  6585: # ------------------------------------------------------------ get_timebased_id 
                   6586: 
                   6587: sub get_timebased_id {
                   6588:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6589:         $maxtries) = @_;
                   6590:     my ($newid,$error,$dellock);
                   6591:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6592:         return ('','ok','invalid call to get suffix');
                   6593:     }
                   6594: 
                   6595: # set defaults for any optional args for which values were not supplied
                   6596:     if ($who eq '') {
                   6597:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6598:     }
                   6599:     if (!$locktries) {
                   6600:         $locktries = 3;
                   6601:     }
                   6602:     if (!$maxtries) {
                   6603:         $maxtries = 10;
                   6604:     }
                   6605:     
                   6606:     if (($cdom eq '') || ($cnum eq '')) {
                   6607:         if ($env{'request.course.id'}) {
                   6608:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6609:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6610:         }
                   6611:         if (($cdom eq '') || ($cnum eq '')) {
                   6612:             return ('','ok','call to get suffix not in course context');
                   6613:         }
                   6614:     }
                   6615: 
                   6616: # construct locking item
                   6617:     my $lockhash = {
                   6618:                       $prefix."\0".'locked_'.$keyid => $who,
                   6619:                    };
                   6620:     my $tries = 0;
                   6621: 
                   6622: # attempt to get lock on nohist_$namespace file
                   6623:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6624:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6625:         $tries ++;
                   6626:         sleep 1;
                   6627:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6628:     }
                   6629: 
                   6630: # attempt to get unique identifier, based on current timestamp
                   6631:     if ($gotlock eq 'ok') {
                   6632:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6633:         my $id = time;
                   6634:         $newid = $id;
1.1268    raeburn  6635:         if ($idtype eq 'addcode') {
                   6636:             $newid .= &sixnum_code();
                   6637:         }
1.1198    raeburn  6638:         my $idtries = 0;
                   6639:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6640:             if ($idtype eq 'concat') {
                   6641:                 $newid = $id.$idtries;
1.1268    raeburn  6642:             } elsif ($idtype eq 'addcode') {
                   6643:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6644:             } else {
                   6645:                 $newid ++;
                   6646:             }
                   6647:             $idtries ++;
                   6648:         }
                   6649:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6650:             my %new_item =  (
                   6651:                               $prefix."\0".$newid => $who,
                   6652:                             );
                   6653:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6654:                                                  $cdom,$cnum);
                   6655:             if ($putresult ne 'ok') {
                   6656:                 undef($newid);
                   6657:                 $error = 'error saving new item: '.$putresult;
                   6658:             }
                   6659:         } else {
1.1268    raeburn  6660:              undef($newid);
1.1198    raeburn  6661:              $error = ('error: no unique suffix available for the new item ');
                   6662:         }
                   6663: #  remove lock
                   6664:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6665:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6666:     } else {
                   6667:         $error = "error: could not obtain lockfile\n";
                   6668:         $dellock = 'ok';
1.1276    raeburn  6669:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6670:             $dellock = 'nolock';
                   6671:         }
1.1198    raeburn  6672:     }
                   6673:     return ($newid,$dellock,$error);
                   6674: }
                   6675: 
1.1268    raeburn  6676: sub sixnum_code {
                   6677:     my $code;
                   6678:     for (0..6) {
                   6679:         $code .= int( rand(9) );
                   6680:     }
                   6681:     return $code;
                   6682: }
                   6683: 
1.765     albertel 6684: # -------------------------------------------------- portfolio access checking
                   6685: 
                   6686: sub portfolio_access {
1.1270    raeburn  6687:     my ($requrl,$clientip) = @_;
1.765     albertel 6688:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6689:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6690:     if ($result) {
                   6691:         my %setters;
                   6692:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6693:             my ($startblock,$endblock) =
                   6694:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6695:             if ($startblock && $endblock) {
                   6696:                 return 'B';
                   6697:             }
                   6698:         } else {
                   6699:             my ($startblock,$endblock) =
                   6700:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6701:             if ($startblock && $endblock) {
                   6702:                 return 'B';
                   6703:             }
                   6704:         }
                   6705:     }
1.765     albertel 6706:     if ($result eq 'ok') {
1.766     albertel 6707:        return 'F';
1.765     albertel 6708:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6709:        return 'A';
1.765     albertel 6710:     }
1.766     albertel 6711:     return '';
1.765     albertel 6712: }
                   6713: 
                   6714: sub get_portfolio_access {
1.1270    raeburn  6715:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6716: 
                   6717:     if (!ref($access_hash)) {
                   6718: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6719: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6720: 						   $file_name);
                   6721: 	$access_hash = $access_controls{$file_name};
                   6722:     }
                   6723: 
1.1270    raeburn  6724:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6725:     my $now = time;
                   6726:     if (ref($access_hash) eq 'HASH') {
                   6727:         foreach my $key (keys(%{$access_hash})) {
                   6728:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6729:             if ($start > $now) {
                   6730:                 next;
                   6731:             }
                   6732:             if ($end && $end<$now) {
                   6733:                 next;
                   6734:             }
                   6735:             if ($scope eq 'public') {
                   6736:                 $public = $key;
                   6737:                 last;
                   6738:             } elsif ($scope eq 'guest') {
                   6739:                 $guest = $key;
                   6740:             } elsif ($scope eq 'domains') {
                   6741:                 push(@domains,$key);
                   6742:             } elsif ($scope eq 'users') {
                   6743:                 push(@users,$key);
                   6744:             } elsif ($scope eq 'course') {
                   6745:                 push(@courses,$key);
                   6746:             } elsif ($scope eq 'group') {
                   6747:                 push(@groups,$key);
1.1270    raeburn  6748:             } elsif ($scope eq 'ip') {
                   6749:                 push(@ips,$key);
1.765     albertel 6750:             }
                   6751:         }
                   6752:         if ($public) {
                   6753:             return 'ok';
1.1270    raeburn  6754:         } elsif (@ips > 0) {
                   6755:             my $allowed;
                   6756:             foreach my $ipkey (@ips) {
                   6757:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6758:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6759:                         $allowed = 1;
                   6760:                         last; 
                   6761:                     }
                   6762:                 }
                   6763:             }
                   6764:             if ($allowed) {
                   6765:                 return 'ok';
                   6766:             }
1.765     albertel 6767:         }
                   6768:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6769:             if ($guest) {
                   6770:                 return $guest;
                   6771:             }
                   6772:         } else {
                   6773:             if (@domains > 0) {
                   6774:                 foreach my $domkey (@domains) {
                   6775:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6776:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6777:                             return 'ok';
                   6778:                         }
                   6779:                     }
                   6780:                 }
                   6781:             }
                   6782:             if (@users > 0) {
                   6783:                 foreach my $userkey (@users) {
1.865     raeburn  6784:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6785:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6786:                             if (ref($item) eq 'HASH') {
                   6787:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6788:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6789:                                     return 'ok';
                   6790:                                 }
                   6791:                             }
                   6792:                         }
                   6793:                     } 
1.765     albertel 6794:                 }
                   6795:             }
                   6796:             my %roleshash;
                   6797:             my @courses_and_groups = @courses;
                   6798:             push(@courses_and_groups,@groups); 
                   6799:             if (@courses_and_groups > 0) {
                   6800:                 my (%allgroups,%allroles); 
                   6801:                 my ($start,$end,$role,$sec,$group);
                   6802:                 foreach my $envkey (%env) {
1.1060    raeburn  6803:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6804:                         my $cid = $2.'_'.$3; 
                   6805:                         if ($1 eq 'gr') {
                   6806:                             $group = $4;
                   6807:                             $allgroups{$cid}{$group} = $env{$envkey};
                   6808:                         } else {
                   6809:                             if ($4 eq '') {
                   6810:                                 $sec = 'none';
                   6811:                             } else {
                   6812:                                 $sec = $4;
                   6813:                             }
                   6814:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6815:                         }
1.811     albertel 6816:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 6817:                         my $cid = $2.'_'.$3;
                   6818:                         if ($4 eq '') {
                   6819:                             $sec = 'none';
                   6820:                         } else {
                   6821:                             $sec = $4;
                   6822:                         }
                   6823:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   6824:                     }
                   6825:                 }
                   6826:                 if (keys(%allroles) == 0) {
                   6827:                     return;
                   6828:                 }
                   6829:                 foreach my $key (@courses_and_groups) {
                   6830:                     my %content = %{$$access_hash{$key}};
                   6831:                     my $cnum = $content{'number'};
                   6832:                     my $cdom = $content{'domain'};
                   6833:                     my $cid = $cdom.'_'.$cnum;
                   6834:                     if (!exists($allroles{$cid})) {
                   6835:                         next;
                   6836:                     }    
                   6837:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   6838:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   6839:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   6840:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   6841:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   6842:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   6843:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   6844:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   6845:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   6846:                                         if (grep/^all$/,@sections) {
                   6847:                                             return 'ok';
                   6848:                                         } else {
                   6849:                                             if (grep/^$sec$/,@sections) {
                   6850:                                                 return 'ok';
                   6851:                                             }
                   6852:                                         }
                   6853:                                     }
                   6854:                                 }
                   6855:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   6856:                                     if (grep/^none$/,@groups) {
                   6857:                                         return 'ok';
                   6858:                                     }
                   6859:                                 } else {
                   6860:                                     if (grep/^all$/,@groups) {
                   6861:                                         return 'ok';
                   6862:                                     } 
                   6863:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   6864:                                         if (grep/^$group$/,@groups) {
                   6865:                                             return 'ok';
                   6866:                                         }
                   6867:                                     }
                   6868:                                 } 
                   6869:                             }
                   6870:                         }
                   6871:                     }
                   6872:                 }
                   6873:             }
                   6874:             if ($guest) {
                   6875:                 return $guest;
                   6876:             }
                   6877:         }
                   6878:     }
                   6879:     return;
                   6880: }
                   6881: 
                   6882: sub course_group_datechecker {
                   6883:     my ($dates,$now,$status) = @_;
                   6884:     my ($start,$end) = split(/\./,$dates);
                   6885:     if (!$start && !$end) {
                   6886:         return 'ok';
                   6887:     }
                   6888:     if (grep/^active$/,@{$status}) {
                   6889:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   6890:             return 'ok';
                   6891:         }
                   6892:     }
                   6893:     if (grep/^previous$/,@{$status}) {
                   6894:         if ($end > $now ) {
                   6895:             return 'ok';
                   6896:         }
                   6897:     }
                   6898:     if (grep/^future$/,@{$status}) {
                   6899:         if ($start > $now) {
                   6900:             return 'ok';
                   6901:         }
                   6902:     }
                   6903:     return; 
                   6904: }
                   6905: 
                   6906: sub parse_portfolio_url {
                   6907:     my ($url) = @_;
                   6908: 
                   6909:     my ($type,$udom,$unum,$group,$file_name);
                   6910:     
1.823     albertel 6911:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 6912: 	$type = 1;
                   6913:         $udom = $1;
                   6914:         $unum = $2;
                   6915:         $file_name = $3;
1.823     albertel 6916:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 6917: 	$type = 2;
                   6918:         $udom = $1;
                   6919:         $unum = $2;
                   6920:         $group = $3;
                   6921:         $file_name = $3.'/'.$4;
                   6922:     }
                   6923:     if (wantarray) {
                   6924: 	return ($type,$udom,$unum,$file_name,$group);
                   6925:     }
                   6926:     return $type;
                   6927: }
                   6928: 
                   6929: sub is_portfolio_url {
                   6930:     my ($url) = @_;
                   6931:     return scalar(&parse_portfolio_url($url));
                   6932: }
                   6933: 
1.798     raeburn  6934: sub is_portfolio_file {
                   6935:     my ($file) = @_;
1.820     raeburn  6936:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  6937:         return 1;
                   6938:     }
                   6939:     return;
                   6940: }
                   6941: 
1.976     raeburn  6942: sub usertools_access {
1.1084    raeburn  6943:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  6944:     my ($access,%tools);
                   6945:     if ($context eq '') {
                   6946:         $context = 'tools';
                   6947:     }
                   6948:     if ($context eq 'requestcourses') {
                   6949:         %tools = (
                   6950:                       official   => 1,
                   6951:                       unofficial => 1,
1.1006    raeburn  6952:                       community  => 1,
1.1246    raeburn  6953:                       textbook   => 1,
1.1305    raeburn  6954:                       placement  => 1,
1.985     raeburn  6955:                  );
1.1183    raeburn  6956:     } elsif ($context eq 'requestauthor') {
                   6957:         %tools = (
                   6958:                       requestauthor => 1,
                   6959:                  );
1.985     raeburn  6960:     } else {
                   6961:         %tools = (
                   6962:                       aboutme   => 1,
                   6963:                       blog      => 1,
1.1177    raeburn  6964:                       webdav    => 1,
1.985     raeburn  6965:                       portfolio => 1,
                   6966:                  );
                   6967:     }
1.976     raeburn  6968:     return if (!defined($tools{$tool}));
                   6969: 
1.1242    raeburn  6970:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  6971:         $udom = $env{'user.domain'};
                   6972:         $uname = $env{'user.name'};
                   6973:     }
                   6974: 
1.978     raeburn  6975:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   6976:         if ($action ne 'reload') {
1.985     raeburn  6977:             if ($context eq 'requestcourses') {
                   6978:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  6979:             } elsif ($context eq 'requestauthor') {
                   6980:                 return $env{'environment.canrequest.author'};
1.985     raeburn  6981:             } else {
                   6982:                 return $env{'environment.availabletools.'.$tool};
                   6983:             }
                   6984:         }
1.976     raeburn  6985:     }
                   6986: 
1.1183    raeburn  6987:     my ($toolstatus,$inststatus,$envkey);
                   6988:     if ($context eq 'requestauthor') {
                   6989:         $envkey = $context; 
                   6990:     } else {
                   6991:         $envkey = $context.'.'.$tool;
                   6992:     }
1.976     raeburn  6993: 
1.985     raeburn  6994:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   6995:          ($action ne 'reload')) {
1.1183    raeburn  6996:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  6997:         $inststatus = $env{'environment.inststatus'};
                   6998:     } else {
1.1084    raeburn  6999:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7000:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7001:             $inststatus = $userenvref->{'inststatus'};
                   7002:         } else {
1.1183    raeburn  7003:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7004:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7005:             $inststatus = $userenv{'inststatus'};
                   7006:         }
1.976     raeburn  7007:     }
                   7008: 
                   7009:     if ($toolstatus ne '') {
                   7010:         if ($toolstatus) {
                   7011:             $access = 1;
                   7012:         } else {
                   7013:             $access = 0;
                   7014:         }
                   7015:         return $access;
                   7016:     }
                   7017: 
1.1084    raeburn  7018:     my ($is_adv,%domdef);
                   7019:     if (ref($is_advref) eq 'HASH') {
                   7020:         $is_adv = $is_advref->{'is_adv'};
                   7021:     } else {
                   7022:         $is_adv = &is_advanced_user($udom,$uname);
                   7023:     }
                   7024:     if (ref($domdefref) eq 'HASH') {
                   7025:         %domdef = %{$domdefref};
                   7026:     } else {
                   7027:         %domdef = &get_domain_defaults($udom);
                   7028:     }
1.976     raeburn  7029:     if (ref($domdef{$tool}) eq 'HASH') {
                   7030:         if ($is_adv) {
                   7031:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7032:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7033:                     $access = 1;
                   7034:                 } else {
                   7035:                     $access = 0;
                   7036:                 }
                   7037:                 return $access;
                   7038:             }
                   7039:         }
                   7040:         if ($inststatus ne '') {
                   7041:             my ($hasaccess,$hasnoaccess);
                   7042:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7043:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7044:                     if ($domdef{$tool}{$affiliation}) {
                   7045:                         $hasaccess = 1;
                   7046:                     } else {
                   7047:                         $hasnoaccess = 1;
                   7048:                     }
                   7049:                 }
                   7050:             }
                   7051:             if ($hasaccess || $hasnoaccess) {
                   7052:                 if ($hasaccess) {
                   7053:                     $access = 1;
                   7054:                 } elsif ($hasnoaccess) {
                   7055:                     $access = 0; 
                   7056:                 }
                   7057:                 return $access;
                   7058:             }
                   7059:         } else {
                   7060:             if ($domdef{$tool}{'default'} ne '') {
                   7061:                 if ($domdef{$tool}{'default'}) {
                   7062:                     $access = 1;
                   7063:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7064:                     $access = 0;
                   7065:                 }
                   7066:                 return $access;
                   7067:             }
                   7068:         }
                   7069:     } else {
1.1177    raeburn  7070:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7071:             $access = 1;
                   7072:         } else {
                   7073:             $access = 0;
                   7074:         }
1.976     raeburn  7075:         return $access;
                   7076:     }
                   7077: }
                   7078: 
1.1050    raeburn  7079: sub is_course_owner {
                   7080:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7081:     if (($udom eq '') || ($uname eq '')) {
                   7082:         $udom = $env{'user.domain'};
                   7083:         $uname = $env{'user.name'};
                   7084:     }
                   7085:     unless (($udom eq '') || ($uname eq '')) {
                   7086:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7087:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7088:                 return 1;
                   7089:             } else {
                   7090:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7091:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7092:                     return 1;
                   7093:                 }
                   7094:             }
                   7095:         }
                   7096:     }
                   7097:     return;
                   7098: }
                   7099: 
1.976     raeburn  7100: sub is_advanced_user {
                   7101:     my ($udom,$uname) = @_;
1.1085    raeburn  7102:     if ($udom ne '' && $uname ne '') {
                   7103:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7104:             if (wantarray) {
                   7105:                 return ($env{'user.adv'},$env{'user.author'});
                   7106:             } else {
                   7107:                 return $env{'user.adv'};
                   7108:             }
1.1085    raeburn  7109:         }
                   7110:     }
1.976     raeburn  7111:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7112:     my %allroles;
1.1128    raeburn  7113:     my ($is_adv,$is_author);
1.976     raeburn  7114:     foreach my $role (keys(%roleshash)) {
                   7115:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7116:         my $area = '/'.$tdomain.'/'.$trest;
                   7117:         if ($sec ne '') {
                   7118:             $area .= '/'.$sec;
                   7119:         }
                   7120:         if (($area ne '') && ($trole ne '')) {
                   7121:             my $spec=$trole.'.'.$area;
                   7122:             if ($trole =~ /^cr\//) {
                   7123:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7124:             } elsif ($trole ne 'gr') {
                   7125:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7126:             }
1.1128    raeburn  7127:             if ($trole eq 'au') {
                   7128:                 $is_author = 1;
                   7129:             }
1.976     raeburn  7130:         }
                   7131:     }
                   7132:     foreach my $role (keys(%allroles)) {
                   7133:         last if ($is_adv);
                   7134:         foreach my $item (split(/:/,$allroles{$role})) {
                   7135:             if ($item ne '') {
                   7136:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7137:                 if ($privilege eq 'adv') {
                   7138:                     $is_adv = 1;
                   7139:                     last;
                   7140:                 }
                   7141:             }
                   7142:         }
                   7143:     }
1.1128    raeburn  7144:     if (wantarray) {
                   7145:         return ($is_adv,$is_author);
                   7146:     }
1.976     raeburn  7147:     return $is_adv;
                   7148: }
1.798     raeburn  7149: 
1.1035    raeburn  7150: sub check_can_request {
1.1036    raeburn  7151:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  7152:     my $canreq = 0;
                   7153:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7154:     my @options = ('approval','validate','autolimit');
                   7155:     my $optregex = join('|',@options);
                   7156:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7157:         foreach my $type (@{$types}) {
                   7158:             if (&usertools_access($env{'user.name'},
                   7159:                                   $env{'user.domain'},
                   7160:                                   $type,undef,'requestcourses')) {
                   7161:                 $canreq ++;
1.1036    raeburn  7162:                 if (ref($request_domains) eq 'HASH') {
                   7163:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   7164:                 }
1.1035    raeburn  7165:                 if ($dom eq $env{'user.domain'}) {
                   7166:                     $can_request->{$type} = 1;
                   7167:                 }
                   7168:             }
                   7169:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   7170:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7171:                 if (@curr > 0) {
1.1036    raeburn  7172:                     foreach my $item (@curr) {
                   7173:                         if (ref($request_domains) eq 'HASH') {
                   7174:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7175:                             if ($otherdom ne '') {
                   7176:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7177:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7178:                                         push(@{$request_domains->{$type}},$otherdom);
                   7179:                                     }
                   7180:                                 } else {
                   7181:                                     push(@{$request_domains->{$type}},$otherdom);
                   7182:                                 }
                   7183:                             }
                   7184:                         }
                   7185:                     }
                   7186:                     unless($dom eq $env{'user.domain'}) {
                   7187:                         $canreq ++;
1.1035    raeburn  7188:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7189:                             $can_request->{$type} = 1;
                   7190:                         }
                   7191:                     }
                   7192:                 }
                   7193:             }
                   7194:         }
                   7195:     }
                   7196:     return $canreq;
                   7197: }
                   7198: 
1.341     www      7199: # ---------------------------------------------- Custom access rule evaluation
                   7200: 
                   7201: sub customaccess {
                   7202:     my ($priv,$uri)=@_;
1.807     albertel 7203:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7204:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7205:     $udom = &LONCAPA::clean_domain($udom);
                   7206:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7207:     my $access=0;
1.800     albertel 7208:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7209: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7210: 	if ($type eq 'user') {
                   7211: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7212: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7213: 		if ($tdom) {
                   7214: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7215: 		}
1.896     albertel 7216: 		if ($tuname) {
                   7217: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7218: 		}
                   7219: 		$access=($effect eq 'allow');
                   7220: 		last;
                   7221: 	    }
                   7222: 	} else {
                   7223: 	    if ($role) {
                   7224: 		if ($role ne $urole) { next; }
                   7225: 	    }
                   7226: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7227: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7228: 		if ($tdom) {
                   7229: 		    if ($tdom ne $udom) { next; }
                   7230: 		}
                   7231: 		if ($tcrs) {
                   7232: 		    if ($tcrs ne $ucrs) { next; }
                   7233: 		}
                   7234: 		if ($tsec) {
                   7235: 		    if ($tsec ne $usec) { next; }
                   7236: 		}
                   7237: 		$access=($effect eq 'allow');
                   7238: 		last;
                   7239: 	    }
                   7240: 	    if ($realm eq '' && $role eq '') {
                   7241: 		$access=($effect eq 'allow');
                   7242: 	    }
1.402     bowersj2 7243: 	}
1.341     www      7244:     }
                   7245:     return $access;
                   7246: }
                   7247: 
1.103     harris41 7248: # ------------------------------------------------- Check for a user privilege
1.12      www      7249: 
                   7250: sub allowed {
1.1281    raeburn  7251:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7252:     my $ver_orguri=$uri;
1.439     www      7253:     $uri=&deversion($uri);
1.152     www      7254:     my $orguri=$uri;
1.52      www      7255:     $uri=&declutter($uri);
1.809     raeburn  7256: 
1.810     raeburn  7257:     if ($priv eq 'evb') {
                   7258: # Evade communication block restrictions for specified role in a course
                   7259:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7260:             return $1;
                   7261:         } else {
                   7262:             return;
                   7263:         }
                   7264:     }
                   7265: 
1.620     albertel 7266:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7267: # Free bre access to adm and meta resources
1.1343    raeburn  7268:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7269: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7270: 	&& ($priv eq 'bre')) {
1.14      www      7271: 	return 'F';
1.159     www      7272:     }
                   7273: 
1.545     banghart 7274: # Free bre access to user's own portfolio contents
1.714     raeburn  7275:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7276:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7277: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7278:         my %setters;
                   7279:         my ($startblock,$endblock) = 
                   7280:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7281:         if ($startblock && $endblock) {
                   7282:             return 'B';
                   7283:         } else {
                   7284:             return 'F';
                   7285:         }
1.545     banghart 7286:     }
                   7287: 
1.762     raeburn  7288: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7289:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7290:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7291:         if (exists($env{'request.course.id'})) {
                   7292:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7293:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7294:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7295:                 my $courseprivid=$env{'request.course.id'};
                   7296:                 $courseprivid=~s/\_/\//;
                   7297:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7298:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7299:                     return $1; 
1.762     raeburn  7300:                 } else {
                   7301:                     if ($env{'request.course.sec'}) {
                   7302:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7303:                     }
                   7304:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7305:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7306:                         return $2;
                   7307:                     }
1.714     raeburn  7308:                 }
                   7309:             }
                   7310:         }
                   7311:     }
                   7312: 
1.159     www      7313: # Free bre to public access
                   7314: 
                   7315:     if ($priv eq 'bre') {
1.238     www      7316:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 7317: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7318:            return 'F'; 
                   7319:         }
1.238     www      7320:         if ($copyright eq 'priv') {
                   7321:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7322: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7323: 		return '';
                   7324:             }
                   7325:         }
                   7326:         if ($copyright eq 'domain') {
                   7327:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7328: 	    unless (($env{'user.domain'} eq $1) ||
                   7329:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7330: 		return '';
                   7331:             }
1.262     matthew  7332:         }
1.620     albertel 7333:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7334:             # Library role, so allow browsing of resources in this domain.
                   7335:             return 'F';
1.238     www      7336:         }
1.341     www      7337:         if ($copyright eq 'custom') {
                   7338: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7339:         }
1.14      www      7340:     }
1.264     matthew  7341:     # Domain coordinator is trying to create a course
1.620     albertel 7342:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7343:         # uri is the requested domain in this case.
                   7344:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7345:         # a role of dc for the domain in question.
1.620     albertel 7346:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7347:     }
1.29      www      7348: 
1.52      www      7349:     my $thisallowed='';
                   7350:     my $statecond=0;
                   7351:     my $courseprivid='';
                   7352: 
1.1039    raeburn  7353:     my $ownaccess;
1.1043    raeburn  7354:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7355:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7356:         if ($uri eq '') {
                   7357:             $ownaccess = 1;
                   7358:         } else {
                   7359:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7360:                 my $udom = $env{'user.domain'};
                   7361:                 my $uname = $env{'user.name'};
                   7362:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7363:                     $ownaccess = 1;
1.1040    raeburn  7364:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7365:                     unless ($uri =~ m{\.\./}) {
                   7366:                         $ownaccess = 1;
                   7367:                     }
                   7368:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7369:                     my $now = time;
                   7370:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7371:                         my $adom = $1;
                   7372:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7373:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7374:                                 my ($start,$end) = split('.',$env{$key});
                   7375:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7376:                                     $ownaccess = 1;
                   7377:                                     last;
                   7378:                                 }
                   7379:                             }
                   7380:                         }
                   7381:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7382:                         my $adom = $1;
                   7383:                         my $aname = $2;
1.1042    raeburn  7384:                         foreach my $role ('ca','aa') { 
                   7385:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7386:                                 my ($start,$end) =
                   7387:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7388:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7389:                                     $ownaccess = 1;
                   7390:                                     last;
                   7391:                                 }
1.1039    raeburn  7392:                             }
                   7393:                         }
                   7394:                     }
                   7395:                 }
                   7396:             }
                   7397:         }
                   7398:     }
                   7399: 
1.52      www      7400: # Course
                   7401: 
1.620     albertel 7402:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7403:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7404:             $thisallowed.=$1;
                   7405:         }
1.52      www      7406:     }
1.29      www      7407: 
1.52      www      7408: # Domain
                   7409: 
1.620     albertel 7410:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7411:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7412:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7413:             $thisallowed.=$1;
                   7414:         }
1.12      www      7415:     }
1.52      www      7416: 
1.1141    raeburn  7417: # User who is not author or co-author might still be able to edit
                   7418: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7419:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7420:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7421:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7422:             $thisallowed.=$1;
                   7423:         }
                   7424:     }
                   7425: 
1.52      www      7426: # Course: uri itself is a course
1.66      www      7427:     my $courseuri=$uri;
                   7428:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7429:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7430: 
1.620     albertel 7431:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7432:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7433:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7434:             $thisallowed.=$1;
                   7435:         }
1.12      www      7436:     }
1.29      www      7437: 
1.665     albertel 7438: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7439: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7440:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7441: 	$thisallowed='';
1.671     raeburn  7442:         my ($match)=&is_on_map($uri);
                   7443:         if ($match) {
                   7444:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7445:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7446:                 my $value = $1;
                   7447:                 if ($noblockcheck) {
                   7448:                     $thisallowed.=$value;
1.1162    raeburn  7449:                 } else {
1.1281    raeburn  7450:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7451:                     if (@blockers > 0) {
                   7452:                         $thisallowed = 'B';
                   7453:                     } else {
                   7454:                         $thisallowed.=$value;
                   7455:                     }
1.1162    raeburn  7456:                 }
1.671     raeburn  7457:             }
                   7458:         } else {
1.705     albertel 7459:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7460:             if ($refuri) {
                   7461:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7462:                     $thisallowed='F';
1.671     raeburn  7463:                 } else {
                   7464:                     $refuri=&declutter($refuri);
                   7465:                     my ($match) = &is_on_map($refuri);
                   7466:                     if ($match) {
1.1281    raeburn  7467:                         if ($noblockcheck) {
                   7468:                             $thisallowed='F';
1.1162    raeburn  7469:                         } else {
1.1281    raeburn  7470:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7471:                             if (@blockers > 0) {
                   7472:                                 $thisallowed = 'B';
                   7473:                             } else {
                   7474:                                 $thisallowed='F';
                   7475:                             }
1.1162    raeburn  7476:                         }
1.671     raeburn  7477:                     }
1.669     raeburn  7478:                 }
1.671     raeburn  7479:             }
                   7480:         }
1.314     www      7481:     }
1.492     albertel 7482: 
1.766     albertel 7483:     if ($priv eq 'bre'
                   7484: 	&& $thisallowed ne 'F' 
                   7485: 	&& $thisallowed ne '2'
                   7486: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7487: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7488:     }
1.1250    raeburn  7489: 
1.52      www      7490: # Full access at system, domain or course-wide level? Exit.
1.29      www      7491:     if ($thisallowed=~/F/) {
                   7492: 	return 'F';
                   7493:     }
                   7494: 
1.52      www      7495: # If this is generating or modifying users, exit with special codes
1.29      www      7496: 
1.643     www      7497:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7498: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7499: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7500: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7501: 	    unless ($auname) { return $thisallowed; }
                   7502: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7503: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7504: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7505: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7506: 	}
1.52      www      7507: 	return $thisallowed;
                   7508:     }
                   7509: #
1.103     harris41 7510: # Gathered so far: system, domain and course wide privileges
1.52      www      7511: #
                   7512: # Course: See if uri or referer is an individual resource that is part of 
                   7513: # the course
                   7514: 
1.620     albertel 7515:     if ($env{'request.course.id'}) {
1.232     www      7516: 
1.620     albertel 7517:        $courseprivid=$env{'request.course.id'};
                   7518:        if ($env{'request.course.sec'}) {
                   7519:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7520:        }
                   7521:        $courseprivid=~s/\_/\//;
                   7522:        my $checkreferer=1;
1.232     www      7523:        my ($match,$cond)=&is_on_map($uri);
                   7524:        if ($match) {
                   7525:            $statecond=$cond;
1.620     albertel 7526:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7527:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7528:                my $value = $1;
                   7529:                if ($priv eq 'bre') {
1.1281    raeburn  7530:                    if ($noblockcheck) {
                   7531:                        $thisallowed.=$value;
1.1162    raeburn  7532:                    } else {
1.1281    raeburn  7533:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7534:                        if (@blockers > 0) {
                   7535:                            $thisallowed = 'B';
                   7536:                        } else {
                   7537:                            $thisallowed.=$value;
                   7538:                        }
1.1162    raeburn  7539:                    }
                   7540:                } else {
                   7541:                    $thisallowed.=$value;
                   7542:                }
1.52      www      7543:                $checkreferer=0;
                   7544:            }
1.29      www      7545:        }
1.83      www      7546:        
1.148     www      7547:        if ($checkreferer) {
1.620     albertel 7548: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7549:             unless ($refuri) {
1.800     albertel 7550:                 foreach my $key (keys(%env)) {
                   7551: 		    if ($key=~/^httpref\..*\*/) {
                   7552: 			my $pattern=$key;
1.156     www      7553:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7554:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7555:                         $pattern=~s/\//\\\//g;
1.152     www      7556:                         if ($orguri=~/$pattern/) {
1.800     albertel 7557: 			    $refuri=$env{$key};
1.148     www      7558:                         }
                   7559:                     }
1.191     harris41 7560:                 }
1.148     www      7561:             }
1.232     www      7562: 
1.148     www      7563:          if ($refuri) { 
1.152     www      7564: 	  $refuri=&declutter($refuri);
1.232     www      7565:           my ($match,$cond)=&is_on_map($refuri);
                   7566:             if ($match) {
                   7567:               my $refstatecond=$cond;
1.620     albertel 7568:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7569:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7570:                   my $value = $1;
                   7571:                   if ($priv eq 'bre') {
1.1281    raeburn  7572:                       if ($noblockcheck) {
                   7573:                           $thisallowed.=$value;
1.1162    raeburn  7574:                       } else {
1.1281    raeburn  7575:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7576:                           if (@blockers > 0) {
                   7577:                               $thisallowed = 'B';
                   7578:                           } else {
                   7579:                               $thisallowed.=$value;
                   7580:                           }
1.1162    raeburn  7581:                       }
                   7582:                   } else {
                   7583:                       $thisallowed.=$value;
                   7584:                   }
1.53      www      7585:                   $uri=$refuri;
                   7586:                   $statecond=$refstatecond;
1.52      www      7587:               }
                   7588:           }
1.148     www      7589:         }
1.29      www      7590:        }
1.52      www      7591:    }
1.29      www      7592: 
1.52      www      7593: #
1.103     harris41 7594: # Gathered now: all privileges that could apply, and condition number
1.52      www      7595: # 
                   7596: #
                   7597: # Full or no access?
                   7598: #
1.29      www      7599: 
1.52      www      7600:     if ($thisallowed=~/F/) {
                   7601: 	return 'F';
                   7602:     }
1.29      www      7603: 
1.52      www      7604:     unless ($thisallowed) {
                   7605:         return '';
                   7606:     }
1.29      www      7607: 
1.52      www      7608: # Restrictions exist, deal with them
                   7609: #
                   7610: #   C:according to course preferences
                   7611: #   R:according to resource settings
                   7612: #   L:unless locked
                   7613: #   X:according to user session state
                   7614: #
                   7615: 
                   7616: # Possibly locked functionality, check all courses
1.54      www      7617: # Locks might take effect only after 10 minutes cache expiration for other
                   7618: # courses, and 2 minutes for current course
1.52      www      7619: 
                   7620:     my $envkey;
                   7621:     if ($thisallowed=~/L/) {
1.1000    raeburn  7622:         foreach $envkey (keys(%env)) {
1.54      www      7623:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7624:                my $courseid=$2;
                   7625:                my $roleid=$1.'.'.$2;
1.92      www      7626:                $courseid=~s/^\///;
1.54      www      7627:                my $expiretime=600;
1.620     albertel 7628:                if ($env{'request.role'} eq $roleid) {
1.54      www      7629: 		  $expiretime=120;
                   7630:                }
                   7631: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7632:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7633:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7634: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7635:                }
1.620     albertel 7636:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7637:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7638: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7639:                        &log($env{'user.domain'},$env{'user.name'},
                   7640:                             $env{'user.home'},
1.57      www      7641:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7642:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7643:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7644: 		       return '';
                   7645:                    }
                   7646:                }
1.620     albertel 7647:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7648:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7649: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7650:                        &log($env{'user.domain'},$env{'user.name'},
                   7651:                             $env{'user.home'},
1.57      www      7652:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7653:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7654:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7655: 		       return '';
                   7656:                    }
                   7657:                }
                   7658: 	   }
1.29      www      7659:        }
1.52      www      7660:     }
                   7661:    
                   7662: #
                   7663: # Rest of the restrictions depend on selected course
                   7664: #
                   7665: 
1.620     albertel 7666:     unless ($env{'request.course.id'}) {
1.766     albertel 7667: 	if ($thisallowed eq 'A') {
                   7668: 	    return 'A';
1.814     raeburn  7669:         } elsif ($thisallowed eq 'B') {
                   7670:             return 'B';
1.766     albertel 7671: 	} else {
                   7672: 	    return '1';
                   7673: 	}
1.52      www      7674:     }
1.29      www      7675: 
1.52      www      7676: #
                   7677: # Now user is definitely in a course
                   7678: #
1.53      www      7679: 
                   7680: 
                   7681: # Course preferences
                   7682: 
                   7683:    if ($thisallowed=~/C/) {
1.620     albertel 7684:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7685:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7686:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7687: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7688: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7689: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7690: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7691: 			$env{'request.course.id'});
                   7692: 	   }
1.237     www      7693:            return '';
                   7694:        }
                   7695: 
1.620     albertel 7696:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7697: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7698: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7699: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7700: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7701: 			$env{'request.course.id'});
                   7702: 	   }
1.54      www      7703:            return '';
                   7704:        }
1.53      www      7705:    }
                   7706: 
                   7707: # Resource preferences
                   7708: 
                   7709:    if ($thisallowed=~/R/) {
1.620     albertel 7710:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7711:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7712: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7713: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7714: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7715: 	   }
                   7716: 	   return '';
1.54      www      7717:        }
1.53      www      7718:    }
1.30      www      7719: 
1.246     www      7720: # Restricted by state or randomout?
1.30      www      7721: 
1.52      www      7722:    if ($thisallowed=~/X/) {
1.620     albertel 7723:       if ($env{'acc.randomout'}) {
1.579     albertel 7724: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7725:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7726:             return ''; 
                   7727:          }
1.247     www      7728:       }
                   7729:       if (&condval($statecond)) {
1.52      www      7730: 	 return '2';
                   7731:       } else {
                   7732:          return '';
                   7733:       }
                   7734:    }
1.30      www      7735: 
1.766     albertel 7736:     if ($thisallowed eq 'A') {
                   7737: 	return 'A';
1.814     raeburn  7738:     } elsif ($thisallowed eq 'B') {
                   7739:         return 'B';
1.766     albertel 7740:     }
1.52      www      7741:    return 'F';
1.232     www      7742: }
1.1162    raeburn  7743: 
1.1192    raeburn  7744: # ------------------------------------------- Check construction space access
                   7745: 
                   7746: sub constructaccess {
                   7747:     my ($url,$setpriv)=@_;
                   7748: 
                   7749: # We do not allow editing of previous versions of files
                   7750:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7751: 
                   7752: # Get username and domain from URL
                   7753:     my ($ownername,$ownerdomain,$ownerhome);
                   7754: 
                   7755:     ($ownerdomain,$ownername) =
1.1325    raeburn  7756:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7757: 
                   7758: # The URL does not really point to any authorspace, forget it
                   7759:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7760: 
                   7761: # Now we need to see if the user has access to the authorspace of
                   7762: # $ownername at $ownerdomain
                   7763: 
                   7764:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7765: # Real author for this?
                   7766:        $ownerhome = $env{'user.home'};
                   7767:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7768:           return ($ownername,$ownerdomain,$ownerhome);
                   7769:        }
                   7770:     } else {
                   7771: # Co-author for this?
                   7772:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7773:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7774:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7775:             return ($ownername,$ownerdomain,$ownerhome);
                   7776:         }
1.1312    raeburn  7777:         if ($env{'request.course.id'}) {
                   7778:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7779:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7780:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7781:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7782:                     return ($ownername,$ownerdomain,$ownerhome);
                   7783:                 }
                   7784:             }
                   7785:         }
1.1192    raeburn  7786:     }
                   7787: 
                   7788: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7789: # we might as well leave
                   7790:    unless ($setpriv) { return ''; }
                   7791: 
                   7792: # Backdoor access?
                   7793:     my $allowed=&allowed('eco',$ownerdomain);
                   7794: # Nope
                   7795:     unless ($allowed) { return ''; }
                   7796: # Looks like we may have access, but could be locked by the owner of the construction space
                   7797:     if ($allowed eq 'U') {
                   7798:         my %blocked=&get('environment',['domcoord.author'],
                   7799:                          $ownerdomain,$ownername);
                   7800: # Is blocked by owner
                   7801:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   7802:     }
                   7803:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   7804: # Grant temporary access
                   7805:         my $then=$env{'user.login.time'};
1.1209    raeburn  7806:         my $update=$env{'user.update.time'};
1.1192    raeburn  7807:         if (!$update) { $update = $then; }
                   7808:         my $refresh=$env{'user.refresh.time'};
                   7809:         if (!$refresh) { $refresh = $update; }
                   7810:         my $now = time;
                   7811:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   7812:                            $now,'ca','constructaccess');
                   7813:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   7814:         return($ownername,$ownerdomain,$ownerhome);
                   7815:     }
                   7816: # No business here
                   7817:     return '';
                   7818: }
                   7819: 
1.1282    raeburn  7820: # ----------------------------------------------------------- Content Blocking
                   7821: 
                   7822: {
                   7823: # Caches for faster Course Contents display where content blocking
                   7824: # is in operation (i.e., interval param set) for timed quiz.
                   7825: #
                   7826: # User for whom data are being temporarily cached.
                   7827: my $cacheduser='';
                   7828: # Cached blockers for this user (a hash of blocking items). 
                   7829: my %cachedblockers=();
                   7830: # When the data were last cached.
                   7831: my $cachedlast='';
                   7832: 
                   7833: sub load_all_blockers {
                   7834:     my ($uname,$udom,$blocks)=@_;
                   7835:     if (($uname ne '') && ($udom ne '')) { 
                   7836:         if (($cacheduser eq $uname.':'.$udom) &&
                   7837:             (abs($cachedlast-time)<5)) {
                   7838:             return;
                   7839:         }
                   7840:     }
                   7841:     $cachedlast=time;
                   7842:     $cacheduser=$uname.':'.$udom;
                   7843:     %cachedblockers = &get_commblock_resources($blocks);
                   7844: }
                   7845: 
1.1162    raeburn  7846: sub get_comm_blocks {
                   7847:     my ($cdom,$cnum) = @_;
                   7848:     if ($cdom eq '' || $cnum eq '') {
                   7849:         return unless ($env{'request.course.id'});
                   7850:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7851:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7852:     }
                   7853:     my %commblocks;
                   7854:     my $hashid=$cdom.'_'.$cnum;
                   7855:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   7856:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   7857:         %commblocks = %{$blocksref};
                   7858:     } else {
                   7859:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   7860:         my $cachetime = 600;
                   7861:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   7862:     }
                   7863:     return %commblocks;
                   7864: }
                   7865: 
1.1282    raeburn  7866: sub get_commblock_resources {
                   7867:     my ($blocks) = @_;
                   7868:     my %blockers = ();
                   7869:     return %blockers unless ($env{'request.course.id'});
                   7870:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  7871:     my %commblocks;
                   7872:     if (ref($blocks) eq 'HASH') {
                   7873:         %commblocks = %{$blocks};
                   7874:     } else {
                   7875:         %commblocks = &get_comm_blocks();
                   7876:     }
1.1282    raeburn  7877:     return %blockers unless (keys(%commblocks) > 0); 
                   7878:     my $navmap = Apache::lonnavmaps::navmap->new();
                   7879:     return %blockers unless (ref($navmap));
1.1162    raeburn  7880:     my $now = time;
                   7881:     foreach my $block (keys(%commblocks)) {
                   7882:         if ($block =~ /^(\d+)____(\d+)$/) {
                   7883:             my ($start,$end) = ($1,$2);
                   7884:             if ($start <= $now && $end >= $now) {
                   7885:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7886:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   7887:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  7888:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7889:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  7890:                             }
                   7891:                         }
                   7892:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  7893:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7894:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  7895:                             }
                   7896:                         }
                   7897:                     }
                   7898:                 }
                   7899:             }
                   7900:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   7901:             my $item = $1;
1.1163    raeburn  7902:             my @to_test;
1.1162    raeburn  7903:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   7904:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  7905:                     my @interval;
                   7906:                     my $type = 'map';
                   7907:                     if ($item eq 'course') {
                   7908:                         $type = 'course';
                   7909:                         @interval=&EXT("resource.0.interval");
                   7910:                     } else {
                   7911:                         if ($item =~ /___\d+___/) {
                   7912:                             $type = 'resource';
                   7913:                             @interval=&EXT("resource.0.interval",$item);
                   7914:                             if (ref($navmap)) {                        
                   7915:                                 my $res = $navmap->getBySymb($item); 
                   7916:                                 push(@to_test,$res);
                   7917:                             }
1.1162    raeburn  7918:                         } else {
1.1282    raeburn  7919:                             my $mapsymb = &symbread($item,1);
                   7920:                             if ($mapsymb) {
                   7921:                                 if (ref($navmap)) {
                   7922:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   7923:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   7924:                                     foreach my $res (@to_test) {
                   7925:                                         my $symb = $res->symb();
                   7926:                                         next if ($symb eq $mapsymb);
                   7927:                                         if ($symb ne '') {
                   7928:                                             @interval=&EXT("resource.0.interval",$symb);
                   7929:                                             if ($interval[1] eq 'map') {
                   7930:                                                 last;
1.1162    raeburn  7931:                                             }
                   7932:                                         }
                   7933:                                     }
                   7934:                                 }
                   7935:                             }
                   7936:                         }
1.1282    raeburn  7937:                     }
1.1310    raeburn  7938:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  7939:                         my $timelimit = $1; 
1.1282    raeburn  7940:                         my $first_access;
                   7941:                         if ($type eq 'resource') {
                   7942:                             $first_access=&get_first_access($interval[1],$item);
                   7943:                         } elsif ($type eq 'map') {
                   7944:                             $first_access=&get_first_access($interval[1],undef,$item);
                   7945:                         } else {
                   7946:                             $first_access=&get_first_access($interval[1]);
                   7947:                         }
                   7948:                         if ($first_access) {
1.1292    raeburn  7949:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  7950:                             if ($timesup > $now) {
                   7951:                                 my $activeblock;
                   7952:                                 foreach my $res (@to_test) {
1.1283    raeburn  7953:                                     if ($res->answerable()) {
1.1282    raeburn  7954:                                         $activeblock = 1;
                   7955:                                         last;
                   7956:                                     }
                   7957:                                 }
                   7958:                                 if ($activeblock) {
                   7959:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   7960:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   7961:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   7962:                                          }
                   7963:                                     }
                   7964:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   7965:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   7966:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  7967:                                         }
1.1162    raeburn  7968:                                     }
                   7969:                                 }
                   7970:                             }
                   7971:                         }
                   7972:                     }
                   7973:                 }
                   7974:             }
                   7975:         }
                   7976:     }
1.1282    raeburn  7977:     return %blockers;
1.1162    raeburn  7978: }
                   7979: 
1.1282    raeburn  7980: sub has_comm_blocking {
                   7981:     my ($priv,$symb,$uri,$blocks) = @_;
                   7982:     my @blockers;
                   7983:     return unless ($env{'request.course.id'});
                   7984:     return unless ($priv eq 'bre');
                   7985:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   7986:     return if ($env{'request.state'} eq 'construct');
                   7987:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   7988:     return unless (keys(%cachedblockers) > 0);
                   7989:     my (%possibles,@symbs);
                   7990:     if (!$symb) {
                   7991:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  7992:     }
1.1282    raeburn  7993:     if ($symb) {
                   7994:         @symbs = ($symb);
                   7995:     } elsif (keys(%possibles)) { 
                   7996:         @symbs = keys(%possibles);
                   7997:     }
                   7998:     my $noblock;
                   7999:     foreach my $symb (@symbs) {
                   8000:         last if ($noblock);
                   8001:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8002:         foreach my $block (keys(%cachedblockers)) {
                   8003:             if ($block =~ /^firstaccess____(.+)$/) {
                   8004:                 my $item = $1;
                   8005:                 if (($item eq $map) || ($item eq $symb)) {
                   8006:                     $noblock = 1;
                   8007:                     last;
                   8008:                 }
                   8009:             }
                   8010:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8011:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8012:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8013:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8014:                             push(@blockers,$block);
                   8015:                         }
                   8016:                     }
                   8017:                 }
1.1162    raeburn  8018:             }
1.1282    raeburn  8019:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8020:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8021:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8022:                         push(@blockers,$block);
                   8023:                     }
                   8024:                 }
1.1162    raeburn  8025:             }
                   8026:         }
                   8027:     }
1.1282    raeburn  8028:     return if ($noblock);
                   8029:     return @blockers;
                   8030: }
1.1162    raeburn  8031: }
                   8032: 
1.1282    raeburn  8033: # -------------------------------- Deversion and split uri into path an filename   
                   8034: 
1.1133    foxr     8035: #
1.1282    raeburn  8036: #   Removes the version from a URI and
1.1133    foxr     8037: #   splits it in to its filename and path to the filename.
                   8038: #   Seems like File::Basename could have done this more clearly.
                   8039: #   Parameters:
                   8040: #      $uri   - input URI
                   8041: #   Returns:
                   8042: #     Two element list consisting of 
                   8043: #     $pathname  - the URI up to and excluding the trailing /
                   8044: #     $filename  - The part of the URI following the last /
                   8045: #  NOTE:
                   8046: #    Another realization of this is simply:
                   8047: #    use File::Basename;
                   8048: #    ...
                   8049: #    $uri = shift;
                   8050: #    $filename = basename($uri);
                   8051: #    $path     = dirname($uri);
                   8052: #    return ($filename, $path);
                   8053: #
                   8054: #     The implementation below is probably faster however.
                   8055: #
1.710     albertel 8056: sub split_uri_for_cond {
                   8057:     my $uri=&deversion(&declutter(shift));
                   8058:     my @uriparts=split(/\//,$uri);
                   8059:     my $filename=pop(@uriparts);
                   8060:     my $pathname=join('/',@uriparts);
                   8061:     return ($pathname,$filename);
                   8062: }
1.232     www      8063: # --------------------------------------------------- Is a resource on the map?
                   8064: 
                   8065: sub is_on_map {
1.710     albertel 8066:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8067:     #Trying to find the conditional for the file
1.620     albertel 8068:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8069: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8070:     if ($match) {
1.289     bowersj2 8071: 	return (1,$1);
                   8072:     } else {
1.434     www      8073: 	return (0,0);
1.289     bowersj2 8074:     }
1.12      www      8075: }
                   8076: 
1.427     www      8077: # --------------------------------------------------------- Get symb from alias
                   8078: 
                   8079: sub get_symb_from_alias {
                   8080:     my $symb=shift;
                   8081:     my ($map,$resid,$url)=&decode_symb($symb);
                   8082: # Already is a symb
                   8083:     if ($url) { return $symb; }
                   8084: # Must be an alias
                   8085:     my $aliassymb='';
                   8086:     my %bighash;
1.620     albertel 8087:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8088:                             &GDBM_READER(),0640)) {
                   8089:         my $rid=$bighash{'mapalias_'.$symb};
                   8090: 	if ($rid) {
                   8091: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8092: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8093: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8094: 	}
                   8095:         untie %bighash;
                   8096:     }
                   8097:     return $aliassymb;
                   8098: }
                   8099: 
1.12      www      8100: # ----------------------------------------------------------------- Define Role
                   8101: 
                   8102: sub definerole {
                   8103:   if (allowed('mcr','/')) {
1.1326    raeburn  8104:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8105:     foreach my $role (split(':',$sysrole)) {
                   8106: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8107:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8108:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8109: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8110:                return "refused:s:$crole&$cqual"; 
                   8111:             }
                   8112:         }
1.191     harris41 8113:     }
1.800     albertel 8114:     foreach my $role (split(':',$domrole)) {
                   8115: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8116:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8117:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8118: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8119:                return "refused:d:$crole&$cqual"; 
                   8120:             }
                   8121:         }
1.191     harris41 8122:     }
1.800     albertel 8123:     foreach my $role (split(':',$courole)) {
                   8124: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8125:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8126:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8127: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8128:                return "refused:c:$crole&$cqual"; 
                   8129:             }
                   8130:         }
1.191     harris41 8131:     }
1.1326    raeburn  8132:     my $uhome;
                   8133:     if (($uname ne '') && ($udom ne '')) {
                   8134:         $uhome = &homeserver($uname,$udom);
                   8135:         return $uhome if ($uhome eq 'no_host');
                   8136:     } else {
                   8137:         $uname = $env{'user.name'};
                   8138:         $udom = $env{'user.domain'};
                   8139:         $uhome = $env{'user.home'};
                   8140:     }
1.620     albertel 8141:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8142:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8143:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8144:     return reply($command,$uhome);
1.12      www      8145:   } else {
                   8146:     return 'refused';
                   8147:   }
1.105     harris41 8148: }
                   8149: 
                   8150: # ---------------- Make a metadata query against the network of library servers
                   8151: 
                   8152: sub metadata_query {
1.1237    raeburn  8153:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8154:     my %rhash;
1.845     albertel 8155:     my %libserv = &all_library();
1.244     matthew  8156:     my @server_list = (defined($server_array) ? @$server_array
                   8157:                                               : keys(%libserv) );
                   8158:     for my $server (@server_list) {
1.1237    raeburn  8159:         my $domains = ''; 
                   8160:         if (ref($domains_hash) eq 'HASH') {
                   8161:             $domains = $domains_hash->{$server}; 
                   8162:         }
1.118     harris41 8163: 	unless ($custom or $customshow) {
1.1237    raeburn  8164: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8165: 	    $rhash{$server}=$reply;
                   8166: 	}
                   8167: 	else {
                   8168: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8169: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8170: 			     $server);
                   8171: 	    $rhash{$server}=$reply;
                   8172: 	}
1.112     harris41 8173:     }
1.118     harris41 8174:     return \%rhash;
1.240     www      8175: }
                   8176: 
                   8177: # ----------------------------------------- Send log queries and wait for reply
                   8178: 
                   8179: sub log_query {
                   8180:     my ($uname,$udom,$query,%filters)=@_;
                   8181:     my $uhome=&homeserver($uname,$udom);
                   8182:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8183:     my $uhost=&hostname($uhome);
1.800     albertel 8184:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8185:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8186:                        $uhome);
1.479     albertel 8187:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8188:     return get_query_reply($queryid);
                   8189: }
                   8190: 
1.818     raeburn  8191: # -------------------------- Update MySQL table for portfolio file
                   8192: 
                   8193: sub update_portfolio_table {
1.821     raeburn  8194:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8195:     if ($group ne '') {
                   8196:         $file_name =~s /^\Q$group\E//;
                   8197:     }
1.818     raeburn  8198:     my $homeserver = &homeserver($uname,$udom);
                   8199:     my $queryid=
1.821     raeburn  8200:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8201:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8202:     my $reply = &get_query_reply($queryid);
                   8203:     return $reply;
                   8204: }
                   8205: 
1.899     raeburn  8206: # -------------------------- Update MySQL allusers table
                   8207: 
                   8208: sub update_allusers_table {
                   8209:     my ($uname,$udom,$names) = @_;
                   8210:     my $homeserver = &homeserver($uname,$udom);
                   8211:     my $queryid=
                   8212:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8213:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8214:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8215:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8216:                'generation='.&escape($names->{'generation'}).'%%'.
                   8217:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8218:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8219:     return;
1.899     raeburn  8220: }
                   8221: 
1.508     raeburn  8222: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8223: 
                   8224: sub fetch_enrollment_query {
1.511     raeburn  8225:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8226:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8227:     my $maxtries = 1;
1.508     raeburn  8228:     if ($context eq 'automated') {
                   8229:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8230:         $sleep = 2;
                   8231:         $loopmax = 100;
1.547     raeburn  8232:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8233:     } else {
                   8234:         $homeserver = &homeserver($cnum,$dom);
                   8235:     }
1.838     albertel 8236:     my $host=&hostname($homeserver);
1.506     raeburn  8237:     my $cmd = '';
1.1000    raeburn  8238:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8239:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8240:     }
                   8241:     $cmd =~ s/%%$//;
                   8242:     $cmd = &escape($cmd);
                   8243:     my $query = 'fetchenrollment';
1.620     albertel 8244:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8245:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8246:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8247:         return 'error: '.$queryid;
                   8248:     }
1.1317    raeburn  8249:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8250:     my $tries = 1;
                   8251:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8252:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8253:         $tries ++;
                   8254:     }
1.526     raeburn  8255:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8256:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8257:     } else {
1.901     albertel 8258:         my @responses = split(/:/,$reply);
1.1322    raeburn  8259:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8260:             foreach my $line (@responses) {
                   8261:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8262:                 $$replyref{$key} = $value;
                   8263:             }
                   8264:         } else {
1.1117    foxr     8265:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8266:             foreach my $line (@responses) {
                   8267:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8268:                 $$replyref{$key} = $value;
                   8269:                 if ($value > 0) {
1.800     albertel 8270:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8271:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8272:                         my $destname = $pathname.'/'.$filename;
                   8273:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8274:                         if ($xml_classlist =~ /^error/) {
                   8275:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8276:                         } else {
1.506     raeburn  8277:                             if ( open(FILE,">$destname") ) {
                   8278:                                 print FILE &unescape($xml_classlist);
                   8279:                                 close(FILE);
1.526     raeburn  8280:                             } else {
                   8281:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8282:                             }
                   8283:                         }
                   8284:                     }
                   8285:                 }
                   8286:             }
                   8287:         }
                   8288:         return 'ok';
                   8289:     }
                   8290:     return 'error';
                   8291: }
                   8292: 
1.242     www      8293: sub get_query_reply {
1.1317    raeburn  8294:     my ($queryid,$sleep,$loopmax) = @_;;
                   8295:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8296:         $sleep = 0.2;
                   8297:     }
                   8298:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8299:         $loopmax = 100;
                   8300:     }
1.1117    foxr     8301:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8302:     my $reply='';
1.1317    raeburn  8303:     for (1..$loopmax) {
                   8304: 	sleep($sleep);
1.240     www      8305:         if (-e $replyfile.'.end') {
1.448     albertel 8306: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 8307: 		$reply = join('',<$fh>);
                   8308: 		close($fh);
1.240     www      8309: 	   } else { return 'error: reply_file_error'; }
1.242     www      8310:            return &unescape($reply);
                   8311: 	}
1.240     www      8312:     }
1.242     www      8313:     return 'timeout:'.$queryid;
1.240     www      8314: }
                   8315: 
                   8316: sub courselog_query {
1.241     www      8317: #
                   8318: # possible filters:
                   8319: # url: url or symb
                   8320: # username
                   8321: # domain
                   8322: # action: view, submit, grade
                   8323: # start: timestamp
                   8324: # end: timestamp
                   8325: #
1.240     www      8326:     my (%filters)=@_;
1.620     albertel 8327:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8328:     if ($filters{'url'}) {
                   8329: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8330:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8331:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8332:     }
1.620     albertel 8333:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8334:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8335:     return &log_query($cname,$cdom,'courselog',%filters);
                   8336: }
                   8337: 
                   8338: sub userlog_query {
1.858     raeburn  8339: #
                   8340: # possible filters:
                   8341: # action: log check role
                   8342: # start: timestamp
                   8343: # end: timestamp
                   8344: #
1.240     www      8345:     my ($uname,$udom,%filters)=@_;
                   8346:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8347: }
                   8348: 
1.506     raeburn  8349: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8350: 
                   8351: sub auto_run {
1.508     raeburn  8352:     my ($cnum,$cdom) = @_;
1.876     raeburn  8353:     my $response = 0;
                   8354:     my $settings;
                   8355:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8356:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8357:         $settings = $domconfig{'autoenroll'};
                   8358:         if ($settings->{'run'} eq '1') {
                   8359:             $response = 1;
                   8360:         }
                   8361:     } else {
1.934     raeburn  8362:         my $homeserver;
                   8363:         if (&is_course($cdom,$cnum)) {
                   8364:             $homeserver = &homeserver($cnum,$cdom);
                   8365:         } else {
                   8366:             $homeserver = &domain($cdom,'primary');
                   8367:         }
                   8368:         if ($homeserver ne 'no_host') {
                   8369:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8370:         }
1.876     raeburn  8371:     }
1.506     raeburn  8372:     return $response;
                   8373: }
1.776     albertel 8374: 
1.506     raeburn  8375: sub auto_get_sections {
1.508     raeburn  8376:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8377:     my $homeserver;
                   8378:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8379:         $homeserver = &homeserver($cnum,$cdom);
                   8380:     }
                   8381:     if (!defined($homeserver)) { 
                   8382:         if ($cdom =~ /^$match_domain$/) {
                   8383:             $homeserver = &domain($cdom,'primary');
                   8384:         }
                   8385:     }
                   8386:     my @secs;
                   8387:     if (defined($homeserver)) {
                   8388:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8389:         unless ($response eq 'refused') {
                   8390:             @secs = split(/:/,$response);
                   8391:         }
1.506     raeburn  8392:     }
                   8393:     return @secs;
                   8394: }
1.776     albertel 8395: 
1.506     raeburn  8396: sub auto_new_course {
1.1099    raeburn  8397:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8398:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8399:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8400:     return $response;
                   8401: }
1.776     albertel 8402: 
1.506     raeburn  8403: sub auto_validate_courseID {
1.508     raeburn  8404:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8405:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8406:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8407:     return $response;
                   8408: }
1.776     albertel 8409: 
1.1007    raeburn  8410: sub auto_validate_instcode {
1.1020    raeburn  8411:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8412:     my ($homeserver,$response);
                   8413:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8414:         $homeserver = &homeserver($cnum,$cdom);
                   8415:     }
                   8416:     if (!defined($homeserver)) {
                   8417:         if ($cdom =~ /^$match_domain$/) {
                   8418:             $homeserver = &domain($cdom,'primary');
                   8419:         }
                   8420:     }
1.1065    raeburn  8421:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8422:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8423:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8424:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8425: }
                   8426: 
1.506     raeburn  8427: sub auto_create_password {
1.873     raeburn  8428:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8429:     my ($homeserver,$response);
1.506     raeburn  8430:     my $create_passwd = 0;
                   8431:     my $authchk = '';
1.873     raeburn  8432:     if ($udom =~ /^$match_domain$/) {
                   8433:         $homeserver = &domain($udom,'primary');
                   8434:     }
                   8435:     if ($homeserver eq '') {
                   8436:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8437:             $homeserver = &homeserver($cnum,$cdom);
                   8438:         }
                   8439:     }
                   8440:     if ($homeserver eq '') {
                   8441:         $authchk = 'nodomain';
1.506     raeburn  8442:     } else {
1.873     raeburn  8443:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8444:         if ($response eq 'refused') {
                   8445:             $authchk = 'refused';
                   8446:         } else {
1.901     albertel 8447:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8448:         }
1.506     raeburn  8449:     }
                   8450:     return ($authparam,$create_passwd,$authchk);
                   8451: }
                   8452: 
1.706     raeburn  8453: sub auto_photo_permission {
                   8454:     my ($cnum,$cdom,$students) = @_;
                   8455:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8456:     my ($outcome,$perm_reqd,$conditions) = 
                   8457: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8458:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8459: 	return (undef,undef);
                   8460:     }
1.706     raeburn  8461:     return ($outcome,$perm_reqd,$conditions);
                   8462: }
                   8463: 
                   8464: sub auto_checkphotos {
                   8465:     my ($uname,$udom,$pid) = @_;
                   8466:     my $homeserver = &homeserver($uname,$udom);
                   8467:     my ($result,$resulttype);
                   8468:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8469: 				   &escape($uname).':'.&escape($pid),
                   8470: 				   $homeserver));
1.709     albertel 8471:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8472: 	return (undef,undef);
                   8473:     }
1.706     raeburn  8474:     if ($outcome) {
                   8475:         ($result,$resulttype) = split(/:/,$outcome);
                   8476:     } 
                   8477:     return ($result,$resulttype);
                   8478: }
                   8479: 
                   8480: sub auto_photochoice {
                   8481:     my ($cnum,$cdom) = @_;
                   8482:     my $homeserver = &homeserver($cnum,$cdom);
                   8483:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8484: 						       &escape($cdom),
                   8485: 						       $homeserver)));
1.709     albertel 8486:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8487: 	return (undef,undef);
                   8488:     }
1.706     raeburn  8489:     return ($update,$comment);
                   8490: }
                   8491: 
                   8492: sub auto_photoupdate {
                   8493:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8494:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8495:     my $host=&hostname($homeserver);
1.706     raeburn  8496:     my $cmd = '';
                   8497:     my $maxtries = 1;
1.800     albertel 8498:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8499:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8500:     }
                   8501:     $cmd =~ s/%%$//;
                   8502:     $cmd = &escape($cmd);
                   8503:     my $query = 'institutionalphotos';
                   8504:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8505:     unless ($queryid=~/^\Q$host\E\_/) {
                   8506:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8507:         return 'error: '.$queryid;
                   8508:     }
                   8509:     my $reply = &get_query_reply($queryid);
                   8510:     my $tries = 1;
                   8511:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8512:         $reply = &get_query_reply($queryid);
                   8513:         $tries ++;
                   8514:     }
                   8515:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8516:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8517:     } else {
                   8518:         my @responses = split(/:/,$reply);
                   8519:         my $outcome = shift(@responses); 
                   8520:         foreach my $item (@responses) {
                   8521:             my ($key,$value) = split(/=/,$item);
                   8522:             $$photo{$key} = $value;
                   8523:         }
                   8524:         return $outcome;
                   8525:     }
                   8526:     return 'error';
                   8527: }
                   8528: 
1.521     raeburn  8529: sub auto_instcode_format {
1.793     albertel 8530:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8531: 	$cat_order) = @_;
1.521     raeburn  8532:     my $courses = '';
1.772     raeburn  8533:     my @homeservers;
1.521     raeburn  8534:     if ($caller eq 'global') {
1.841     albertel 8535: 	my %servers = &get_servers($codedom,'library');
                   8536: 	foreach my $tryserver (keys(%servers)) {
                   8537: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8538: 		push(@homeservers,$tryserver);
                   8539: 	    }
1.584     raeburn  8540:         }
1.1022    raeburn  8541:     } elsif ($caller eq 'requests') {
                   8542:         if ($codedom =~ /^$match_domain$/) {
                   8543:             my $chome = &domain($codedom,'primary');
                   8544:             unless ($chome eq 'no_host') {
                   8545:                 push(@homeservers,$chome);
                   8546:             }
                   8547:         }
1.521     raeburn  8548:     } else {
1.772     raeburn  8549:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8550:     }
1.793     albertel 8551:     foreach my $code (keys(%{$instcodes})) {
                   8552:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8553:     }
                   8554:     chop($courses);
1.772     raeburn  8555:     my $ok_response = 0;
                   8556:     my $response;
                   8557:     while (@homeservers > 0 && $ok_response == 0) {
                   8558:         my $server = shift(@homeservers); 
                   8559:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8560:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8561:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8562: 		split(/:/,$response);
1.772     raeburn  8563:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8564:             push(@{$codetitles},&str2array($codetitles_str));
                   8565:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8566:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8567:             $ok_response = 1;
                   8568:         }
                   8569:     }
                   8570:     if ($ok_response) {
1.521     raeburn  8571:         return 'ok';
1.772     raeburn  8572:     } else {
                   8573:         return $response;
1.521     raeburn  8574:     }
                   8575: }
                   8576: 
1.792     raeburn  8577: sub auto_instcode_defaults {
                   8578:     my ($domain,$returnhash,$code_order) = @_;
                   8579:     my @homeservers;
1.841     albertel 8580: 
                   8581:     my %servers = &get_servers($domain,'library');
                   8582:     foreach my $tryserver (keys(%servers)) {
                   8583: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8584: 	    push(@homeservers,$tryserver);
                   8585: 	}
1.792     raeburn  8586:     }
1.841     albertel 8587: 
1.792     raeburn  8588:     my $response;
1.841     albertel 8589:     foreach my $server (@homeservers) {
1.792     raeburn  8590:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8591:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8592: 	
                   8593: 	foreach my $pair (split(/\&/,$response)) {
                   8594: 	    my ($name,$value)=split(/\=/,$pair);
                   8595: 	    if ($name eq 'code_order') {
                   8596: 		@{$code_order} = split(/\&/,&unescape($value));
                   8597: 	    } else {
                   8598: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8599: 	    }
                   8600: 	}
                   8601: 	return 'ok';
1.792     raeburn  8602:     }
1.841     albertel 8603: 
                   8604:     return $response;
1.1003    raeburn  8605: }
                   8606: 
                   8607: sub auto_possible_instcodes {
1.1007    raeburn  8608:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8609:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8610:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8611:         return;
                   8612:     }
1.1003    raeburn  8613:     my (@homeservers,$uhome);
                   8614:     if (defined(&domain($domain,'primary'))) {
                   8615:         $uhome=&domain($domain,'primary');
                   8616:         push(@homeservers,&domain($domain,'primary'));
                   8617:     } else {
                   8618:         my %servers = &get_servers($domain,'library');
                   8619:         foreach my $tryserver (keys(%servers)) {
                   8620:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8621:                 push(@homeservers,$tryserver);
                   8622:             }
                   8623:         }
                   8624:     }
                   8625:     my $response;
                   8626:     foreach my $server (@homeservers) {
                   8627:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8628:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8629:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8630:             split(':',$response);
                   8631:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8632:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8633:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8634:             my ($name,$value)=split('=',$item);
                   8635:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8636:         }
                   8637:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8638:             my ($name,$value)=split('=',$item);
                   8639:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8640:         }
                   8641:         return 'ok';
                   8642:     }
                   8643:     return $response;
                   8644: }
1.792     raeburn  8645: 
1.1010    raeburn  8646: sub auto_courserequest_checks {
                   8647:     my ($dom) = @_;
1.1020    raeburn  8648:     my ($homeserver,%validations);
                   8649:     if ($dom =~ /^$match_domain$/) {
                   8650:         $homeserver = &domain($dom,'primary');
                   8651:     }
                   8652:     unless ($homeserver eq 'no_host') {
                   8653:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8654:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8655:             my @items = split(/&/,$response);
                   8656:             foreach my $item (@items) {
                   8657:                 my ($key,$value) = split('=',$item);
                   8658:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8659:             }
                   8660:         }
                   8661:     }
1.1010    raeburn  8662:     return %validations; 
                   8663: }
                   8664: 
1.1020    raeburn  8665: sub auto_courserequest_validation {
1.1255    raeburn  8666:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8667:     my ($homeserver,$response);
                   8668:     if ($dom =~ /^$match_domain$/) {
                   8669:         $homeserver = &domain($dom,'primary');
                   8670:     }
1.1255    raeburn  8671:     unless ($homeserver eq 'no_host') {
                   8672:         my $customdata;
                   8673:         if (ref($custominfo) eq 'HASH') {
                   8674:             $customdata = &freeze_escape($custominfo);
                   8675:         }
1.1020    raeburn  8676:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8677:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8678:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8679:                                     $customdata,$homeserver));
1.1020    raeburn  8680:     }
                   8681:     return $response;
                   8682: }
                   8683: 
1.777     albertel 8684: sub auto_validate_class_sec {
1.918     raeburn  8685:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8686:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8687:     my $ownerlist;
                   8688:     if (ref($owners) eq 'ARRAY') {
                   8689:         $ownerlist = join(',',@{$owners});
                   8690:     } else {
                   8691:         $ownerlist = $owners;
                   8692:     }
1.773     raeburn  8693:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8694:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8695:     return $response;
                   8696: }
                   8697: 
1.1248    raeburn  8698: sub auto_crsreq_update {
                   8699:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8700:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8701:     my ($homeserver,%crsreqresponse);
                   8702:     if ($cdom =~ /^$match_domain$/) {
                   8703:         $homeserver = &domain($cdom,'primary');
                   8704:     }
                   8705:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8706:         my $info;
                   8707:         if (ref($inbound) eq 'HASH') {
                   8708:             $info = &freeze_escape($inbound);
                   8709:         }
                   8710:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8711:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8712:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8713:                             &escape($title).':'.&escape($code).':'.
                   8714:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8715:                             $homeserver);
1.1248    raeburn  8716:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8717:             my @items = split(/&/,$response);
                   8718:             foreach my $item (@items) {
                   8719:                 my ($key,$value) = split('=',$item);
                   8720:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8721:             }
                   8722:         }
                   8723:     }
                   8724:     return \%crsreqresponse;
                   8725: }
                   8726: 
1.1305    raeburn  8727: sub auto_export_grades {
1.1309    raeburn  8728:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8729:     my ($homeserver,%exportresponse);
                   8730:     if ($cdom =~ /^$match_domain$/) {
                   8731:         $homeserver = &domain($cdom,'primary');
                   8732:     }
                   8733:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8734:         my $info;
                   8735:         if (ref($inforef) eq 'HASH') {
                   8736:             $info = &freeze_escape($inforef);
                   8737:         }
                   8738:         if (ref($gradesref) eq 'HASH') {
                   8739:             my $grades = &freeze_escape($gradesref);
                   8740:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8741:                                 $info.':'.$grades,$homeserver);
                   8742:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8743:                 my @items = split(/&/,$response);
                   8744:                 foreach my $item (@items) {
                   8745:                     my ($key,$value) = split('=',$item);
                   8746:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8747:                 }
                   8748:             }
                   8749:         }
                   8750:     }
                   8751:     return \%exportresponse;
1.1305    raeburn  8752: }
                   8753: 
1.1287    raeburn  8754: sub check_instcode_cloning {
                   8755:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8756:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8757:         return;
                   8758:     }
                   8759:     my $canclone;
                   8760:     if (@{$code_order} > 0) {
                   8761:         my $instcoderegexp ='^';
                   8762:         my @clonecodes = split(/\&/,$cloner);
                   8763:         foreach my $item (@{$code_order}) {
                   8764:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8765:                 foreach my $pair (@clonecodes) {
                   8766:                     my ($key,$val) = split(/\=/,$pair,2);
                   8767:                     $val = &unescape($val);
                   8768:                     if ($key eq $item) {
                   8769:                         $instcoderegexp .= '('.$val.')';
                   8770:                         last;
                   8771:                     }
                   8772:                 }
                   8773:             } else {
                   8774:                 $instcoderegexp .= $codedefaults->{$item};
                   8775:             }
                   8776:         }
                   8777:         $instcoderegexp .= '$';
                   8778:         my (@from,@to);
                   8779:         eval {
                   8780:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8781:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8782:         };
                   8783:         if ((@from > 0) && (@to > 0)) {
                   8784:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8785:             if (!@diffs) {
                   8786:                 $canclone = 1;
                   8787:             }
                   8788:         }
                   8789:     }
                   8790:     return $canclone;
                   8791: }
                   8792: 
                   8793: sub default_instcode_cloning {
                   8794:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   8795:     my (%codedefaults,@code_order,$canclone);
                   8796:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   8797:         %codedefaults = %{$codedefaultsref};
                   8798:         @code_order = @{$codeorderref};
                   8799:     } elsif ($clonedom) {
                   8800:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   8801:     }
                   8802:     if (($domdefclone) && (@code_order)) {
                   8803:         my @clonecodes = split(/\+/,$domdefclone);
                   8804:         my $instcoderegexp ='^';
                   8805:         foreach my $item (@code_order) {
                   8806:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   8807:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   8808:             } else {
                   8809:                 $instcoderegexp .= $codedefaults{$item};
                   8810:             }
                   8811:         }
                   8812:         $instcoderegexp .= '$';
                   8813:         my (@from,@to);
                   8814:         eval {
                   8815:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   8816:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   8817:         };
                   8818:         if ((@from > 0) && (@to > 0)) {
                   8819:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   8820:             if (!@diffs) {
                   8821:                 $canclone = 1;
                   8822:             }
                   8823:         }
                   8824:     }
                   8825:     return $canclone;
                   8826: }
                   8827: 
1.679     raeburn  8828: # ------------------------------------------------------- Course Group routines
                   8829: 
                   8830: sub get_coursegroups {
1.809     raeburn  8831:     my ($cdom,$cnum,$group,$namespace) = @_;
                   8832:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  8833: }
                   8834: 
1.679     raeburn  8835: sub modify_coursegroup {
                   8836:     my ($cdom,$cnum,$groupsettings) = @_;
                   8837:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   8838: }
                   8839: 
1.809     raeburn  8840: sub toggle_coursegroup_status {
                   8841:     my ($cdom,$cnum,$group,$action) = @_;
                   8842:     my ($from_namespace,$to_namespace);
                   8843:     if ($action eq 'delete') {
                   8844:         $from_namespace = 'coursegroups';
                   8845:         $to_namespace = 'deleted_groups';
                   8846:     } else {
                   8847:         $from_namespace = 'deleted_groups';
                   8848:         $to_namespace = 'coursegroups';
                   8849:     }
                   8850:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  8851:     if (my $tmp = &error(%curr_group)) {
                   8852:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   8853:         return ('read error',$tmp);
                   8854:     } else {
                   8855:         my %savedsettings = %curr_group; 
1.809     raeburn  8856:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  8857:         my $deloutcome;
                   8858:         if ($result eq 'ok') {
1.809     raeburn  8859:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  8860:         } else {
                   8861:             return ('write error',$result);
                   8862:         }
                   8863:         if ($deloutcome eq 'ok') {
                   8864:             return 'ok';
                   8865:         } else {
                   8866:             return ('delete error',$deloutcome);
                   8867:         }
                   8868:     }
                   8869: }
                   8870: 
1.679     raeburn  8871: sub modify_group_roles {
1.957     raeburn  8872:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  8873:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   8874:     my $role = 'gr/'.&escape($userprivs);
                   8875:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  8876:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  8877:     if ($result eq 'ok') {
                   8878:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   8879:     }
1.679     raeburn  8880:     return $result;
                   8881: }
                   8882: 
                   8883: sub modify_coursegroup_membership {
                   8884:     my ($cdom,$cnum,$membership) = @_;
                   8885:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   8886:     return $result;
                   8887: }
                   8888: 
1.682     raeburn  8889: sub get_active_groups {
                   8890:     my ($udom,$uname,$cdom,$cnum) = @_;
                   8891:     my $now = time;
                   8892:     my %groups = ();
                   8893:     foreach my $key (keys(%env)) {
1.811     albertel 8894:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  8895:             my ($start,$end) = split(/\./,$env{$key});
                   8896:             if (($end!=0) && ($end<$now)) { next; }
                   8897:             if (($start!=0) && ($start>$now)) { next; }
                   8898:             if ($1 eq $cdom && $2 eq $cnum) {
                   8899:                 $groups{$3} = $env{$key} ;
                   8900:             }
                   8901:         }
                   8902:     }
                   8903:     return %groups;
                   8904: }
                   8905: 
1.683     raeburn  8906: sub get_group_membership {
                   8907:     my ($cdom,$cnum,$group) = @_;
                   8908:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   8909: }
                   8910: 
                   8911: sub get_users_groups {
                   8912:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  8913:     my @usersgroups;
1.683     raeburn  8914:     my $cachetime=1800;
                   8915: 
                   8916:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  8917:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   8918:     if (defined($cached)) {
1.734     albertel 8919:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  8920:     } else {  
                   8921:         $grouplist = '';
1.816     raeburn  8922:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  8923:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  8924:         my $access_end = $env{'course.'.$courseid.
                   8925:                               '.default_enrollment_end_date'};
                   8926:         my $now = time;
                   8927:         foreach my $key (keys(%roleshash)) {
                   8928:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   8929:                 my $group = $1;
                   8930:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   8931:                     my $start = $2;
                   8932:                     my $end = $1;
                   8933:                     if ($start == -1) { next; } # deleted from group
                   8934:                     if (($start!=0) && ($start>$now)) { next; }
                   8935:                     if (($end!=0) && ($end<$now)) {
                   8936:                         if ($access_end && $access_end < $now) {
                   8937:                             if ($access_end - $end < 86400) {
                   8938:                                 push(@usersgroups,$group);
1.733     raeburn  8939:                             }
                   8940:                         }
1.817     raeburn  8941:                         next;
1.733     raeburn  8942:                     }
1.817     raeburn  8943:                     push(@usersgroups,$group);
1.683     raeburn  8944:                 }
                   8945:             }
                   8946:         }
1.817     raeburn  8947:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   8948:         $grouplist = join(':',@usersgroups);
                   8949:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  8950:     }
1.733     raeburn  8951:     return @usersgroups;
1.683     raeburn  8952: }
                   8953: 
                   8954: sub devalidate_getgroups_cache {
                   8955:     my ($udom,$uname,$cdom,$cnum)=@_;
                   8956:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 8957: 
1.683     raeburn  8958:     my $hashid="$udom:$uname:$courseid";
                   8959:     &devalidate_cache_new('getgroups',$hashid);
                   8960: }
                   8961: 
1.12      www      8962: # ------------------------------------------------------------------ Plain Text
                   8963: 
                   8964: sub plaintext {
1.988     raeburn  8965:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  8966:     if ($short =~ m{^cr/}) {
1.758     albertel 8967: 	return (split('/',$short))[-1];
                   8968:     }
1.742     raeburn  8969:     if (!defined($cid)) {
                   8970:         $cid = $env{'request.course.id'};
                   8971:     }
                   8972:     my %rolenames = (
1.1008    raeburn  8973:                       Course    => 'std',
                   8974:                       Community => 'alt1',
1.1305    raeburn  8975:                       Placement => 'std',
1.742     raeburn  8976:                     );
1.1037    raeburn  8977:     if ($cid ne '') {
                   8978:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   8979:             unless ($forcedefault) {
                   8980:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   8981:                 &Apache::lonlocal::mt_escape(\$roletext);
                   8982:                 return &Apache::lonlocal::mt($roletext);
                   8983:             }
                   8984:         }
                   8985:     }
                   8986:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   8987:         (defined($rolenames{$type})) && 
                   8988:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  8989:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  8990:     } elsif ($cid ne '') {
                   8991:         my $crstype = $env{'course.'.$cid.'.type'};
                   8992:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   8993:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   8994:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   8995:         }
1.742     raeburn  8996:     }
1.1037    raeburn  8997:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      8998: }
                   8999: 
                   9000: # ----------------------------------------------------------------- Assign Role
                   9001: 
                   9002: sub assignrole {
1.957     raeburn  9003:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9004:         $context)=@_;
1.21      www      9005:     my $mrole;
                   9006:     if ($role =~ /^cr\//) {
1.393     www      9007:         my $cwosec=$url;
1.811     albertel 9008:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9009: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9010:            my $refused = 1;
                   9011:            if ($context eq 'requestcourses') {
                   9012:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9013:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9014:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9015:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9016:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9017:                            if ($crsenv{'internal.courseowner'} eq
                   9018:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9019:                                $refused = '';
                   9020:                            }
                   9021:                        }
                   9022:                    }
                   9023:                }
                   9024:            }
                   9025:            if ($refused) {
                   9026:                &logthis('Refused custom assignrole: '.
                   9027:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9028:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9029:                return 'refused';
                   9030:            }
1.104     www      9031:         }
1.21      www      9032:         $mrole='cr';
1.678     raeburn  9033:     } elsif ($role =~ /^gr\//) {
                   9034:         my $cwogrp=$url;
1.811     albertel 9035:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9036:         unless (&allowed('mdg',$cwogrp)) {
                   9037:             &logthis('Refused group assignrole: '.
                   9038:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9039:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9040:             return 'refused';
                   9041:         }
                   9042:         $mrole='gr';
1.21      www      9043:     } else {
1.82      www      9044:         my $cwosec=$url;
1.811     albertel 9045:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9046:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9047:             my $refused;
                   9048:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9049:                 if (!(&allowed('c'.$role,$url))) {
                   9050:                     $refused = 1;
                   9051:                 }
                   9052:             } else {
                   9053:                 $refused = 1;
                   9054:             }
1.947     raeburn  9055:             if ($refused) {
1.1045    raeburn  9056:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9057:                 if (!$selfenroll && $context eq 'course') {
                   9058:                     my %crsenv;
                   9059:                     if ($role eq 'cc' || $role eq 'co') {
                   9060:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9061:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9062:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9063:                                 if ($crsenv{'internal.courseowner'} eq 
                   9064:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9065:                                     $refused = '';
                   9066:                                 }
                   9067:                             }
                   9068:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9069:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9070:                                 if ($crsenv{'internal.courseowner'} eq 
                   9071:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9072:                                     $refused = '';
                   9073:                                 }
                   9074:                             }
                   9075:                         }
                   9076:                     }
                   9077:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  9078:                     $refused = '';
1.1017    raeburn  9079:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9080:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9081:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9082:                         my $wrongcc;
                   9083:                         if ($cnum =~ /^$match_community$/) {
                   9084:                             $wrongcc = 1 if ($role eq 'cc');
                   9085:                         } else {
                   9086:                             $wrongcc = 1 if ($role eq 'co');
                   9087:                         }
                   9088:                         unless ($wrongcc) {
                   9089:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9090:                             if ($crsenv{'internal.courseowner'} eq 
                   9091:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9092:                                 $refused = '';
                   9093:                             }
1.1017    raeburn  9094:                         }
                   9095:                     }
1.1183    raeburn  9096:                 } elsif ($context eq 'requestauthor') {
                   9097:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9098:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9099:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9100:                             $refused = '';
                   9101:                         } else {
                   9102:                             my %domdefaults = &get_domain_defaults($udom);
                   9103:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9104:                                 my $checkbystatus;
                   9105:                                 if ($env{'user.adv'}) { 
                   9106:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9107:                                     if ($disposition eq 'automatic') {
                   9108:                                         $refused = '';
                   9109:                                     } elsif ($disposition eq '') {
                   9110:                                         $checkbystatus = 1;
                   9111:                                     } 
                   9112:                                 } else {
                   9113:                                     $checkbystatus = 1;
                   9114:                                 }
                   9115:                                 if ($checkbystatus) {
                   9116:                                     if ($env{'environment.inststatus'}) {
                   9117:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9118:                                         foreach my $type (@inststatuses) {
                   9119:                                             if (($type ne '') &&
                   9120:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9121:                                                 $refused = '';
                   9122:                                             }
                   9123:                                         }
                   9124:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9125:                                         $refused = '';
                   9126:                                     }
                   9127:                                 }
                   9128:                             }
                   9129:                         }
                   9130:                     }
1.1017    raeburn  9131:                 }
                   9132:                 if ($refused) {
1.947     raeburn  9133:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9134:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9135: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9136:                     return 'refused';
                   9137:                 }
1.932     raeburn  9138:             }
1.1131    raeburn  9139:         } elsif ($role eq 'au') {
                   9140:             if ($url ne '/'.$udom.'/') {
                   9141:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9142:                          ' to assign author role for '.$uname.':'.$udom.
                   9143:                          ' in domain: '.$url.' refused (wrong domain).');
                   9144:                 return 'refused';
                   9145:             }
1.104     www      9146:         }
1.21      www      9147:         $mrole=$role;
                   9148:     }
1.620     albertel 9149:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9150:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9151:     if ($end) { $command.='_'.$end; }
1.21      www      9152:     if ($start) {
                   9153: 	if ($end) { 
1.81      www      9154:            $command.='_'.$start; 
1.21      www      9155:         } else {
1.81      www      9156:            $command.='_0_'.$start;
1.21      www      9157:         }
                   9158:     }
1.739     raeburn  9159:     my $origstart = $start;
                   9160:     my $origend = $end;
1.957     raeburn  9161:     my $delflag;
1.357     www      9162: # actually delete
                   9163:     if ($deleteflag) {
1.373     www      9164: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9165: # modify command to delete the role
1.620     albertel 9166:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9167:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9168: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9169: # set start and finish to negative values for userrolelog
                   9170:            $start=-1;
                   9171:            $end=-1;
1.957     raeburn  9172:            $delflag = 1;
1.357     www      9173:         }
                   9174:     }
                   9175: # send command
1.349     www      9176:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9177: # log new user role if status is ok
1.349     www      9178:     if ($answer eq 'ok') {
1.663     raeburn  9179: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9180:         if (($role eq 'cc') || ($role eq 'in') ||
                   9181:             ($role eq 'ep') || ($role eq 'ad') ||
                   9182:             ($role eq 'ta') || ($role eq 'st') ||
                   9183:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9184:             ($role eq 'co')) {
1.1200    raeburn  9185: # for course roles, perform group memberships changes triggered by role change.
                   9186:             unless ($role =~ /^gr/) {
                   9187:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9188:                                                  $origstart,$selfenroll,$context);
                   9189:             }
1.1184    raeburn  9190:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9191:                            $selfenroll,$context);
                   9192:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9193:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9194:                  ($role eq 'da')) {
1.1184    raeburn  9195:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9196:                            $context);
                   9197:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9198:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9199:                              $context); 
                   9200:         }
1.1053    raeburn  9201:         if ($role eq 'cc') {
                   9202:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9203:         }
1.349     www      9204:     }
                   9205:     return $answer;
1.169     harris41 9206: }
                   9207: 
1.1053    raeburn  9208: sub autoupdate_coowners {
                   9209:     my ($url,$end,$start,$uname,$udom) = @_;
                   9210:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9211:     if (($cdom ne '') && ($cnum ne '')) {
                   9212:         my $now = time;
                   9213:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9214:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9215:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9216:             my $instcode = $coursehash{'internal.coursecode'};
                   9217:             if ($instcode ne '') {
1.1056    raeburn  9218:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9219:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9220:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9221:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9222:                         if ($result eq 'valid') {
                   9223:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9224:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9225:                                     push(@newcoowners,$coowner);
                   9226:                                 }
                   9227:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9228:                                     push(@newcoowners,$uname.':'.$udom);
                   9229:                                 }
                   9230:                                 @newcoowners = sort(@newcoowners);
                   9231:                             } else {
                   9232:                                 push(@newcoowners,$uname.':'.$udom);
                   9233:                             }
                   9234:                         } else {
                   9235:                             if ($coursehash{'internal.co-owners'}) {
                   9236:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9237:                                     unless ($coowner eq $uname.':'.$udom) {
                   9238:                                         push(@newcoowners,$coowner);
                   9239:                                     }
                   9240:                                 }
                   9241:                                 unless (@newcoowners > 0) {
                   9242:                                     $delcoowners = 1;
                   9243:                                     $coowners = '';
                   9244:                                 }
                   9245:                             }
                   9246:                         }
                   9247:                         if (@newcoowners || $delcoowners) {
                   9248:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9249:                                             $delcoowners,@newcoowners);
                   9250:                         }
                   9251:                     }
                   9252:                 }
                   9253:             }
                   9254:         }
                   9255:     }
                   9256: }
                   9257: 
                   9258: sub store_coowners {
                   9259:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9260:     my $cid = $cdom.'_'.$cnum;
                   9261:     my ($coowners,$delresult,$putresult);
                   9262:     if (@newcoowners) {
                   9263:         $coowners = join(',',@newcoowners);
                   9264:         my %coownershash = (
                   9265:                             'internal.co-owners' => $coowners,
                   9266:                            );
                   9267:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9268:         if ($putresult eq 'ok') {
                   9269:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9270:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9271:             }
                   9272:         }
                   9273:     }
                   9274:     if ($delcoowners) {
                   9275:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9276:         if ($delresult eq 'ok') {
                   9277:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9278:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9279:             }
                   9280:         }
                   9281:     }
                   9282:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9283:         my %crsinfo =
                   9284:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9285:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9286:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9287:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9288:         }
                   9289:     }
                   9290: }
                   9291: 
1.169     harris41 9292: # -------------------------------------------------- Modify user authentication
1.197     www      9293: # Overrides without validation
                   9294: 
1.169     harris41 9295: sub modifyuserauth {
                   9296:     my ($udom,$uname,$umode,$upass)=@_;
                   9297:     my $uhome=&homeserver($uname,$udom);
1.197     www      9298:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9299:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9300:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9301:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9302:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9303: 		     &escape($upass),$uhome);
1.620     albertel 9304:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9305:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9306:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9307:     &log($udom,,$uname,$uhome,
1.620     albertel 9308:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9309:                                      $env{'user.name'}.', '.$umode.
1.197     www      9310:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9311:     unless ($reply eq 'ok') {
1.197     www      9312:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9313: 	return 'error: '.$reply;
                   9314:     }   
1.170     harris41 9315:     return 'ok';
1.80      www      9316: }
                   9317: 
1.81      www      9318: # --------------------------------------------------------------- Modify a user
1.80      www      9319: 
1.81      www      9320: sub modifyuser {
1.206     matthew  9321:     my ($udom,    $uname, $uid,
                   9322:         $umode,   $upass, $first,
                   9323:         $middle,  $last,  $gene,
1.1058    raeburn  9324:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9325:     $udom= &LONCAPA::clean_domain($udom);
                   9326:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9327:     my $showcandelete = 'none';
                   9328:     if (ref($candelete) eq 'ARRAY') {
                   9329:         if (@{$candelete} > 0) {
                   9330:             $showcandelete = join(', ',@{$candelete});
                   9331:         }
                   9332:     }
1.81      www      9333:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9334:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9335: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9336:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9337:                                      ' desiredhome not specified'). 
1.620     albertel 9338:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9339:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9340:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9341:     my $newuser;
                   9342:     if ($uhome eq 'no_host') {
                   9343:         $newuser = 1;
                   9344:     }
1.80      www      9345: # ----------------------------------------------------------------- Create User
1.406     albertel 9346:     if (($uhome eq 'no_host') && 
                   9347: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      9348:         my $unhome='';
1.844     albertel 9349:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9350:             $unhome = $desiredhome;
1.620     albertel 9351: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9352: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9353:         } else { # load balancing routine for determining $unhome
1.81      www      9354:             my $loadm=10000000;
1.841     albertel 9355: 	    my %servers = &get_servers($udom,'library');
                   9356: 	    foreach my $tryserver (keys(%servers)) {
                   9357: 		my $answer=reply('load',$tryserver);
                   9358: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9359: 		    $loadm=$answer;
                   9360: 		    $unhome=$tryserver;
                   9361: 		}
1.80      www      9362: 	    }
                   9363:         }
                   9364:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9365: 	    return 'error: unable to find a home server for '.$uname.
                   9366:                    ' in domain '.$udom;
1.80      www      9367:         }
                   9368:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9369:                          &escape($upass),$unhome);
                   9370: 	unless ($reply eq 'ok') {
                   9371:             return 'error: '.$reply;
                   9372:         }   
1.230     stredwic 9373:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9374:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9375: 	    return 'error: unable verify users home machine.';
1.80      www      9376:         }
1.209     matthew  9377:     }   # End of creation of new user
1.80      www      9378: # ---------------------------------------------------------------------- Add ID
                   9379:     if ($uid) {
                   9380:        $uid=~tr/A-Z/a-z/;
                   9381:        my %uidhash=&idrget($udom,$uname);
1.196     www      9382:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9383:          && (!$forceid)) {
1.80      www      9384: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9385: 	      return 'error: user id "'.$uid.'" does not match '.
                   9386:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9387:           }
                   9388:        } else {
1.1300    raeburn  9389: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9390:        }
                   9391:     }
                   9392: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9393:     my @tmp=&get('environment',
1.899     raeburn  9394: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9395:                     'permanentemail','inststatus'],
1.134     albertel 9396: 		   $udom,$uname);
1.1075    raeburn  9397:     my (%names,%oldnames);
1.313     matthew  9398:     if ($tmp[0] =~ m/^error:.*/) { 
                   9399:         %names=(); 
                   9400:     } else {
                   9401:         %names = @tmp;
1.1075    raeburn  9402:         %oldnames = %names;
1.313     matthew  9403:     }
1.388     www      9404: #
1.1058    raeburn  9405: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9406: # of users did not contain them), do not overwrite existing values
                   9407: # unless field is in $candelete array ref.  
                   9408: #
                   9409: 
                   9410:     my @fields = ('firstname','middlename','lastname','generation',
                   9411:                   'permanentemail','id');
                   9412:     my %newvalues;
                   9413:     if (ref($candelete) eq 'ARRAY') {
                   9414:         foreach my $field (@fields) {
                   9415:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9416:                 if ($field eq 'firstname') {
                   9417:                     $names{$field} = $first;
                   9418:                 } elsif ($field eq 'middlename') {
                   9419:                     $names{$field} = $middle;
                   9420:                 } elsif ($field eq 'lastname') {
                   9421:                     $names{$field} = $last;
                   9422:                 } elsif ($field eq 'generation') { 
                   9423:                     $names{$field} = $gene;
                   9424:                 } elsif ($field eq 'permanentemail') {
                   9425:                     $names{$field} = $email;
                   9426:                 } elsif ($field eq 'id') {
                   9427:                     $names{$field}  = $uid;
                   9428:                 }
                   9429:             }
                   9430:         }
                   9431:     }
1.388     www      9432:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9433:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9434:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9435:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9436:     if ($email) {
                   9437:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9438:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9439:     }
1.899     raeburn  9440:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9441:     if (defined($inststatus)) {
                   9442:         $names{'inststatus'} = '';
                   9443:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9444:         if (ref($usertypes) eq 'HASH') {
                   9445:             my @okstatuses; 
                   9446:             foreach my $item (split(/:/,$inststatus)) {
                   9447:                 if (defined($usertypes->{$item})) {
                   9448:                     push(@okstatuses,$item);  
                   9449:                 }
                   9450:             }
                   9451:             if (@okstatuses) {
                   9452:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9453:             }
                   9454:         }
                   9455:     }
1.1075    raeburn  9456:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9457:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9458:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9459:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9460:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9461:     } else {
                   9462:         $logmsg .= ' during self creation';
                   9463:     }
1.1075    raeburn  9464:     my $changed;
                   9465:     if ($newuser) {
                   9466:         $changed = 1;
                   9467:     } else {
                   9468:         foreach my $field (@fields) {
                   9469:             if ($names{$field} ne $oldnames{$field}) {
                   9470:                 $changed = 1;
                   9471:                 last;
                   9472:             }
                   9473:         }
                   9474:     }
                   9475:     unless ($changed) {
                   9476:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9477:         &logthis($logmsg);
                   9478:         return 'ok';
                   9479:     }
                   9480:     my $reply = &put('environment', \%names, $udom,$uname);
                   9481:     if ($reply ne 'ok') { 
                   9482:         return 'error: '.$reply;
                   9483:     }
1.1087    raeburn  9484:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9485:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9486:     }
1.1075    raeburn  9487:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9488:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9489:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9490:     &logthis($logmsg);
1.134     albertel 9491:     return 'ok';
1.80      www      9492: }
                   9493: 
1.81      www      9494: # -------------------------------------------------------------- Modify student
1.80      www      9495: 
1.81      www      9496: sub modifystudent {
                   9497:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9498:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9499:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9500:     if (!$cid) {
1.620     albertel 9501: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9502: 	    return 'not_in_class';
                   9503: 	}
1.80      www      9504:     }
                   9505: # --------------------------------------------------------------- Make the user
1.81      www      9506:     my $reply=&modifyuser
1.209     matthew  9507: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9508:          $desiredhome,$email,$inststatus);
1.80      www      9509:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9510:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9511:     # student's environment
1.297     matthew  9512:     $uid = undef if (!$forceid);
1.455     albertel 9513:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9514:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9515:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9516:     return $reply;
                   9517: }
                   9518: 
                   9519: sub modify_student_enrollment {
1.1216    raeburn  9520:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9521:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9522:     my ($cdom,$cnum,$chome);
                   9523:     if (!$cid) {
1.620     albertel 9524: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9525: 	    return 'not_in_class';
                   9526: 	}
1.620     albertel 9527: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9528: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9529:     } else {
                   9530: 	($cdom,$cnum)=split(/_/,$cid);
                   9531:     }
1.620     albertel 9532:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9533:     if (!$chome) {
1.457     raeburn  9534: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9535:     }
1.455     albertel 9536:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9537:     # Make sure the user exists
1.81      www      9538:     my $uhome=&homeserver($uname,$udom);
                   9539:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9540: 	return 'error: no such user';
                   9541:     }
1.297     matthew  9542:     # Get student data if we were not given enough information
                   9543:     if (!defined($first)  || $first  eq '' || 
                   9544:         !defined($last)   || $last   eq '' || 
                   9545:         !defined($uid)    || $uid    eq '' || 
                   9546:         !defined($middle) || $middle eq '' || 
                   9547:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9548:         # They did not supply us with enough data to enroll the student, so
                   9549:         # we need to pick up more information.
1.297     matthew  9550:         my %tmp = &get('environment',
1.294     matthew  9551:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9552:                        ,$udom,$uname);
                   9553: 
1.800     albertel 9554:         #foreach my $key (keys(%tmp)) {
                   9555:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9556:         #}
1.294     matthew  9557:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9558:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9559:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9560:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9561:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9562:     }
1.556     albertel 9563:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9564:     my $user = "$uname:$udom";
                   9565:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9566:     my $reply=cput('classlist',
1.1148    raeburn  9567: 		   {$user => 
1.1314    raeburn  9568: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9569: 		   $cdom,$cnum);
1.1148    raeburn  9570:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9571:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9572:     } else { 
1.81      www      9573: 	return 'error: '.$reply;
                   9574:     }
1.297     matthew  9575:     # Add student role to user
1.83      www      9576:     my $uurl='/'.$cid;
1.81      www      9577:     $uurl=~s/\_/\//g;
                   9578:     if ($usec) {
                   9579: 	$uurl.='/'.$usec;
                   9580:     }
1.1148    raeburn  9581:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9582:                              $selfenroll,$context);
                   9583:     if ($result ne 'ok') {
                   9584:         if ($old_entry{$user} ne '') {
                   9585:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9586:         } else {
                   9587:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9588:         }
                   9589:     }
                   9590:     return $result; 
1.21      www      9591: }
                   9592: 
1.556     albertel 9593: sub format_name {
                   9594:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9595:     my $name;
                   9596:     if ($first ne 'lastname') {
                   9597: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9598:     } else {
                   9599: 	if ($lastname=~/\S/) {
                   9600: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9601: 	    $name=~s/\s+,/,/;
                   9602: 	} else {
                   9603: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9604: 	}
                   9605:     }
                   9606:     $name=~s/^\s+//;
                   9607:     $name=~s/\s+$//;
                   9608:     $name=~s/\s+/ /g;
                   9609:     return $name;
                   9610: }
                   9611: 
1.84      www      9612: # ------------------------------------------------- Write to course preferences
                   9613: 
                   9614: sub writecoursepref {
                   9615:     my ($courseid,%prefs)=@_;
                   9616:     $courseid=~s/^\///;
                   9617:     $courseid=~s/\_/\//g;
                   9618:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9619:     my $chome=homeserver($cnum,$cdomain);
                   9620:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9621: 	return 'error: no such course';
                   9622:     }
                   9623:     my $cstring='';
1.800     albertel 9624:     foreach my $pref (keys(%prefs)) {
                   9625: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9626:     }
1.84      www      9627:     $cstring=~s/\&$//;
                   9628:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9629: }
                   9630: 
                   9631: # ---------------------------------------------------------- Make/modify course
                   9632: 
                   9633: sub createcourse {
1.741     raeburn  9634:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9635:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9636:     $url=&declutter($url);
                   9637:     my $cid='';
1.1028    raeburn  9638:     if ($context eq 'requestcourses') {
                   9639:         my $can_create = 0;
                   9640:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9641:         if ($udom eq $ownerdom) {
                   9642:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9643:                                   $context)) {
                   9644:                 $can_create = 1;
                   9645:             }
                   9646:         } else {
                   9647:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9648:                                            $category);
                   9649:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9650:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9651:                 if (@curr > 0) {
                   9652:                     my @options = qw(approval validate autolimit);
                   9653:                     my $optregex = join('|',@options);
                   9654:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9655:                         $can_create = 1;
                   9656:                     }
                   9657:                 }
                   9658:             }
                   9659:         }
                   9660:         if ($can_create) {
                   9661:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9662:                 unless (&allowed('ccc',$udom)) {
                   9663:                     return 'refused'; 
                   9664:                 }
1.1017    raeburn  9665:             }
                   9666:         } else {
                   9667:             return 'refused';
                   9668:         }
1.1028    raeburn  9669:     } elsif (!&allowed('ccc',$udom)) {
                   9670:         return 'refused';
1.84      www      9671:     }
1.1011    raeburn  9672: # --------------------------------------------------------------- Get Unique ID
                   9673:     my $uname;
                   9674:     if ($cnum =~ /^$match_courseid$/) {
                   9675:         my $chome=&homeserver($cnum,$udom,'true');
                   9676:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9677:             $uname = $cnum;
                   9678:         } else {
1.1038    raeburn  9679:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9680:         }
                   9681:     } else {
1.1038    raeburn  9682:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9683:     }
                   9684:     return $uname if ($uname =~ /^error/);
                   9685: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9686:     if (!defined($course_server)) {
                   9687:         if (defined(&domain($udom,'primary'))) {
                   9688:             $course_server = &domain($udom,'primary');
                   9689:         } else {
                   9690:             $course_server = $env{'user.home'}; 
                   9691:         }
                   9692:     }
                   9693:     my %host_servers =
                   9694:         &Apache::lonnet::get_servers($udom,'library');
                   9695:     unless ($host_servers{$course_server}) {
                   9696:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9697:     }
1.84      www      9698: # ------------------------------------------------------------- Make the course
                   9699:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9700:                       $course_server);
1.84      www      9701:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9702:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9703:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9704: 	return 'error: no such course';
                   9705:     }
1.271     www      9706: # ----------------------------------------------------------------- Course made
1.516     raeburn  9707: # log existence
1.1029    raeburn  9708:     my $now = time;
1.918     raeburn  9709:     my $newcourse = {
                   9710:                     $udom.'_'.$uname => {
1.921     raeburn  9711:                                      description => $description,
                   9712:                                      inst_code   => $inst_code,
                   9713:                                      owner       => $course_owner,
                   9714:                                      type        => $crstype,
1.1029    raeburn  9715:                                      creator     => $env{'user.name'}.':'.
                   9716:                                                     $env{'user.domain'},
                   9717:                                      created     => $now,
                   9718:                                      context     => $context,
1.918     raeburn  9719:                                                 },
                   9720:                     };
1.921     raeburn  9721:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9722: # set toplevel url
1.271     www      9723:     my $topurl=$url;
                   9724:     unless ($nonstandard) {
                   9725: # ------------------------------------------ For standard courses, make top url
                   9726:         my $mapurl=&clutter($url);
1.278     www      9727:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9728:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9729: <map>
                   9730: <resource id="1" type="start"></resource>
                   9731: <resource id="2" src="$mapurl"></resource>
                   9732: <resource id="3" type="finish"></resource>
                   9733: <link index="1" from="1" to="2"></link>
                   9734: <link index="2" from="2" to="3"></link>
                   9735: </map>
                   9736: ENDINITMAP
                   9737:         $topurl=&declutter(
1.638     albertel 9738:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9739:                           );
                   9740:     }
                   9741: # ----------------------------------------------------------- Write preferences
1.84      www      9742:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9743:                      ('description'              => $description,
                   9744:                       'url'                      => $topurl,
                   9745:                       'internal.creator'         => $env{'user.name'}.':'.
                   9746:                                                     $env{'user.domain'},
                   9747:                       'internal.created'         => $now,
                   9748:                       'internal.creationcontext' => $context)
                   9749:                     );
1.84      www      9750:     return '/'.$udom.'/'.$uname;
                   9751: }
                   9752: 
1.1011    raeburn  9753: # ------------------------------------------------------------------- Create ID
                   9754: sub generate_coursenum {
1.1038    raeburn  9755:     my ($udom,$crstype) = @_;
1.1011    raeburn  9756:     my $domdesc = &domain($udom);
                   9757:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9758:     my $first;
                   9759:     if ($crstype eq 'Community') {
                   9760:         $first = '0';
                   9761:     } else {
                   9762:         $first = int(1+rand(9)); 
                   9763:     } 
                   9764:     my $uname=$first.
1.1011    raeburn  9765:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9766:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9767:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9768: # ----------------------------------------------- Make sure that does not exist
                   9769:     my $uhome=&homeserver($uname,$udom,'true');
                   9770:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  9771:         if ($crstype eq 'Community') {
                   9772:             $first = '0';
                   9773:         } else {
                   9774:             $first = int(1+rand(9));
                   9775:         }
                   9776:         $uname=$first.
1.1011    raeburn  9777:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   9778:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   9779:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   9780:         $uhome=&homeserver($uname,$udom,'true');
                   9781:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   9782:             return 'error: unable to generate unique course-ID';
                   9783:         }
                   9784:     }
                   9785:     return $uname;
                   9786: }
                   9787: 
1.813     albertel 9788: sub is_course {
1.1167    droeschl 9789:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   9790:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   9791: 
                   9792:     return unless $cdom and $cnum;
                   9793: 
                   9794:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   9795:         '.');
                   9796: 
1.1219    raeburn  9797:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 9798:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 9799: }
                   9800: 
1.1015    raeburn  9801: sub store_userdata {
                   9802:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  9803:     my $result;
1.1016    raeburn  9804:     if ($datakey ne '') {
1.1013    raeburn  9805:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  9806:             if ($udom eq '' || $uname eq '') {
                   9807:                 $udom = $env{'user.domain'};
                   9808:                 $uname = $env{'user.name'};
                   9809:             }
                   9810:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  9811:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   9812:                 $result = 'error: no_host';
                   9813:             } else {
                   9814:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   9815:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   9816: 
                   9817:                 my $namevalue='';
                   9818:                 foreach my $key (keys(%{$storehash})) {
                   9819:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   9820:                 }
                   9821:                 $namevalue=~s/\&$//;
1.1224    raeburn  9822:                 unless ($namespace eq 'courserequests') {
                   9823:                     $datakey = &escape($datakey);
                   9824:                 }
1.1105    raeburn  9825:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   9826:                                   $namevalue,$uhome);
1.1013    raeburn  9827:             }
                   9828:         } else {
                   9829:             $result = 'error: data to store was not a hash reference'; 
                   9830:         }
                   9831:     } else {
                   9832:         $result= 'error: invalid requestkey'; 
                   9833:     }
                   9834:     return $result;
                   9835: }
                   9836: 
1.21      www      9837: # ---------------------------------------------------------- Assign Custom Role
                   9838: 
                   9839: sub assigncustomrole {
1.957     raeburn  9840:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9841:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  9842:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      9843: }
                   9844: 
                   9845: # ----------------------------------------------------------------- Revoke Role
                   9846: 
                   9847: sub revokerole {
1.957     raeburn  9848:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9849:     my $now=time;
1.965     raeburn  9850:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      9851: }
                   9852: 
                   9853: # ---------------------------------------------------------- Revoke Custom Role
                   9854: 
                   9855: sub revokecustomrole {
1.957     raeburn  9856:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      9857:     my $now=time;
1.357     www      9858:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  9859:            $deleteflag,$selfenroll,$context);
1.17      www      9860: }
                   9861: 
1.533     banghart 9862: # ------------------------------------------------------------ Disk usage
1.535     albertel 9863: sub diskusage {
1.955     raeburn  9864:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   9865:     $directorypath =~ s/\/$//;
                   9866:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   9867:                        .&escape($getpropath).':'.&escape($uname).':'
                   9868:                        .&escape($udom),homeserver($uname,$udom));
                   9869:     if ($listing eq 'unknown_cmd') {
                   9870:         if ($getpropath) {
                   9871:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   9872:         }
                   9873:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   9874:     }
1.514     albertel 9875:     return $listing;
1.512     banghart 9876: }
                   9877: 
1.566     banghart 9878: sub is_locked {
1.1096    raeburn  9879:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 9880:     my @check;
                   9881:     my $is_locked;
1.1093    raeburn  9882:     push (@check,$file_name);
1.613     albertel 9883:     my %locked = &get('file_permissions',\@check,
1.620     albertel 9884: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 9885:     my ($tmp)=keys(%locked);
                   9886:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  9887:     
1.566     banghart 9888:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  9889:         $is_locked = 'false';
                   9890:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  9891:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  9892:                $is_locked = 'true';
1.1096    raeburn  9893:                if (ref($which) eq 'ARRAY') {
                   9894:                    push(@{$which},$entry);
                   9895:                } else {
                   9896:                    last;
                   9897:                }
1.745     raeburn  9898:            }
                   9899:        }
1.566     banghart 9900:     } else {
                   9901:         $is_locked = 'false';
                   9902:     }
1.1093    raeburn  9903:     return $is_locked;
1.566     banghart 9904: }
                   9905: 
1.759     albertel 9906: sub declutter_portfile {
                   9907:     my ($file) = @_;
1.833     albertel 9908:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 9909:     return $file;
                   9910: }
                   9911: 
1.559     banghart 9912: # ------------------------------------------------------------- Mark as Read Only
                   9913: 
                   9914: sub mark_as_readonly {
                   9915:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 9916:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 9917:     my ($tmp)=keys(%current_permissions);
                   9918:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 9919:     foreach my $file (@{$files}) {
1.759     albertel 9920: 	$file = &declutter_portfile($file);
1.561     banghart 9921:         push(@{$current_permissions{$file}},$what);
1.559     banghart 9922:     }
1.613     albertel 9923:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 9924:     return;
                   9925: }
                   9926: 
1.572     banghart 9927: # ------------------------------------------------------------Save Selected Files
                   9928: 
                   9929: sub save_selected_files {
                   9930:     my ($user, $path, @files) = @_;
                   9931:     my $filename = $user."savedfiles";
1.573     banghart 9932:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 9933:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 9934:     foreach my $file (@files) {
1.620     albertel 9935:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 9936:     }
                   9937:     foreach my $file (@other_files) {
1.574     banghart 9938:         print (OUT $file."\n");
1.572     banghart 9939:     }
1.574     banghart 9940:     close (OUT);
1.572     banghart 9941:     return 'ok';
                   9942: }
                   9943: 
1.574     banghart 9944: sub clear_selected_files {
                   9945:     my ($user) = @_;
                   9946:     my $filename = $user."savedfiles";
1.1117    foxr     9947:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 9948:     print (OUT undef);
                   9949:     close (OUT);
                   9950:     return ("ok");    
                   9951: }
                   9952: 
1.572     banghart 9953: sub files_in_path {
                   9954:     my ($user, $path) = @_;
                   9955:     my $filename = $user."savedfiles";
                   9956:     my %return_files;
1.1117    foxr     9957:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 9958:     while (my $line_in = <IN>) {
1.574     banghart 9959:         chomp ($line_in);
                   9960:         my @paths_and_file = split (m!/!, $line_in);
                   9961:         my $file_part = pop (@paths_and_file);
                   9962:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 9963:         $path_part.='/';
                   9964:         my $path_and_file = $path_part.$file_part;
                   9965:         if ($path_part eq $path) {
                   9966:             $return_files{$file_part}= 'selected';
                   9967:         }
                   9968:     }
1.574     banghart 9969:     close (IN);
                   9970:     return (\%return_files);
1.572     banghart 9971: }
                   9972: 
                   9973: # called in portfolio select mode, to show files selected NOT in current directory
                   9974: sub files_not_in_path {
                   9975:     my ($user, $path) = @_;
                   9976:     my $filename = $user."savedfiles";
                   9977:     my @return_files;
                   9978:     my $path_part;
1.1117    foxr     9979:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 9980:     while (my $line = <IN>) {
1.572     banghart 9981:         #ok, I know it's clunky, but I want it to work
1.800     albertel 9982:         my @paths_and_file = split(m|/|, $line);
                   9983:         my $file_part = pop(@paths_and_file);
                   9984:         chomp($file_part);
                   9985:         my $path_part = join('/', @paths_and_file);
1.572     banghart 9986:         $path_part .= '/';
                   9987:         my $path_and_file = $path_part.$file_part;
                   9988:         if ($path_part ne $path) {
1.800     albertel 9989:             push(@return_files, ($path_and_file));
1.572     banghart 9990:         }
                   9991:     }
1.800     albertel 9992:     close(OUT);
1.574     banghart 9993:     return (@return_files);
1.572     banghart 9994: }
                   9995: 
1.1273    raeburn  9996: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   9997:  
                   9998: sub portfiles_versioning {
                   9999:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10000:     my $portfolio_root = '/userfiles/portfolio';
                   10001:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10002:     foreach my $file (@{$portfiles}) {
                   10003:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10004:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10005:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10006:         my $getpropath = 1;
                   10007:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10008:                                              $stu_name,$getpropath);
                   10009:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10010:         my $new_answer = 
                   10011:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10012:         if ($new_answer ne 'problem getting file') {
                   10013:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10014:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10015:                               [$symb,$env{'request.course.id'},'graded']);
                   10016:         }
                   10017:     }
                   10018: }
                   10019: 
                   10020: sub get_next_version {
                   10021:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10022:     my $version;
                   10023:     if (ref($dir_list) eq 'ARRAY') {
                   10024:         foreach my $row (@{$dir_list}) {
                   10025:             my ($file) = split(/\&/,$row,2);
                   10026:             my ($file_name,$file_version,$file_ext) =
                   10027:                 &file_name_version_ext($file);
                   10028:             if (($file_name eq $answer_name) &&
                   10029:                 ($file_ext eq $answer_ext)) {
                   10030:                      # gets here if filename and extension match,
                   10031:                      # regardless of version
                   10032:                 if ($file_version ne '') {
                   10033:                     # a versioned file is found  so save it for later
                   10034:                     if ($file_version > $version) {
                   10035:                         $version = $file_version;
                   10036:                     }
                   10037:                 }
                   10038:             }
                   10039:         }
                   10040:     }
                   10041:     $version ++;
                   10042:     return($version);
                   10043: }
                   10044: 
                   10045: sub version_selected_portfile {
                   10046:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10047:     my ($answer_name,$answer_ver,$answer_ext) =
                   10048:         &file_name_version_ext($file_name);
                   10049:     my $new_answer;
                   10050:     $env{'form.copy'} =
                   10051:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10052:     if($env{'form.copy'} eq '-1') {
                   10053:         $new_answer = 'problem getting file';
                   10054:     } else {
                   10055:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10056:         my $copy_result = 
                   10057:             &finishuserfileupload($stu_name,$domain,'copy',
                   10058:                                   '/portfolio'.$directory.$new_answer);
                   10059:     }
                   10060:     undef($env{'form.copy'});
                   10061:     return ($new_answer);
                   10062: }
                   10063: 
                   10064: sub file_name_version_ext {
                   10065:     my ($file)=@_;
                   10066:     my @file_parts = split(/\./, $file);
                   10067:     my ($name,$version,$ext);
                   10068:     if (@file_parts > 1) {
                   10069:         $ext=pop(@file_parts);
                   10070:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10071:             $version=pop(@file_parts);
                   10072:         }
                   10073:         $name=join('.',@file_parts);
                   10074:     } else {
                   10075:         $name=join('.',@file_parts);
                   10076:     }
                   10077:     return($name,$version,$ext);
                   10078: }
                   10079: 
1.745     raeburn  10080: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10081: 
1.745     raeburn  10082: sub get_portfile_permissions {
                   10083:     my ($domain,$user) = @_;
1.613     albertel 10084:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10085:     my ($tmp)=keys(%current_permissions);
                   10086:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10087:     return \%current_permissions;
                   10088: }
                   10089: 
                   10090: #---------------------------------------------Get portfolio file access controls
                   10091: 
1.749     raeburn  10092: sub get_access_controls {
1.745     raeburn  10093:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10094:     my %access;
                   10095:     my $real_file = $file;
                   10096:     $file =~ s/\.meta$//;
1.745     raeburn  10097:     if (defined($file)) {
1.749     raeburn  10098:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10099:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10100:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10101:             }
                   10102:         }
1.745     raeburn  10103:     } else {
1.749     raeburn  10104:         foreach my $key (keys(%{$current_permissions})) {
                   10105:             if ($key =~ /\0accesscontrol$/) {
                   10106:                 if (defined($group)) {
                   10107:                     if ($key !~ m-^\Q$group\E/-) {
                   10108:                         next;
                   10109:                     }
                   10110:                 }
                   10111:                 my ($fullpath) = split(/\0/,$key);
                   10112:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10113:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10114:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10115:                     }
                   10116:                 }
                   10117:             }
                   10118:         }
                   10119:     }
                   10120:     return %access;
                   10121: }
                   10122: 
                   10123: sub modify_access_controls {
                   10124:     my ($file_name,$changes,$domain,$user)=@_;
                   10125:     my ($outcome,$deloutcome);
                   10126:     my %store_permissions;
                   10127:     my %new_values;
                   10128:     my %new_control;
                   10129:     my %translation;
                   10130:     my @deletions = ();
                   10131:     my $now = time;
                   10132:     if (exists($$changes{'activate'})) {
                   10133:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10134:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10135:             my $numnew = scalar(@newitems);
                   10136:             for (my $i=0; $i<$numnew; $i++) {
                   10137:                 my $newkey = $newitems[$i];
                   10138:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10139:                 if ($newkey =~ /^\d+:/) { 
                   10140:                     $newkey =~ s/^(\d+)/$newid/;
                   10141:                     $translation{$1} = $newid;
                   10142:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10143:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10144:                     $translation{$1} = $newid;
                   10145:                 }
1.749     raeburn  10146:                 $new_values{$file_name."\0".$newkey} = 
                   10147:                                           $$changes{'activate'}{$newitems[$i]};
                   10148:                 $new_control{$newkey} = $now;
                   10149:             }
                   10150:         }
                   10151:     }
                   10152:     my %todelete;
                   10153:     my %changed_items;
                   10154:     foreach my $action ('delete','update') {
                   10155:         if (exists($$changes{$action})) {
                   10156:             if (ref($$changes{$action}) eq 'HASH') {
                   10157:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10158:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10159:                     if ($action eq 'delete') { 
                   10160:                         $todelete{$itemnum} = 1;
                   10161:                     } else {
                   10162:                         $changed_items{$itemnum} = $key;
                   10163:                     }
                   10164:                 }
1.745     raeburn  10165:             }
                   10166:         }
1.749     raeburn  10167:     }
                   10168:     # get lock on access controls for file.
                   10169:     my $lockhash = {
                   10170:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10171:                                                        ':'.$env{'user.domain'},
                   10172:                    }; 
                   10173:     my $tries = 0;
                   10174:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10175:    
1.1288    damieng  10176:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10177:         $tries ++;
1.1289    damieng  10178:         sleep(0.1);
1.749     raeburn  10179:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10180:     }
                   10181:     if ($gotlock eq 'ok') {
                   10182:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10183:         my ($tmp)=keys(%curr_permissions);
                   10184:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10185:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10186:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10187:             if (ref($curr_controls) eq 'HASH') {
                   10188:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10189:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10190:                     if (defined($todelete{$itemnum})) {
                   10191:                         push(@deletions,$file_name."\0".$control_item);
                   10192:                     } else {
                   10193:                         if (defined($changed_items{$itemnum})) {
                   10194:                             $new_control{$changed_items{$itemnum}} = $now;
                   10195:                             push(@deletions,$file_name."\0".$control_item);
                   10196:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10197:                         } else {
                   10198:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10199:                         }
                   10200:                     }
1.745     raeburn  10201:                 }
                   10202:             }
                   10203:         }
1.970     raeburn  10204:         my ($group);
                   10205:         if (&is_course($domain,$user)) {
                   10206:             ($group,my $file) = split(/\//,$file_name,2);
                   10207:         }
1.749     raeburn  10208:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10209:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10210:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10211:         #  remove lock
                   10212:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10213:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10214:         my $sqlresult =
1.970     raeburn  10215:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10216:                                     $group);
1.749     raeburn  10217:     } else {
                   10218:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10219:     }
1.749     raeburn  10220:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10221: }
                   10222: 
1.827     raeburn  10223: sub make_public_indefinitely {
1.1271    raeburn  10224:     my (@requrl) = @_;
                   10225:     return &automated_portfile_access('public',\@requrl);
                   10226: }
                   10227: 
                   10228: sub automated_portfile_access {
                   10229:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10230:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10231:         return 'invalid';
                   10232:     }
1.1271    raeburn  10233:     my %urls;
                   10234:     if (ref($addsref) eq 'ARRAY') {
                   10235:         foreach my $requrl (@{$addsref}) {
                   10236:             if (&is_portfolio_url($requrl)) {
                   10237:                 unless (exists($urls{$requrl})) {
                   10238:                     $urls{$requrl} = 'add';
                   10239:                 }
                   10240:             }
                   10241:         }
                   10242:     }
                   10243:     if (ref($delsref) eq 'ARRAY') {
                   10244:         foreach my $requrl (@{$delsref}) { 
                   10245:             if (&is_portfolio_url($requrl)) {
                   10246:                 unless (exists($urls{$requrl})) {
                   10247:                     $urls{$requrl} = 'delete'; 
                   10248:                 }
                   10249:             }
                   10250:         }
                   10251:     }
                   10252:     unless (keys(%urls)) {
                   10253:         return 'invalid';
                   10254:     }
                   10255:     my $ip;
                   10256:     if ($accesstype eq 'ip') {
                   10257:         if (ref($info) eq 'HASH') {
                   10258:             if ($info->{'ip'} ne '') {
                   10259:                 $ip = $info->{'ip'};
                   10260:             }
                   10261:         }
                   10262:         if ($ip eq '') {
                   10263:             return 'invalid';
                   10264:         }
                   10265:     }
                   10266:     my $errors;
1.827     raeburn  10267:     my $now = time;
1.1271    raeburn  10268:     my %current_perms;
                   10269:     foreach my $requrl (sort(keys(%urls))) {
                   10270:         my $action;
                   10271:         if ($urls{$requrl} eq 'add') {
                   10272:             $action = 'activate';
                   10273:         } else {
                   10274:             $action = 'none';
                   10275:         }
                   10276:         my $aclnum = 0;
1.827     raeburn  10277:         my (undef,$udom,$unum,$file_name,$group) =
                   10278:             &parse_portfolio_url($requrl);
1.1271    raeburn  10279:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10280:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10281:         }
                   10282:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10283:                                                    $group,$file_name);
                   10284:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10285:             my ($num,$scope,$end,$start) = 
                   10286:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10287:             if ($scope eq $accesstype) {
                   10288:                 if (($start <= $now) && ($end == 0)) {
                   10289:                     if ($accesstype eq 'ip') {
                   10290:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10291:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10292:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10293:                                     if ($urls{$requrl} eq 'add') {
                   10294:                                         $action = 'none';
                   10295:                                         last;
                   10296:                                     } else {
                   10297:                                         $action = 'delete';
                   10298:                                         $aclnum = $num;
                   10299:                                         last;
                   10300:                                     }
                   10301:                                 }
                   10302:                             }
                   10303:                         }
                   10304:                     } elsif ($accesstype eq 'public') {
                   10305:                         if ($urls{$requrl} eq 'add') {
                   10306:                             $action = 'none';
                   10307:                             last;
                   10308:                         } else {
                   10309:                             $action = 'delete';
                   10310:                             $aclnum = $num;
                   10311:                             last;
                   10312:                         }
                   10313:                     }
                   10314:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10315:                     $action = 'update';
                   10316:                     $aclnum = $num;
1.1271    raeburn  10317:                     last;
1.827     raeburn  10318:                 }
                   10319:             }
                   10320:         }
                   10321:         if ($action eq 'none') {
1.1271    raeburn  10322:             next;
1.827     raeburn  10323:         } else {
                   10324:             my %changes;
                   10325:             my $newend = 0;
                   10326:             my $newstart = $now;
1.1271    raeburn  10327:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10328:             $changes{$action}{$newkey} = {
1.1271    raeburn  10329:                 type => $accesstype,
1.827     raeburn  10330:                 time => {
                   10331:                     start => $newstart,
                   10332:                     end   => $newend,
                   10333:                 },
                   10334:             };
1.1271    raeburn  10335:             if ($accesstype eq 'ip') {
                   10336:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10337:             }
1.827     raeburn  10338:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10339:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10340:             unless ($outcome eq 'ok') {
                   10341:                 $errors .= $outcome.' ';
                   10342:             }
1.827     raeburn  10343:         }
1.1271    raeburn  10344:     }
                   10345:     if ($errors) {
                   10346:         $errors =~ s/\s$//;
                   10347:         return $errors;
1.827     raeburn  10348:     } else {
1.1271    raeburn  10349:         return 'ok';
1.827     raeburn  10350:     }
                   10351: }
                   10352: 
1.745     raeburn  10353: #------------------------------------------------------Get Marked as Read Only
                   10354: 
                   10355: sub get_marked_as_readonly {
                   10356:     my ($domain,$user,$what,$group) = @_;
                   10357:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10358:     my @readonly_files;
1.629     banghart 10359:     my $cmp1=$what;
                   10360:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10361:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10362:         if (defined($group)) {
                   10363:             if ($file_name !~ m-^\Q$group\E/-) {
                   10364:                 next;
                   10365:             }
                   10366:         }
1.561     banghart 10367:         if (ref($value) eq "ARRAY"){
                   10368:             foreach my $stored_what (@{$value}) {
1.629     banghart 10369:                 my $cmp2=$stored_what;
1.759     albertel 10370:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10371:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10372:                 }
1.629     banghart 10373:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10374:                     push(@readonly_files, $file_name);
1.745     raeburn  10375:                     last;
1.563     banghart 10376:                 } elsif (!defined($what)) {
                   10377:                     push(@readonly_files, $file_name);
1.745     raeburn  10378:                     last;
1.561     banghart 10379:                 }
                   10380:             }
1.745     raeburn  10381:         }
1.561     banghart 10382:     }
                   10383:     return @readonly_files;
                   10384: }
1.577     banghart 10385: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10386: 
1.577     banghart 10387: sub get_marked_as_readonly_hash {
1.745     raeburn  10388:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10389:     my %readonly_files;
1.745     raeburn  10390:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10391:         if (defined($group)) {
                   10392:             if ($file_name !~ m-^\Q$group\E/-) {
                   10393:                 next;
                   10394:             }
                   10395:         }
1.577     banghart 10396:         if (ref($value) eq "ARRAY"){
                   10397:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10398:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10399:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10400:                         if ($lock_descriptor eq 'graded') {
                   10401:                             $readonly_files{$file_name} = 'graded';
                   10402:                         } elsif ($lock_descriptor eq 'handback') {
                   10403:                             $readonly_files{$file_name} = 'handback';
                   10404:                         } else {
                   10405:                             if (!exists($readonly_files{$file_name})) {
                   10406:                                 $readonly_files{$file_name} = 'locked';
                   10407:                             }
                   10408:                         }
1.745     raeburn  10409:                     }
1.750     banghart 10410:                 } 
1.577     banghart 10411:             }
                   10412:         } 
                   10413:     }
                   10414:     return %readonly_files;
                   10415: }
1.559     banghart 10416: # ------------------------------------------------------------ Unmark as Read Only
                   10417: 
                   10418: sub unmark_as_readonly {
1.629     banghart 10419:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10420:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10421:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10422:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10423:     my $symb_crs = $what;
                   10424:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10425:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10426:     my ($tmp)=keys(%current_permissions);
                   10427:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10428:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10429:     foreach my $file (@readonly_files) {
1.759     albertel 10430: 	my $clean_file = &declutter_portfile($file);
                   10431: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10432: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10433:         my @new_locks;
                   10434:         my @del_keys;
                   10435:         if (ref($current_locks) eq "ARRAY"){
                   10436:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10437:                 my $compare=$locker;
1.749     raeburn  10438:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10439:                     $compare=join('',@{$locker});
1.746     raeburn  10440:                     if ($compare ne $symb_crs) {
                   10441:                         push(@new_locks, $locker);
                   10442:                     }
1.563     banghart 10443:                 }
                   10444:             }
1.650     albertel 10445:             if (scalar(@new_locks) > 0) {
1.563     banghart 10446:                 $current_permissions{$file} = \@new_locks;
                   10447:             } else {
                   10448:                 push(@del_keys, $file);
1.613     albertel 10449:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10450:                 delete($current_permissions{$file});
1.563     banghart 10451:             }
                   10452:         }
1.561     banghart 10453:     }
1.613     albertel 10454:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10455:     return;
                   10456: }
1.512     banghart 10457: 
1.17      www      10458: # ------------------------------------------------------------ Directory lister
                   10459: 
                   10460: sub dirlist {
1.955     raeburn  10461:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10462:     $uri=~s/^\///;
                   10463:     $uri=~s/\/$//;
1.253     stredwic 10464:     my ($udom, $uname);
1.955     raeburn  10465:     if ($getuserdir) {
1.253     stredwic 10466:         $udom = $userdomain;
                   10467:         $uname = $username;
1.955     raeburn  10468:     } else {
                   10469:         (undef,$udom,$uname)=split(/\//,$uri);
                   10470:         if(defined($userdomain)) {
                   10471:             $udom = $userdomain;
                   10472:         }
                   10473:         if(defined($username)) {
                   10474:             $uname = $username;
                   10475:         }
1.253     stredwic 10476:     }
1.955     raeburn  10477:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10478: 
1.955     raeburn  10479:     $dirRoot = $perlvar{'lonDocRoot'};
                   10480:     if (defined($getpropath)) {
                   10481:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10482:         $dirRoot =~ s/\/$//;
1.955     raeburn  10483:     } elsif (defined($getuserdir)) {
                   10484:         my $subdir=$uname.'__';
                   10485:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10486:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10487:                    ."/$udom/$subdir/$uname";
                   10488:     } elsif (defined($alternateRoot)) {
                   10489:         $dirRoot = $alternateRoot;
1.751     banghart 10490:     }
1.253     stredwic 10491: 
                   10492:     if($udom) {
                   10493:         if($uname) {
1.1135    raeburn  10494:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10495:             if ($uhome eq 'no_host') {
                   10496:                 return ([],'no_host');
                   10497:             }
1.955     raeburn  10498:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10499:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10500:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10501:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10502:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10503:             } else {
                   10504:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10505:             }
1.605     matthew  10506:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10507:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10508:                 @listing_results = split(/:/,$listing);
                   10509:             } else {
                   10510:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10511:             }
1.1135    raeburn  10512:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10513:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10514:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10515:                 return ([],$listing);
                   10516:             } else {
                   10517:                 return (\@listing_results);
1.1135    raeburn  10518:             }
1.955     raeburn  10519:         } elsif(!$alternateRoot) {
1.1136    raeburn  10520:             my (%allusers,%listerror);
1.841     albertel 10521: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10522:  	    foreach my $tryserver (keys(%servers)) {
                   10523:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10524:                                   &escape($udom),$tryserver);
                   10525:                 if ($listing eq 'unknown_cmd') {
                   10526: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10527: 				      $udom, $tryserver);
                   10528:                 } else {
                   10529:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10530:                 }
1.841     albertel 10531: 		if ($listing eq 'unknown_cmd') {
                   10532: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10533: 				      $udom, $tryserver);
                   10534: 		    @listing_results = split(/:/,$listing);
                   10535: 		} else {
                   10536: 		    @listing_results =
                   10537: 			map { &unescape($_); } split(/:/,$listing);
                   10538: 		}
1.1136    raeburn  10539:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10540:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10541:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10542:                     $listerror{$tryserver} = $listing;
                   10543:                 } else {
1.841     albertel 10544: 		    foreach my $line (@listing_results) {
                   10545: 			my ($entry) = split(/&/,$line,2);
                   10546: 			$allusers{$entry} = 1;
                   10547: 		    }
                   10548: 		}
1.253     stredwic 10549:             }
1.1136    raeburn  10550:             my @alluserslist=();
1.800     albertel 10551:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10552:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10553:             }
1.1318    droeschl 10554: 
                   10555:             if (!%listerror) {
                   10556:                 # no errors
                   10557:                 return (\@alluserslist);
                   10558:             } elsif (scalar(keys(%servers)) == 1) {
                   10559:                 # one library server, one error 
                   10560:                 my ($key) = keys(%listerror);
                   10561:                 return (\@alluserslist, $listerror{$key});
                   10562:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10563:                 # con_lost indicates that we might miss data from at least one
                   10564:                 # library server
                   10565:                 return (\@alluserslist, 'con_lost');
                   10566:             } else {
                   10567:                 # multiple library servers and no con_lost -> data should be
                   10568:                 # complete. 
                   10569:                 return (\@alluserslist);
                   10570:             }
                   10571: 
1.253     stredwic 10572:         } else {
1.1136    raeburn  10573:             return ([],'missing username');
1.253     stredwic 10574:         }
1.955     raeburn  10575:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10576:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10577:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10578:         return (\@all_domains);
1.955     raeburn  10579:     } else {
1.1136    raeburn  10580:         return ([],'missing domain');
1.275     stredwic 10581:     }
                   10582: }
                   10583: 
                   10584: # --------------------------------------------- GetFileTimestamp
                   10585: # This function utilizes dirlist and returns the date stamp for
                   10586: # when it was last modified.  It will also return an error of -1
                   10587: # if an error occurs
                   10588: 
                   10589: sub GetFileTimestamp {
1.955     raeburn  10590:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10591:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10592:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10593:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10594:                                     undef,$getuserdir);
                   10595:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10596:         return -1;
                   10597:     }
                   10598:     if (ref($fileref) eq 'ARRAY') {
                   10599:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10600:         # @stats contains first the filename, then the stat output
                   10601:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10602:     } else {
                   10603:         return -1;
1.253     stredwic 10604:     }
1.26      www      10605: }
                   10606: 
1.712     albertel 10607: sub stat_file {
                   10608:     my ($uri) = @_;
1.787     albertel 10609:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10610: 
1.955     raeburn  10611:     my ($udom,$uname,$file);
1.712     albertel 10612:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10613: 	($udom,$uname,$file) =
1.811     albertel 10614: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10615: 	$file = 'userfiles/'.$file;
                   10616:     }
                   10617:     if ($uri =~ m-^/res/-) {
                   10618: 	($udom,$uname) = 
1.807     albertel 10619: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10620: 	$file = $uri;
                   10621:     }
                   10622: 
                   10623:     if (!$udom || !$uname || !$file) {
                   10624: 	# unable to handle the uri
                   10625: 	return ();
                   10626:     }
1.956     raeburn  10627:     my $getpropath;
                   10628:     if ($file =~ /^userfiles\//) {
                   10629:         $getpropath = 1;
                   10630:     }
1.1136    raeburn  10631:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10632:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10633:         return ();
                   10634:     } else {
                   10635:         if (ref($listref) eq 'ARRAY') {
                   10636:             my @stats = split('&',$listref->[0]);
                   10637: 	    shift(@stats); #filename is first
                   10638: 	    return @stats;
                   10639:         }
1.712     albertel 10640:     }
                   10641:     return ();
                   10642: }
                   10643: 
1.1313    raeburn  10644: # --------------------------------------------------------- recursedirs
                   10645: # Recursive function to traverse either a specific user's Authoring Space
                   10646: # or corresponding Published Resource Space, and populate the hash ref:
                   10647: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10648: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10649: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10650: # files in Authoring Space.
                   10651: #
                   10652: # Inputs:
                   10653: #
                   10654: # $is_home - true if current server is home server for user's space
                   10655: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10656: # $docroot - Document root (i.e., /home/httpd/html
                   10657: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10658: # $relpath - Current path (relative to top level).
                   10659: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10660: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10661: #
                   10662: # Returns: nothing
                   10663: #
                   10664: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10665: #
                   10666: # Currently used by interface/londocs.pm to create linked select boxes for
                   10667: # directory and filename to import a Course "Author" resource into a course, and
                   10668: # also to create linked select boxes for Authoring Space and Directory to choose
                   10669: # save location for creation of a new "standard" problem from the Course Editor.
                   10670: #
                   10671: 
                   10672: sub recursedirs {
                   10673:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10674:     return unless (ref($dirhashref) eq 'HASH');
                   10675:     my $currpath = $docroot.$toppath;
                   10676:     if ($relpath) {
                   10677:         $currpath .= "/$relpath";
                   10678:     }
                   10679:     my $savefile;
                   10680:     if (ref($filehashref)) {
                   10681:         $savefile = 1;
                   10682:     }
                   10683:     if ($is_home) {
                   10684:         if (opendir(my $dirh,$currpath)) {
                   10685:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10686:                 next if ($item eq '');
                   10687:                 if (-d "$currpath/$item") {
                   10688:                     my $newpath;
                   10689:                     if ($relpath) {
                   10690:                         $newpath = "$relpath/$item";
                   10691:                     } else {
                   10692:                         $newpath = $item;
                   10693:                     }
                   10694:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10695:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10696:                 } elsif ($savefile) {
                   10697:                     if ($context eq 'priv') {
                   10698:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10699:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10700:                         }
                   10701:                     } else {
                   10702:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10703:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10704:                         }
                   10705:                     }
                   10706:                 }
                   10707:             }
                   10708:             closedir($dirh);
                   10709:         }
                   10710:     } else {
                   10711:         my ($dirlistref,$listerror) =
                   10712:             &dirlist($toppath.$relpath);
                   10713:         my @dir_lines;
                   10714:         my $dirptr=16384;
                   10715:         if (ref($dirlistref) eq 'ARRAY') {
                   10716:             foreach my $dir_line (sort
                   10717:                               {
                   10718:                                   my ($afile)=split('&',$a,2);
                   10719:                                   my ($bfile)=split('&',$b,2);
                   10720:                                   return (lc($afile) cmp lc($bfile));
                   10721:                               } (@{$dirlistref})) {
                   10722:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10723:                     split(/\&/,$dir_line,16);
                   10724:                 $item =~ s/\s+$//;
                   10725:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10726:                 if ($dirptr&$testdir) {
                   10727:                     my $newpath;
                   10728:                     if ($relpath) {
                   10729:                         $newpath = "$relpath/$item";
                   10730:                     } else {
                   10731:                         $relpath = '/';
                   10732:                         $newpath = $item;
                   10733:                     }
                   10734:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10735:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10736:                 } elsif ($savefile) {
                   10737:                     if ($context eq 'priv') {
                   10738:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10739:                             $filehashref->{$relpath}{$item} = 1;
                   10740:                         }
                   10741:                     } else {
                   10742:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10743:                             $filehashref->{$relpath}{$item} = 1;
                   10744:                         }
                   10745:                     }
                   10746:                 }
                   10747:             }
                   10748:         }
                   10749:     }
                   10750:     return;
                   10751: }
                   10752: 
1.26      www      10753: # -------------------------------------------------------- Value of a Condition
                   10754: 
1.713     albertel 10755: # gets the value of a specific preevaluated condition
                   10756: #    stored in the string  $env{user.state.<cid>}
                   10757: # or looks up a condition reference in the bighash and if if hasn't
                   10758: # already been evaluated recurses into docondval to get the value of
                   10759: # the condition, then memoizing it to 
                   10760: #   $env{user.state.<cid>.<condition>}
1.40      www      10761: sub directcondval {
                   10762:     my $number=shift;
1.620     albertel 10763:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 10764: 	&Apache::lonuserstate::evalstate();
                   10765:     }
1.713     albertel 10766:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   10767: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   10768:     } elsif ($number =~ /^_/) {
                   10769: 	my $sub_condition;
                   10770: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   10771: 		&GDBM_READER(),0640)) {
                   10772: 	    $sub_condition=$bighash{'conditions'.$number};
                   10773: 	    untie(%bighash);
                   10774: 	}
                   10775: 	my $value = &docondval($sub_condition);
1.949     raeburn  10776: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 10777: 	return $value;
                   10778:     }
1.620     albertel 10779:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   10780:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      10781:     } else {
                   10782:        return 2;
                   10783:     }
                   10784: }
                   10785: 
1.713     albertel 10786: # get the collection of conditions for this resource
1.26      www      10787: sub condval {
                   10788:     my $condidx=shift;
1.54      www      10789:     my $allpathcond='';
1.713     albertel 10790:     foreach my $cond (split(/\|/,$condidx)) {
                   10791: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   10792: 	    $allpathcond.=
                   10793: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   10794: 	}
1.191     harris41 10795:     }
1.54      www      10796:     $allpathcond=~s/\|$//;
1.713     albertel 10797:     return &docondval($allpathcond);
                   10798: }
                   10799: 
                   10800: #evaluates an expression of conditions
                   10801: sub docondval {
                   10802:     my ($allpathcond) = @_;
                   10803:     my $result=0;
                   10804:     if ($env{'request.course.id'}
                   10805: 	&& defined($allpathcond)) {
                   10806: 	my $operand='|';
                   10807: 	my @stack;
                   10808: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   10809: 	    if ($chunk eq '(') {
                   10810: 		push @stack,($operand,$result);
                   10811: 	    } elsif ($chunk eq ')') {
                   10812: 		my $before=pop @stack;
                   10813: 		if (pop @stack eq '&') {
                   10814: 		    $result=$result>$before?$before:$result;
                   10815: 		} else {
                   10816: 		    $result=$result>$before?$result:$before;
                   10817: 		}
                   10818: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   10819: 		$operand=$chunk;
                   10820: 	    } else {
                   10821: 		my $new=directcondval($chunk);
                   10822: 		if ($operand eq '&') {
                   10823: 		    $result=$result>$new?$new:$result;
                   10824: 		} else {
                   10825: 		    $result=$result>$new?$result:$new;
                   10826: 		}
                   10827: 	    }
                   10828: 	}
1.26      www      10829:     }
                   10830:     return $result;
1.421     albertel 10831: }
                   10832: 
                   10833: # ---------------------------------------------------- Devalidate courseresdata
                   10834: 
                   10835: sub devalidatecourseresdata {
                   10836:     my ($coursenum,$coursedomain)=@_;
                   10837:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10838:     &devalidate_cache_new('courseres',$hashid);
1.28      www      10839: }
                   10840: 
1.763     www      10841: 
1.200     www      10842: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     10843: #
                   10844: #  Parameters:
                   10845: #      $coursenum    - Number of the course.
                   10846: #      $coursedomain - Domain at which the course was created.
                   10847: #  Returns:
                   10848: #     A hash of the course parameters along (I think) with timestamps
                   10849: #     and version info.
1.877     foxr     10850: 
1.624     albertel 10851: sub get_courseresdata {
                   10852:     my ($coursenum,$coursedomain)=@_;
1.200     www      10853:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   10854:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 10855:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 10856:     my %dumpreply;
1.417     albertel 10857:     unless (defined($cached)) {
1.624     albertel 10858: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 10859: 	$result=\%dumpreply;
1.251     albertel 10860: 	my ($tmp) = keys(%dumpreply);
                   10861: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 10862: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 10863: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   10864: 	    return $tmp;
1.416     albertel 10865: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 10866: 	    $result=undef;
1.599     albertel 10867: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 10868: 	}
                   10869:     }
1.624     albertel 10870:     return $result;
                   10871: }
                   10872: 
1.633     albertel 10873: sub devalidateuserresdata {
                   10874:     my ($uname,$udom)=@_;
                   10875:     my $hashid="$udom:$uname";
                   10876:     &devalidate_cache_new('userres',$hashid);
                   10877: }
                   10878: 
1.624     albertel 10879: sub get_userresdata {
                   10880:     my ($uname,$udom)=@_;
                   10881:     #most student don\'t have any data set, check if there is some data
                   10882:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   10883: 
                   10884:     my $hashid="$udom:$uname";
                   10885:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   10886:     if (!defined($cached)) {
                   10887: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   10888: 	$result=\%resourcedata;
                   10889: 	&do_cache_new('userres',$hashid,$result,600);
                   10890:     }
                   10891:     my ($tmp)=keys(%$result);
                   10892:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   10893: 	return $result;
                   10894:     }
                   10895:     #error 2 occurs when the .db doesn't exist
                   10896:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  10897:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   10898: 	    &logthis("<font color=\"blue\">WARNING:".
                   10899: 		     " Trying to get resource data for ".
                   10900: 		     $uname." at ".$udom.": ".
                   10901: 		     $tmp."</font>");
                   10902:         }
1.624     albertel 10903:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 10904: 	#&EXT_cache_set($udom,$uname);
                   10905: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 10906: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 10907:     }
                   10908:     return $tmp;
                   10909: }
1.879     foxr     10910: #----------------------------------------------- resdata - return resource data
                   10911: #  Purpose:
                   10912: #    Return resource data for either users or for a course.
                   10913: #  Parameters:
                   10914: #     $name      - Course/user name.
                   10915: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  10916: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  10917: #     $mapp      - decluttered URL of enclosing map  
                   10918: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   10919: #     $recurseup - Ref to array of map URLs, starting with map containing
                   10920: #                  $mapp up through hierarchy of nested maps to top level map.  
                   10921: #     $courseid  - CourseID (first part of param identifier).
                   10922: #     $modifier  - Middle part of param identifier.
                   10923: #     $what      - Last part of param identifier.
1.879     foxr     10924: #     @which     - Array of names of resources desired.
                   10925: #  Returns:
                   10926: #     The value of the first reasource in @which that is found in the
                   10927: #     resource hash.
                   10928: #  Exceptional Conditions:
                   10929: #     If the $type passed in is not valid (not the string 'course' or 
                   10930: #     'user', an undefined  reference is returned.
                   10931: #     If none of the resources are found, an undef is returned
1.624     albertel 10932: sub resdata {
1.1301    raeburn  10933:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   10934:         $modifier,$what,@which)=@_;
1.624     albertel 10935:     my $result;
                   10936:     if ($type eq 'course') {
                   10937: 	$result=&get_courseresdata($name,$domain);
                   10938:     } elsif ($type eq 'user') {
                   10939: 	$result=&get_userresdata($name,$domain);
                   10940:     }
                   10941:     if (!ref($result)) { return $result; }    
1.251     albertel 10942:     foreach my $item (@which) {
1.1301    raeburn  10943:         if ($item->[1] eq 'course') {
                   10944:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   10945:                 unless ($$recursed) {
1.1302    raeburn  10946:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  10947:                     $$recursed = 1;
                   10948:                 }
                   10949:                 foreach my $item (@${recurseup}) {
                   10950:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   10951:                     last if (defined($result->{$norecursechk}));
                   10952:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   10953:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   10954:                 }
                   10955:             }
                   10956:         }
                   10957:         if (defined($result->{$item->[0]})) {
1.927     albertel 10958: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 10959: 	}
1.250     albertel 10960:     }
1.291     albertel 10961:     return undef;
1.200     www      10962: }
                   10963: 
1.1298    raeburn  10964: sub get_domain_ltitools {
                   10965:     my ($cdom) = @_;
                   10966:     my %ltitools;
                   10967:     my ($result,$cached)=&is_cached_new('ltitools',$cdom);
                   10968:     if (defined($cached)) {
                   10969:         if (ref($result) eq 'HASH') {
                   10970:             %ltitools = %{$result};
                   10971:         }
                   10972:     } else {
                   10973:         my %domconfig = &get_dom('configuration',['ltitools'],$cdom);
                   10974:         if (ref($domconfig{'ltitools'}) eq 'HASH') {
                   10975:             %ltitools = %{$domconfig{'ltitools'}};
1.1344    raeburn  10976:             my %encdomconfig = &get_dom('encconfig',['ltitools'],$cdom);
                   10977:             if (ref($encdomconfig{'ltitools'}) eq 'HASH') {
                   10978:                 foreach my $id (keys(%ltitools)) {
                   10979:                     if (ref($encdomconfig{'ltitools'}{$id}) eq 'HASH') {
                   10980:                         foreach my $item ('key','secret') {
                   10981:                             $ltitools{$id}{$item} = $encdomconfig{'ltitools'}{$id}{$item};
                   10982:                         }
                   10983:                     }
                   10984:                 }
                   10985:             }
1.1298    raeburn  10986:         }
                   10987:         my $cachetime = 24*60*60;
                   10988:         &do_cache_new('ltitools',$cdom,\%ltitools,$cachetime);
                   10989:     }
                   10990:     return %ltitools;
                   10991: }
                   10992: 
1.1236    raeburn  10993: sub get_numsuppfiles {
                   10994:     my ($cnum,$cdom,$ignorecache)=@_;
                   10995:     my $hashid=$cnum.':'.$cdom;
                   10996:     my ($suppcount,$cached);
                   10997:     unless ($ignorecache) {
                   10998:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   10999:     }
                   11000:     unless (defined($cached)) {
                   11001:         my $chome=&homeserver($cnum,$cdom);
                   11002:         unless ($chome eq 'no_host') {
                   11003:             ($suppcount,my $errors) = (0,0);
                   11004:             my $suppmap = 'supplemental.sequence';
                   11005:             ($suppcount,$errors) = 
                   11006:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
                   11007:         }
                   11008:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11009:     }
                   11010:     return $suppcount;
                   11011: }
                   11012: 
1.379     matthew  11013: #
                   11014: # EXT resource caching routines
                   11015: #
                   11016: 
1.1302    raeburn  11017: {
                   11018: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11019: #
                   11020: # The course for which we cache
                   11021: my $cachedmapkey='';
                   11022: # The cached recursive maps for this course
                   11023: my %cachedmaps=();
                   11024: # When this was last done
                   11025: my $cachedmaptime='';
                   11026: 
1.379     matthew  11027: sub clear_EXT_cache_status {
1.383     albertel 11028:     &delenv('cache.EXT.');
1.379     matthew  11029: }
                   11030: 
                   11031: sub EXT_cache_status {
                   11032:     my ($target_domain,$target_user) = @_;
1.383     albertel 11033:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11034:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11035:         # We know already the user has no data
                   11036:         return 1;
                   11037:     } else {
                   11038:         return 0;
                   11039:     }
                   11040: }
                   11041: 
                   11042: sub EXT_cache_set {
                   11043:     my ($target_domain,$target_user) = @_;
1.383     albertel 11044:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11045:     #&appenv({$cachename => time});
1.379     matthew  11046: }
                   11047: 
1.28      www      11048: # --------------------------------------------------------- Value of a Variable
1.58      www      11049: sub EXT {
1.715     albertel 11050: 
1.1228    raeburn  11051:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11052:     unless ($varname) { return ''; }
1.218     albertel 11053:     #get real user name/domain, courseid and symb
                   11054:     my $courseid;
1.359     albertel 11055:     my $publicuser;
1.427     www      11056:     if ($symbparm) {
                   11057: 	$symbparm=&get_symb_from_alias($symbparm);
                   11058:     }
1.218     albertel 11059:     if (!($uname && $udom)) {
1.790     albertel 11060:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11061:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11062:     } else {
1.620     albertel 11063: 	$courseid=$env{'request.course.id'};
1.218     albertel 11064:     }
1.48      www      11065:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11066:     my $rest;
1.320     albertel 11067:     if (defined($therest[0])) {
1.48      www      11068:        $rest=join('.',@therest);
                   11069:     } else {
                   11070:        $rest='';
                   11071:     }
1.320     albertel 11072: 
1.57      www      11073:     my $qualifierrest=$qualifier;
                   11074:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11075:     my $spacequalifierrest=$space;
                   11076:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11077:     if ($realm eq 'user') {
1.48      www      11078: # --------------------------------------------------------------- user.resource
                   11079: 	if ($space eq 'resource') {
1.651     albertel 11080: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11081: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11082: 		 &&
1.744     albertel 11083: 		 ($symbparm eq &symbread()) ) {	
                   11084: 		# if we are in the middle of processing the resource the
                   11085: 		# get the value we are planning on committing
                   11086:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11087:                     return $Apache::lonhomework::results{$qualifierrest};
                   11088:                 } else {
                   11089:                     return $Apache::lonhomework::history{$qualifierrest};
                   11090:                 }
1.335     albertel 11091: 	    } else {
1.359     albertel 11092: 		my %restored;
1.620     albertel 11093: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11094: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11095: 		} else {
                   11096: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11097: 		}
1.335     albertel 11098: 		return $restored{$qualifierrest};
                   11099: 	    }
1.48      www      11100: # ----------------------------------------------------------------- user.access
                   11101:         } elsif ($space eq 'access') {
1.218     albertel 11102: 	    # FIXME - not supporting calls for a specific user
1.48      www      11103:             return &allowed($qualifier,$rest);
                   11104: # ------------------------------------------ user.preferences, user.environment
                   11105:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11106: 	    if (($uname eq $env{'user.name'}) &&
                   11107: 		($udom eq $env{'user.domain'})) {
                   11108: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11109: 	    } else {
1.359     albertel 11110: 		my %returnhash;
                   11111: 		if (!$publicuser) {
                   11112: 		    %returnhash=&userenvironment($udom,$uname,
                   11113: 						 $qualifierrest);
                   11114: 		}
1.218     albertel 11115: 		return $returnhash{$qualifierrest};
                   11116: 	    }
1.48      www      11117: # ----------------------------------------------------------------- user.course
                   11118:         } elsif ($space eq 'course') {
1.218     albertel 11119: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11120:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11121: # ------------------------------------------------------------------- user.role
                   11122:         } elsif ($space eq 'role') {
1.218     albertel 11123: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11124:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11125:             if ($qualifier eq 'value') {
                   11126: 		return $role;
                   11127:             } elsif ($qualifier eq 'extent') {
                   11128:                 return $where;
                   11129:             }
                   11130: # ----------------------------------------------------------------- user.domain
                   11131:         } elsif ($space eq 'domain') {
1.218     albertel 11132:             return $udom;
1.48      www      11133: # ------------------------------------------------------------------- user.name
                   11134:         } elsif ($space eq 'name') {
1.218     albertel 11135:             return $uname;
1.48      www      11136: # ---------------------------------------------------- Any other user namespace
1.29      www      11137:         } else {
1.359     albertel 11138: 	    my %reply;
                   11139: 	    if (!$publicuser) {
                   11140: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11141: 	    }
                   11142: 	    return $reply{$qualifierrest};
1.48      www      11143:         }
1.236     www      11144:     } elsif ($realm eq 'query') {
                   11145: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11146:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11147: 						[$spacequalifierrest]);
1.620     albertel 11148: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11149:    } elsif ($realm eq 'request') {
1.48      www      11150: # ------------------------------------------------------------- request.browser
                   11151:         if ($space eq 'browser') {
1.1145    bisitz   11152:             return $env{'browser.'.$qualifier};
1.57      www      11153: # ------------------------------------------------------------ request.filename
                   11154:         } else {
1.620     albertel 11155:             return $env{'request.'.$spacequalifierrest};
1.29      www      11156:         }
1.28      www      11157:     } elsif ($realm eq 'course') {
1.48      www      11158: # ---------------------------------------------------------- course.description
1.620     albertel 11159:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11160:     } elsif ($realm eq 'resource') {
1.165     www      11161: 
1.620     albertel 11162: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11163: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11164: 	}
1.693     albertel 11165: 
1.1232    raeburn  11166:         if ($qualifier eq '') {
                   11167: 	    if ($space eq 'title') {
                   11168: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11169: 	        return &gettitle($symbparm);
                   11170: 	    }
1.693     albertel 11171: 	
1.1232    raeburn  11172: 	    if ($space eq 'map') {
                   11173: 	        my ($map) = &decode_symb($symbparm);
                   11174: 	        return &symbread($map);
                   11175: 	    }
                   11176:             if ($space eq 'maptitle') {
                   11177:                 my ($map) = &decode_symb($symbparm);
                   11178:                 return &gettitle($map);
                   11179:             }
                   11180: 	    if ($space eq 'filename') {
                   11181: 	        if ($symbparm) {
                   11182: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11183: 	        }
                   11184: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11185: 	    }
1.1232    raeburn  11186: 
1.1233    raeburn  11187:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11188:                 if ($space eq 'visibleparts') {
                   11189:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11190:                     my $item;
                   11191:                     if (ref($navmap)) {
                   11192:                         my $res = $navmap->getBySymb($symbparm);
                   11193:                         my $parts = $res->parts();
                   11194:                         if (ref($parts) eq 'ARRAY') {
                   11195:                             $item = join(',',@{$parts});
                   11196:                         }
                   11197:                         undef($navmap);
1.1232    raeburn  11198:                     }
1.1233    raeburn  11199:                     return $item;
1.1232    raeburn  11200:                 }
                   11201:             }
                   11202:         }
1.693     albertel 11203: 
1.1301    raeburn  11204: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11205: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11206:         if (($courseid eq '') && ($cid)) {
                   11207:             $courseid = $cid;
                   11208:         }
                   11209: 	if (($symbparm && $courseid) && 
                   11210: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11211: 
1.218     albertel 11212: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11213: 
1.60      www      11214: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11215: 	    my $symbp=$symbparm;
1.1301    raeburn  11216: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11217: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11218:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11219: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11220: 	    if (($env{'user.name'} eq $uname) &&
                   11221: 		($env{'user.domain'} eq $udom)) {
                   11222: 		$section=$env{'request.course.sec'};
1.733     raeburn  11223:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11224:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11225: 	    } else {
1.539     albertel 11226: 		if (! defined($usection)) {
1.551     albertel 11227: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11228: 		} else {
                   11229: 		    $section = $usection;
                   11230: 		}
1.733     raeburn  11231:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11232: 	    }
                   11233: 
                   11234: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11235: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11236:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11237: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11238: 
1.593     albertel 11239: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11240: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11241:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11242: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11243: 
1.60      www      11244: # ----------------------------------------------------------- first, check user
1.624     albertel 11245: 
1.1301    raeburn  11246: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11247:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11248: 				       ([$courselevelr,'resource'],
                   11249: 					[$courselevelm,'map'     ],
1.1301    raeburn  11250:                                         [$courseleveli,'map'     ],
1.927     albertel 11251: 					[$courselevel, 'course'  ]));
1.931     albertel 11252: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11253: 
1.594     albertel 11254: # ------------------------------------------------ second, check some of course
1.684     raeburn  11255:             my $coursereply;
1.691     raeburn  11256:             if (@groups > 0) {
                   11257:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11258:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11259:                                        $mapp,\$recursed,\@recurseup);
                   11260:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11261:             }
1.96      www      11262: 
1.684     raeburn  11263: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11264: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11265: 				  'course',$mapp,\$recursed,\@recurseup,
                   11266:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11267: 				  ([$seclevelr,   'resource'],
                   11268: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11269:                                    [$secleveli,   'map'     ],
1.927     albertel 11270: 				   [$seclevel,    'course'  ],
                   11271: 				   [$courselevelr,'resource']));
                   11272: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11273: 
1.60      www      11274: # ------------------------------------------------------ third, check map parms
1.218     albertel 11275: 	    my %parmhash=();
                   11276: 	    my $thisparm='';
                   11277: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11278: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11279: 		    &GDBM_READER(),0640)) {
1.218     albertel 11280: 		$thisparm=$parmhash{$symbparm};
                   11281: 		untie(%parmhash);
                   11282: 	    }
1.927     albertel 11283: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11284: 	}
1.594     albertel 11285: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11286:  
                   11287:         my $what = $spacequalifierrest;
                   11288: 	$what=~s/\./\_/;
1.282     albertel 11289: 	my $filename;
                   11290: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11291: 	if ($symbparm) {
1.409     www      11292: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11293: 	} else {
1.620     albertel 11294: 	    $filename=$env{'request.filename'};
1.282     albertel 11295: 	}
1.1301    raeburn  11296: 	my $metadata=&metadata($filename,$what);
1.927     albertel 11297: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1301    raeburn  11298: 	$metadata=&metadata($filename,'parameter_'.$what);
1.927     albertel 11299: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11300: 
1.1301    raeburn  11301: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11302: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11303: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11304: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11305: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11306: 				     'course',$mapp,\$recursed,\@recurseup,
                   11307:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11308: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11309:                                       [$courseleveli,'map'   ],
1.927     albertel 11310: 				      [$courselevel, 'course']));
                   11311: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11312: 	}
1.145     www      11313: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11314: 	unless ($space eq '0') {
1.336     albertel 11315: 	    my @parts=split(/_/,$space);
                   11316: 	    my $id=pop(@parts);
                   11317: 	    my $part=join('_',@parts);
                   11318: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11319: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11320: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11321: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11322: 	}
1.395     albertel 11323: 	if ($recurse) { return undef; }
                   11324: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 11325: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11326: # ---------------------------------------------------- Any other user namespace
                   11327:     } elsif ($realm eq 'environment') {
                   11328: # ----------------------------------------------------------------- environment
1.620     albertel 11329: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11330: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11331: 	} else {
1.770     albertel 11332: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11333: 		return '';
                   11334: 	    }
1.219     albertel 11335: 	    my %returnhash=&userenvironment($udom,$uname,
                   11336: 					    $spacequalifierrest);
                   11337: 	    return $returnhash{$spacequalifierrest};
                   11338: 	}
1.28      www      11339:     } elsif ($realm eq 'system') {
1.48      www      11340: # ----------------------------------------------------------------- system.time
                   11341: 	if ($space eq 'time') {
                   11342: 	    return time;
                   11343:         }
1.696     albertel 11344:     } elsif ($realm eq 'server') {
                   11345: # ----------------------------------------------------------------- system.time
                   11346: 	if ($space eq 'name') {
                   11347: 	    return $ENV{'SERVER_NAME'};
                   11348:         }
1.28      www      11349:     }
1.48      www      11350:     return '';
1.61      www      11351: }
                   11352: 
1.927     albertel 11353: sub get_reply {
                   11354:     my ($reply_value) = @_;
1.940     raeburn  11355:     if (ref($reply_value) eq 'ARRAY') {
                   11356:         if (wantarray) {
                   11357: 	    return @$reply_value;
                   11358:         }
                   11359:         return $reply_value->[0];
                   11360:     } else {
                   11361:         return $reply_value;
1.927     albertel 11362:     }
                   11363: }
                   11364: 
1.691     raeburn  11365: sub check_group_parms {
1.1301    raeburn  11366:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11367:         $recursed,$recurseupref) = @_;
                   11368:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11369:                   [$what,'course']);
                   11370:     my $coursereply;
1.691     raeburn  11371:     foreach my $group (@{$groups}) {
1.1301    raeburn  11372:         my @groupitems = ();
1.691     raeburn  11373:         foreach my $level (@levels) {
1.927     albertel 11374:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11375:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11376:         }
1.1301    raeburn  11377:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11378:                                    $env{'course.'.$courseid.'.domain'},
                   11379:                                    'course',$mapp,$recursed,$recurseupref,
                   11380:                                    $courseid,'.['.$group.'].',$what,
                   11381:                                    @groupitems);
                   11382:         last if (defined($coursereply));
1.691     raeburn  11383:     }
                   11384:     return $coursereply;
                   11385: }
                   11386: 
1.1301    raeburn  11387: sub get_map_hierarchy {
1.1302    raeburn  11388:     my ($mapname,$courseid) = @_;
                   11389:     my @recurseup = ();
1.1301    raeburn  11390:     if ($mapname) {
1.1302    raeburn  11391:         if (($cachedmapkey eq $courseid) &&
                   11392:             (abs($cachedmaptime-time)<5)) {
                   11393:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11394:                 return @{$cachedmaps{$mapname}};
                   11395:             }
                   11396:         }
1.1301    raeburn  11397:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11398:         if (ref($navmap)) {
                   11399:             @recurseup = $navmap->recurseup_maps($mapname);
                   11400:             undef($navmap);
1.1302    raeburn  11401:             $cachedmaps{$mapname} = \@recurseup;
                   11402:             $cachedmaptime=time;
                   11403:             $cachedmapkey=$courseid;
1.1301    raeburn  11404:         }
                   11405:     }
                   11406:     return @recurseup;
                   11407: }
                   11408: 
1.1302    raeburn  11409: }
                   11410: 
1.691     raeburn  11411: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11412:     my ($courseid,@groups) = @_;
                   11413:     @groups = sort(@groups);
1.691     raeburn  11414:     return @groups;
                   11415: }
                   11416: 
1.395     albertel 11417: sub packages_tab_default {
                   11418:     my ($uri,$varname)=@_;
                   11419:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11420: 
                   11421:     my (@extension,@specifics,$do_default);
                   11422:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 11423: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11424: 	if ($pack_type eq 'default') {
                   11425: 	    $do_default=1;
                   11426: 	} elsif ($pack_type eq 'extension') {
                   11427: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11428: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11429: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11430: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11431: 	}
                   11432:     }
                   11433:     # first look for a package that matches the requested part id
                   11434:     foreach my $package (@specifics) {
                   11435: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11436: 	next if ($pack_part ne $part);
                   11437: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11438: 	    return $packagetab{"$pack_type&$name&default"};
                   11439: 	}
                   11440:     }
                   11441:     # look for any possible matching non extension_ package
                   11442:     foreach my $package (@specifics) {
                   11443: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11444: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11445: 	    return $packagetab{"$pack_type&$name&default"};
                   11446: 	}
1.585     albertel 11447: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11448: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11449: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11450: 	}
                   11451:     }
1.738     albertel 11452:     # look for any posible extension_ match
                   11453:     foreach my $package (@extension) {
                   11454: 	my ($package,$pack_type)=@{$package};
                   11455: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11456: 	    return $packagetab{"$pack_type&$name&default"};
                   11457: 	}
                   11458: 	if (defined($packagetab{$package."&$name&default"})) {
                   11459: 	    return $packagetab{$package."&$name&default"};
                   11460: 	}
                   11461:     }
                   11462:     # look for a global default setting
                   11463:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11464: 	return $packagetab{"default&$name&default"};
                   11465:     }
1.395     albertel 11466:     return undef;
                   11467: }
                   11468: 
1.334     albertel 11469: sub add_prefix_and_part {
                   11470:     my ($prefix,$part)=@_;
                   11471:     my $keyroot;
                   11472:     if (defined($prefix) && $prefix !~ /^__/) {
                   11473: 	# prefix that has a part already
                   11474: 	$keyroot=$prefix;
                   11475:     } elsif (defined($prefix)) {
                   11476: 	# prefix that is missing a part
                   11477: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11478:     } else {
                   11479: 	# no prefix at all
                   11480: 	if (defined($part)) { $keyroot='_'.$part; }
                   11481:     }
                   11482:     return $keyroot;
                   11483: }
                   11484: 
1.71      www      11485: # ---------------------------------------------------------------- Get metadata
                   11486: 
1.599     albertel 11487: my %metaentry;
1.1070    www      11488: my %importedpartids;
1.71      www      11489: sub metadata {
1.176     www      11490:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      11491:     $uri=&declutter($uri);
1.288     albertel 11492:     # if it is a non metadata possible uri return quickly
1.529     albertel 11493:     if (($uri eq '') || 
                   11494: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11495: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11496:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11497: 	return undef;
                   11498:     }
1.1261    raeburn  11499:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11500: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11501: 	return undef;
1.288     albertel 11502:     }
1.73      www      11503:     my $filename=$uri;
                   11504:     $uri=~s/\.meta$//;
1.172     www      11505: #
                   11506: # Is the metadata already cached?
1.177     www      11507: # Look at timestamp of caching
1.172     www      11508: # Everything is cached by the main uri, libraries are never directly cached
                   11509: #
1.428     albertel 11510:     if (!defined($liburi)) {
1.599     albertel 11511: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11512: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11513:     }
                   11514:     {
1.1069    www      11515: # Imported parts would go here
1.1070    www      11516:         my %importedids=();
                   11517:         my @origfileimportpartids=();
1.1069    www      11518:         my $importedparts=0;
1.172     www      11519: #
                   11520: # Is this a recursive call for a library?
                   11521: #
1.599     albertel 11522: #	if (! exists($metacache{$uri})) {
                   11523: #	    $metacache{$uri}={};
                   11524: #	}
1.924     albertel 11525: 	my $cachetime = 60*60;
1.171     www      11526:         if ($liburi) {
                   11527: 	    $liburi=&declutter($liburi);
                   11528:             $filename=$liburi;
1.401     bowersj2 11529:         } else {
1.599     albertel 11530: 	    &devalidate_cache_new('meta',$uri);
                   11531: 	    undef(%metaentry);
1.401     bowersj2 11532: 	}
1.140     www      11533:         my %metathesekeys=();
1.73      www      11534:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11535: 	my $metastring;
1.1140    www      11536: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11537: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11538: 	    $metastring = 
1.929     albertel 11539: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11540: 					  ('grade_target' => 'meta'));
                   11541: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11542: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11543:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11544: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11545: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11546: 	    $metastring=&getfile($file);
1.489     albertel 11547: 	}
1.208     albertel 11548:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11549:         my $token;
1.140     www      11550:         undef %metathesekeys;
1.71      www      11551:         while ($token=$parser->get_token) {
1.339     albertel 11552: 	    if ($token->[0] eq 'S') {
                   11553: 		if (defined($token->[2]->{'package'})) {
1.172     www      11554: #
                   11555: # This is a package - get package info
                   11556: #
1.339     albertel 11557: 		    my $package=$token->[2]->{'package'};
                   11558: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11559: 		    if (defined($token->[2]->{'id'})) { 
                   11560: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11561: 		    }
1.599     albertel 11562: 		    if ($metaentry{':packages'}) {
                   11563: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11564: 		    } else {
1.599     albertel 11565: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11566: 		    }
1.736     albertel 11567: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11568: 			my $part=$keyroot;
                   11569: 			$part=~s/^\_//;
1.736     albertel 11570: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11571: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11572: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11573: 			    # ignore package.tab specified default values
                   11574:                             # here &package_tab_default() will fetch those
                   11575: 			    if ($subp eq 'default') { next; }
1.736     albertel 11576: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11577: 			    my $unikey;
                   11578: 			    if ($pack =~ /_0$/) {
                   11579: 				$unikey='parameter_0_'.$name;
                   11580: 				$part=0;
                   11581: 			    } else {
                   11582: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11583: 			    }
1.339     albertel 11584: 			    if ($subp eq 'display') {
                   11585: 				$value.=' [Part: '.$part.']';
                   11586: 			    }
1.599     albertel 11587: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11588: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11589: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11590: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11591: 			    }
1.599     albertel 11592: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11593: 				$metaentry{':'.$unikey}=
                   11594: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11595: 			    }
1.339     albertel 11596: 			}
                   11597: 		    }
                   11598: 		} else {
1.172     www      11599: #
                   11600: # This is not a package - some other kind of start tag
1.339     albertel 11601: #
                   11602: 		    my $entry=$token->[1];
1.1068    www      11603: 		    my $unikey='';
1.175     www      11604: 
1.339     albertel 11605: 		    if ($entry eq 'import') {
1.175     www      11606: #
                   11607: # Importing a library here
1.339     albertel 11608: #
1.1067    www      11609:                         my $location=$parser->get_text('/import');
                   11610:                         my $dir=$filename;
                   11611:                         $dir=~s|[^/]*$||;
                   11612:                         $location=&filelocation($dir,$location);
1.1069    www      11613:                        
1.1068    www      11614:                         my $importmode=$token->[2]->{'importmode'};
                   11615:                         if ($importmode eq 'problem') {
1.1069    www      11616: # Import as problem/response
1.1068    www      11617:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11618:                         } elsif ($importmode eq 'part') {
                   11619: # Import as part(s)
1.1069    www      11620:                            $importedparts=1;
                   11621: # We need to get the original file and the imported file to get the part order correct
                   11622: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   11623: # Load and inspect original file
1.1070    www      11624:                            if ($#origfileimportpartids<0) {
                   11625:                               undef(%importedpartids);
                   11626:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11627:                               my $origfile=&getfile($origfilelocation);
                   11628:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11629:                            }
                   11630: 
1.1069    www      11631: # Load and inspect imported file
                   11632:                            my $impfile=&getfile($location);
                   11633:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11634:                            if ($#impfilepartids>=0) {
                   11635: # This problem had parts
1.1070    www      11636:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      11637:                            } else {
                   11638: # Importing by turning a single problem into a problem part
                   11639: # It gets the import-tags ID as part-ID
                   11640:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      11641:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      11642:                            }
1.1068    www      11643:                         } else {
                   11644: # Normal import
                   11645:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11646:                            if (defined($token->[2]->{'id'})) {
                   11647:                               $unikey.='_'.$token->[2]->{'id'};
                   11648:                            }
1.1067    www      11649:                         }
                   11650: 
1.339     albertel 11651: 			if ($depthcount<20) {
1.736     albertel 11652: 			    my $metadata = 
                   11653: 				&metadata($uri,'keys', $location,$unikey,
                   11654: 					  $depthcount+1);
                   11655: 			    foreach my $meta (split(',',$metadata)) {
                   11656: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   11657: 				$metathesekeys{$meta}=1;
1.339     albertel 11658: 			    }
1.1068    www      11659: 			
                   11660:                         }
1.1067    www      11661: 		    } else {
                   11662: #
                   11663: # Not importing, some other kind of non-package, non-library start tag
                   11664: # 
                   11665:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11666:                         if (defined($token->[2]->{'id'})) {
                   11667:                             $unikey.='_'.$token->[2]->{'id'};
                   11668:                         }
1.339     albertel 11669: 			if (defined($token->[2]->{'name'})) { 
                   11670: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   11671: 			}
                   11672: 			$metathesekeys{$unikey}=1;
1.736     albertel 11673: 			foreach my $param (@{$token->[3]}) {
                   11674: 			    $metaentry{':'.$unikey.'.'.$param} =
                   11675: 				$token->[2]->{$param};
1.339     albertel 11676: 			}
                   11677: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 11678: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 11679: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   11680: 		 # only ws inside the tag, and not in default, so use default
                   11681: 		 # as value
1.599     albertel 11682: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 11683: 			} elsif ( $internaltext =~ /\S/ ) {
                   11684: 		  # something interesting inside the tag
                   11685: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 11686: 			} else {
1.908     albertel 11687: 		  # no interesting values, don't set a default
1.339     albertel 11688: 			}
1.172     www      11689: # end of not-a-package not-a-library import
1.339     albertel 11690: 		    }
1.172     www      11691: # end of not-a-package start tag
1.339     albertel 11692: 		}
1.172     www      11693: # the next is the end of "start tag"
1.339     albertel 11694: 	    }
                   11695: 	}
1.483     albertel 11696: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 11697: 	$extension = lc($extension);
                   11698: 	if ($extension eq 'htm') { $extension='html'; }
                   11699: 
1.737     albertel 11700: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 11701: 	    #no specific packages #how's our extension
                   11702: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 11703: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 11704: 					 \%metathesekeys);
                   11705: 	}
1.883     albertel 11706: 
                   11707: 	if (!exists($metaentry{':packages'})
                   11708: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 11709: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 11710: 		#no specific packages well let's get default then
                   11711: 		if ($key!~/^default&/) { next; }
1.488     albertel 11712: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 11713: 					     \%metathesekeys);
                   11714: 	    }
                   11715: 	}
1.338     www      11716: # are there custom rights to evaluate
1.599     albertel 11717: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 11718: 
1.338     www      11719:     #
                   11720:     # Importing a rights file here
1.339     albertel 11721:     #
                   11722: 	    unless ($depthcount) {
1.599     albertel 11723: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 11724: 		my $dir=$filename;
                   11725: 		$dir=~s|[^/]*$||;
                   11726: 		$location=&filelocation($dir,$location);
1.736     albertel 11727: 		my $rights_metadata =
                   11728: 		    &metadata($uri,'keys',$location,'_rights',
                   11729: 			      $depthcount+1);
                   11730: 		foreach my $rights (split(',',$rights_metadata)) {
                   11731: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   11732: 		    $metathesekeys{$rights}=1;
1.339     albertel 11733: 		}
                   11734: 	    }
                   11735: 	}
1.737     albertel 11736: 	# uniqifiy package listing
                   11737: 	my %seen;
                   11738: 	my @uniq_packages =
                   11739: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   11740: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   11741: 
1.1070    www      11742:         if ($importedparts) {
                   11743: # We had imported parts and need to rebuild partorder
                   11744:            $metaentry{':partorder'}='';
                   11745:            $metathesekeys{'partorder'}=1;
                   11746:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   11747:                if ($origfileimportpartids[$index] eq 'part') {
                   11748: # original part, part of the problem
                   11749:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   11750:                } else {
                   11751: # we have imported parts at this position
                   11752:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   11753:                }
                   11754:            }
                   11755:            $metaentry{':partorder'}=~s/^\,//;
                   11756:         }
                   11757: 
1.737     albertel 11758: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 11759: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  11760: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.924     albertel 11761: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      11762: # this is the end of "was not already recently cached
1.71      www      11763:     }
1.599     albertel 11764:     return $metaentry{':'.$what};
1.261     albertel 11765: }
                   11766: 
1.488     albertel 11767: sub metadata_create_package_def {
1.483     albertel 11768:     my ($uri,$key,$package,$metathesekeys)=@_;
                   11769:     my ($pack,$name,$subp)=split(/\&/,$key);
                   11770:     if ($subp eq 'default') { next; }
                   11771:     
1.599     albertel 11772:     if (defined($metaentry{':packages'})) {
                   11773: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 11774:     } else {
1.599     albertel 11775: 	$metaentry{':packages'}=$package;
1.483     albertel 11776:     }
                   11777:     my $value=$packagetab{$key};
                   11778:     my $unikey;
                   11779:     $unikey='parameter_0_'.$name;
1.599     albertel 11780:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 11781:     $$metathesekeys{$unikey}=1;
1.599     albertel 11782:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11783: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 11784:     }
1.599     albertel 11785:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   11786: 	$metaentry{':'.$unikey}=
                   11787: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 11788:     }
                   11789: }
                   11790: 
1.261     albertel 11791: sub metadata_generate_part0 {
                   11792:     my ($metadata,$metacache,$uri) = @_;
                   11793:     my %allnames;
1.737     albertel 11794:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 11795: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 11796: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   11797: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 11798: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 11799: 	    $allnames{$name}=$part;
                   11800: 	  }
                   11801: 	}
                   11802:     }
                   11803:     foreach my $name (keys(%allnames)) {
                   11804:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 11805:       my $key=":parameter_0_$name";
1.261     albertel 11806:       $$metacache{"$key.part"}='0';
                   11807:       $$metacache{"$key.name"}=$name;
1.428     albertel 11808:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 11809: 					   $allnames{$name}.'_'.$name.
                   11810: 					   '.type'};
1.428     albertel 11811:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 11812: 			     '.display'};
1.644     www      11813:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 11814:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 11815:       $$metacache{"$key.display"}=$olddis;
                   11816:     }
1.71      www      11817: }
                   11818: 
1.764     albertel 11819: # ------------------------------------------------------ Devalidate title cache
                   11820: 
                   11821: sub devalidate_title_cache {
                   11822:     my ($url)=@_;
                   11823:     if (!$env{'request.course.id'}) { return; }
                   11824:     my $symb=&symbread($url);
                   11825:     if (!$symb) { return; }
                   11826:     my $key=$env{'request.course.id'}."\0".$symb;
                   11827:     &devalidate_cache_new('title',$key);
                   11828: }
                   11829: 
1.1014    droeschl 11830: # ------------------------------------------------- Get the title of a course
                   11831: 
                   11832: sub current_course_title {
                   11833:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   11834: }
1.301     www      11835: # ------------------------------------------------- Get the title of a resource
                   11836: 
                   11837: sub gettitle {
                   11838:     my $urlsymb=shift;
                   11839:     my $symb=&symbread($urlsymb);
1.534     albertel 11840:     if ($symb) {
1.620     albertel 11841: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 11842: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 11843: 	if (defined($cached)) { 
                   11844: 	    return $result;
                   11845: 	}
1.534     albertel 11846: 	my ($map,$resid,$url)=&decode_symb($symb);
                   11847: 	my $title='';
1.907     albertel 11848: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   11849: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   11850: 	} else {
                   11851: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11852: 		    &GDBM_READER(),0640)) {
                   11853: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   11854: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   11855: 		untie(%bighash);
                   11856: 	    }
1.534     albertel 11857: 	}
                   11858: 	$title=~s/\&colon\;/\:/gs;
                   11859: 	if ($title) {
1.1159    www      11860: # Remember both $symb and $title for dynamic metadata
                   11861:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      11862:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      11863: # Cache this title and then return it
1.599     albertel 11864: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 11865: 	}
                   11866: 	$urlsymb=$url;
                   11867:     }
                   11868:     my $title=&metadata($urlsymb,'title');
                   11869:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   11870:     return $title;
1.301     www      11871: }
1.613     albertel 11872: 
1.614     albertel 11873: sub get_slot {
                   11874:     my ($which,$cnum,$cdom)=@_;
                   11875:     if (!$cnum || !$cdom) {
1.790     albertel 11876: 	(undef,my $courseid)=&whichuser();
1.620     albertel 11877: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   11878: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 11879:     }
1.703     albertel 11880:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   11881:     my %slotinfo;
                   11882:     if (exists($remembered{$key})) {
                   11883: 	$slotinfo{$which} = $remembered{$key};
                   11884:     } else {
                   11885: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   11886: 	&Apache::lonhomework::showhash(%slotinfo);
                   11887: 	my ($tmp)=keys(%slotinfo);
                   11888: 	if ($tmp=~/^error:/) { return (); }
                   11889: 	$remembered{$key} = $slotinfo{$which};
                   11890:     }
1.616     albertel 11891:     if (ref($slotinfo{$which}) eq 'HASH') {
                   11892: 	return %{$slotinfo{$which}};
                   11893:     }
                   11894:     return $slotinfo{$which};
1.614     albertel 11895: }
1.1150    raeburn  11896: 
                   11897: sub get_reservable_slots {
                   11898:     my ($cnum,$cdom,$uname,$udom) = @_;
                   11899:     my $now = time;
                   11900:     my $reservable_info;
                   11901:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   11902:     if (exists($remembered{$key})) {
                   11903:         $reservable_info = $remembered{$key};
                   11904:     } else {
                   11905:         my %resv;
                   11906:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   11907:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   11908:         $reservable_info = \%resv;
                   11909:         $remembered{$key} = $reservable_info;
                   11910:     }
                   11911:     return $reservable_info;
                   11912: }
                   11913: 
                   11914: sub get_course_slots {
                   11915:     my ($cnum,$cdom) = @_;
                   11916:     my $hashid=$cnum.':'.$cdom;
                   11917:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   11918:     if (defined($cached)) {
                   11919:         if (ref($result) eq 'HASH') {
                   11920:             return %{$result};
                   11921:         }
                   11922:     } else {
                   11923:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   11924:         my ($tmp) = keys(%slots);
                   11925:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  11926:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  11927:             return %slots;
                   11928:         }
                   11929:     }
                   11930:     return;
                   11931: }
                   11932: 
                   11933: sub devalidate_slots_cache {
                   11934:     my ($cnum,$cdom)=@_;
                   11935:     my $hashid=$cnum.':'.$cdom;
                   11936:     &devalidate_cache_new('allslots',$hashid);
                   11937: }
                   11938: 
1.1181    raeburn  11939: sub get_coursechange {
                   11940:     my ($cdom,$cnum) = @_;
                   11941:     if ($cdom eq '' || $cnum eq '') {
                   11942:         return unless ($env{'request.course.id'});
                   11943:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   11944:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   11945:     }
                   11946:     my $hashid=$cdom.'_'.$cnum;
                   11947:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   11948:     if ((defined($cached)) && ($change ne '')) {
                   11949:         return $change;
                   11950:     } else {
                   11951:         my %crshash;
                   11952:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   11953:         if ($crshash{'internal.contentchange'} eq '') {
                   11954:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   11955:             if ($change eq '') {
                   11956:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   11957:                 $change = $crshash{'internal.created'};
                   11958:             }
                   11959:         } else {
                   11960:             $change = $crshash{'internal.contentchange'};
                   11961:         }
                   11962:         my $cachetime = 600;
                   11963:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   11964:     }
                   11965:     return $change;
                   11966: }
                   11967: 
                   11968: sub devalidate_coursechange_cache {
                   11969:     my ($cnum,$cdom)=@_;
                   11970:     my $hashid=$cnum.':'.$cdom;
                   11971:     &devalidate_cache_new('crschange',$hashid);
                   11972: }
                   11973: 
1.31      www      11974: # ------------------------------------------------- Update symbolic store links
                   11975: 
                   11976: sub symblist {
                   11977:     my ($mapname,%newhash)=@_;
1.438     www      11978:     $mapname=&deversion(&declutter($mapname));
1.31      www      11979:     my %hash;
1.620     albertel 11980:     if (($env{'request.course.fn'}) && (%newhash)) {
                   11981:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 11982:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  11983: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 11984: 		next if ($url eq 'last_known'
                   11985: 			 && $env{'form.no_update_last_known'});
                   11986: 		$hash{declutter($url)}=&encode_symb($mapname,
                   11987: 						    $newhash{$url}->[1],
                   11988: 						    $newhash{$url}->[0]);
1.191     harris41 11989:             }
1.31      www      11990:             if (untie(%hash)) {
                   11991: 		return 'ok';
                   11992:             }
                   11993:         }
                   11994:     }
                   11995:     return 'error';
1.212     www      11996: }
                   11997: 
                   11998: # --------------------------------------------------------------- Verify a symb
                   11999: 
                   12000: sub symbverify {
1.1190    raeburn  12001:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12002:     my $thisfn=$thisurl;
1.439     www      12003:     $thisfn=&declutter($thisfn);
1.215     www      12004: # direct jump to resource in page or to a sequence - will construct own symbs
                   12005:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12006: # check URL part
1.409     www      12007:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12008: 
1.431     www      12009:     unless ($url eq $thisfn) { return 0; }
1.213     www      12010: 
1.216     www      12011:     $symb=&symbclean($symb);
1.510     www      12012:     $thisurl=&deversion($thisurl);
1.439     www      12013:     $thisfn=&deversion($thisfn);
1.213     www      12014: 
                   12015:     my %bighash;
                   12016:     my $okay=0;
1.431     www      12017: 
1.620     albertel 12018:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12019:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12020:         my $noclutter;
1.1032    raeburn  12021:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12022:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12023:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12024:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12025:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12026:                 $noclutter = 1;
                   12027:             }
                   12028:         }
                   12029:         my $ids;
                   12030:         if ($noclutter) {
                   12031:             $ids=$bighash{'ids_'.$thisurl};
                   12032:         } else {
                   12033:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12034:         }
1.1102    raeburn  12035:         unless ($ids) {
                   12036:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12037:             $ids=$bighash{$idkey};
1.216     www      12038:         }
                   12039:         if ($ids) {
                   12040: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12041:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12042:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12043:             }
1.800     albertel 12044: 	    foreach my $id (split(/\,/,$ids)) {
                   12045: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12046:                if (
                   12047:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12048:    eq $symb) {
                   12049:                    if (ref($encstate)) {
                   12050:                        $$encstate = $bighash{'encrypted_'.$id};
                   12051:                    }
1.620     albertel 12052: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12053: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12054:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12055: 		       $okay=1;
1.1202    raeburn  12056:                        last;
1.582     albertel 12057: 		   }
                   12058: 	       }
1.216     www      12059: 	   }
                   12060:         }
1.213     www      12061: 	untie(%bighash);
                   12062:     }
                   12063:     return $okay;
1.31      www      12064: }
                   12065: 
1.210     www      12066: # --------------------------------------------------------------- Clean-up symb
                   12067: 
                   12068: sub symbclean {
                   12069:     my $symb=shift;
1.568     albertel 12070:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12071: # remove version from map
                   12072:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12073: 
1.210     www      12074: # remove version from URL
                   12075:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12076: 
1.507     www      12077: # remove wrapper
                   12078: 
1.510     www      12079:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12080:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12081:     return $symb;
1.409     www      12082: }
                   12083: 
                   12084: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12085: 
                   12086: sub encode_symb {
                   12087:     my ($map,$resid,$url)=@_;
                   12088:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12089: }
1.409     www      12090: 
                   12091: sub decode_symb {
1.568     albertel 12092:     my $symb=shift;
                   12093:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12094:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12095:     return (&fixversion($map),$resid,&fixversion($url));
                   12096: }
                   12097: 
                   12098: sub fixversion {
                   12099:     my $fn=shift;
1.609     banghart 12100:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12101:     my %bighash;
                   12102:     my $uri=&clutter($fn);
1.620     albertel 12103:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12104: # is this cached?
1.599     albertel 12105:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12106:     if (defined($cached)) { return $result; }
                   12107: # unfortunately not cached, or expired
1.620     albertel 12108:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12109: 	    &GDBM_READER(),0640)) {
                   12110:  	if ($bighash{'version_'.$uri}) {
                   12111:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12112:  	    unless (($version eq 'mostrecent') || 
                   12113: 		    ($version==&getversion($uri))) {
1.440     www      12114:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12115:  	    }
                   12116:  	}
                   12117:  	untie %bighash;
1.413     www      12118:     }
1.599     albertel 12119:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12120: }
                   12121: 
                   12122: sub deversion {
                   12123:     my $url=shift;
                   12124:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12125:     return $url;
1.210     www      12126: }
                   12127: 
1.31      www      12128: # ------------------------------------------------------ Return symb list entry
                   12129: 
                   12130: sub symbread {
1.1282    raeburn  12131:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12132:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12133:     if (defined($env{$cache_str})) {
                   12134:         if ($ignorecachednull) {
                   12135:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12136:         } else {
                   12137:             return $env{$cache_str};
                   12138:         }
                   12139:     }
1.242     www      12140: # no filename provided? try from environment
1.1265    raeburn  12141:     unless ($thisfn) {
1.620     albertel 12142:         if ($env{'request.symb'}) {
                   12143: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12144: 	}
1.620     albertel 12145: 	$thisfn=$env{'request.filename'};
1.44      www      12146:     }
1.569     albertel 12147:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12148: # is that filename actually a symb? Verify, clean, and return
                   12149:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12150: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12151: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12152: 	}
1.242     www      12153:     }
1.44      www      12154:     $thisfn=declutter($thisfn);
1.31      www      12155:     my %hash;
1.37      www      12156:     my %bighash;
                   12157:     my $syval='';
1.620     albertel 12158:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12159:         my $targetfn = $thisfn;
1.609     banghart 12160:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12161:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12162:         }
1.687     albertel 12163: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12164: 	    $targetfn=$1;
                   12165: 	}
1.620     albertel 12166:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12167:                       &GDBM_READER(),0640)) {
1.481     raeburn  12168: 	    $syval=$hash{$targetfn};
1.37      www      12169:             untie(%hash);
                   12170:         }
                   12171: # ---------------------------------------------------------- There was an entry
                   12172:         if ($syval) {
1.601     albertel 12173: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12174: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12175: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12176: 		    #return $env{$cache_str}='';
1.601     albertel 12177: 		#}    
                   12178: 		#$syval.=$1;
                   12179: 	    #}
1.37      www      12180:         } else {
                   12181: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12182:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12183:                             &GDBM_READER(),0640)) {
1.37      www      12184: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12185:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12186:               unless ($ids) { 
                   12187:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12188:               }
                   12189:               unless ($ids) {
                   12190: # alias?
                   12191: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12192:               }
1.37      www      12193:               if ($ids) {
                   12194: # ------------------------------------------------------------------- Has ID(s)
                   12195:                  my @possibilities=split(/\,/,$ids);
1.39      www      12196:                  if ($#possibilities==0) {
                   12197: # ----------------------------------------------- There is only one possibility
1.37      www      12198: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12199: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12200: 						    $resid,$thisfn);
1.1282    raeburn  12201:                      if (ref($possibles) eq 'HASH') {
                   12202:                          $possibles->{$syval} = 1;    
                   12203:                      }
                   12204:                      if ($checkforblock) {
                   12205:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12206:                          if (@blockers) {
                   12207:                              $syval = '';
                   12208:                              return;
                   12209:                          }
                   12210:                      }
                   12211:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12212: # ------------------------------------------ There is more than one possibility
                   12213:                      my $realpossible=0;
1.800     albertel 12214:                      foreach my $id (@possibilities) {
                   12215: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12216:                          my $canaccess;
                   12217:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12218:                              $canaccess = 1;
                   12219:                          } else { 
                   12220:                              $canaccess = &allowed('bre',$file);
                   12221:                          }
                   12222:                          if ($canaccess) {
                   12223:          		     my ($mapid,$resid)=split(/\./,$id);
                   12224:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12225:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12226: 						             $resid,$thisfn);
                   12227:                                  if (ref($possibles) eq 'HASH') {
                   12228:                                      $possibles->{$syval} = 1;
                   12229:                                  }
                   12230:                                  if ($checkforblock) {
                   12231:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12232:                                      unless (@blockers > 0) {
                   12233:                                          $syval = $poss_syval;
                   12234:                                          $realpossible++;
                   12235:                                      }
                   12236:                                  } else {
                   12237:                                      $syval = $poss_syval;
                   12238:                                      $realpossible++;
                   12239:                                  }
                   12240:                              }
1.39      www      12241: 			 }
1.191     harris41 12242:                      }
1.39      www      12243: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12244:                  } else {
                   12245:                      $syval='';
1.37      www      12246:                  }
                   12247: 	      }
1.1282    raeburn  12248:               untie(%bighash);
1.481     raeburn  12249:            }
1.31      www      12250:         }
1.62      www      12251:         if ($syval) {
1.620     albertel 12252: 	    return $env{$cache_str}=$syval;
1.62      www      12253:         }
1.31      www      12254:     }
1.949     raeburn  12255:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12256:     return $env{$cache_str}='';
1.31      www      12257: }
                   12258: 
                   12259: # ---------------------------------------------------------- Return random seed
                   12260: 
1.32      www      12261: sub numval {
                   12262:     my $txt=shift;
                   12263:     $txt=~tr/A-J/0-9/;
                   12264:     $txt=~tr/a-j/0-9/;
                   12265:     $txt=~tr/K-T/0-9/;
                   12266:     $txt=~tr/k-t/0-9/;
                   12267:     $txt=~tr/U-Z/0-5/;
                   12268:     $txt=~tr/u-z/0-5/;
                   12269:     $txt=~s/\D//g;
1.564     albertel 12270:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12271:     return int($txt);
1.368     albertel 12272: }
                   12273: 
1.484     albertel 12274: sub numval2 {
                   12275:     my $txt=shift;
                   12276:     $txt=~tr/A-J/0-9/;
                   12277:     $txt=~tr/a-j/0-9/;
                   12278:     $txt=~tr/K-T/0-9/;
                   12279:     $txt=~tr/k-t/0-9/;
                   12280:     $txt=~tr/U-Z/0-5/;
                   12281:     $txt=~tr/u-z/0-5/;
                   12282:     $txt=~s/\D//g;
                   12283:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12284:     my $total;
                   12285:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12286:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12287:     return int($total);
                   12288: }
                   12289: 
1.575     albertel 12290: sub numval3 {
                   12291:     use integer;
                   12292:     my $txt=shift;
                   12293:     $txt=~tr/A-J/0-9/;
                   12294:     $txt=~tr/a-j/0-9/;
                   12295:     $txt=~tr/K-T/0-9/;
                   12296:     $txt=~tr/k-t/0-9/;
                   12297:     $txt=~tr/U-Z/0-5/;
                   12298:     $txt=~tr/u-z/0-5/;
                   12299:     $txt=~s/\D//g;
                   12300:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12301:     my $total;
                   12302:     foreach my $val (@txts) { $total+=$val; }
                   12303:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12304:     return $total;
                   12305: }
                   12306: 
1.675     albertel 12307: sub digest {
                   12308:     my ($data)=@_;
                   12309:     my $digest=&Digest::MD5::md5($data);
                   12310:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12311:     my ($e,$f);
                   12312:     {
                   12313:         use integer;
                   12314:         $e=($a+$b);
                   12315:         $f=($c+$d);
                   12316:         if ($_64bit) {
                   12317:             $e=(($e<<32)>>32);
                   12318:             $f=(($f<<32)>>32);
                   12319:         }
                   12320:     }
                   12321:     if (wantarray) {
                   12322: 	return ($e,$f);
                   12323:     } else {
                   12324: 	my $g;
                   12325: 	{
                   12326: 	    use integer;
                   12327: 	    $g=($e+$f);
                   12328: 	    if ($_64bit) {
                   12329: 		$g=(($g<<32)>>32);
                   12330: 	    }
                   12331: 	}
                   12332: 	return $g;
                   12333:     }
                   12334: }
                   12335: 
1.368     albertel 12336: sub latest_rnd_algorithm_id {
1.675     albertel 12337:     return '64bit5';
1.366     albertel 12338: }
1.32      www      12339: 
1.503     albertel 12340: sub get_rand_alg {
                   12341:     my ($courseid)=@_;
1.790     albertel 12342:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12343:     if ($courseid) {
1.620     albertel 12344: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12345:     }
                   12346:     return &latest_rnd_algorithm_id();
                   12347: }
                   12348: 
1.562     albertel 12349: sub validCODE {
                   12350:     my ($CODE)=@_;
                   12351:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12352:     return 0;
                   12353: }
                   12354: 
1.491     albertel 12355: sub getCODE {
1.620     albertel 12356:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12357:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12358: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12359: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12360: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12361:     }
                   12362:     return undef;
                   12363: }
1.1133    foxr     12364: #
                   12365: #  Determines the random seed for a specific context:
                   12366: #
                   12367: # parameters:
                   12368: #   symb      - in course context the symb for the seed.
                   12369: #   course_id - The course id of the form domain_coursenum.
                   12370: #   domain    - Domain for the user.
                   12371: #   course    - Course for the user.
                   12372: #   cenv      - environment of the course.
                   12373: #
                   12374: # NOTE:
                   12375: #   All parameters are picked out of the environment if missing
                   12376: #   or not defined.
                   12377: #   If a symb cannot be determined the current time is used instead.
                   12378: #
                   12379: #  For a given well defined symb, courside, domain, username,
                   12380: #  and course environment, the seed is reproducible.
                   12381: #
1.31      www      12382: sub rndseed {
1.1133    foxr     12383:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12384:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12385:     if (!defined($symb)) {
1.366     albertel 12386: 	unless ($symb=$wsymb) { return time; }
                   12387:     }
1.1146    foxr     12388:     if (!defined $courseid) { 
                   12389: 	$courseid=$wcourseid; 
                   12390:     }
                   12391:     if (!defined $domain) { $domain=$wdomain; }
                   12392:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12393: 
                   12394:     my $which;
                   12395:     if (defined($cenv->{'rndseed'})) {
                   12396: 	$which = $cenv->{'rndseed'};
                   12397:     } else {
                   12398: 	$which =&get_rand_alg($courseid);
                   12399:     }
1.491     albertel 12400:     if (defined(&getCODE())) {
1.1133    foxr     12401: 
1.675     albertel 12402: 	if ($which eq '64bit5') {
                   12403: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12404: 	} elsif ($which eq '64bit4') {
1.575     albertel 12405: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12406: 	} else {
                   12407: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12408: 	}
1.675     albertel 12409:     } elsif ($which eq '64bit5') {
                   12410: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12411:     } elsif ($which eq '64bit4') {
                   12412: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12413:     } elsif ($which eq '64bit3') {
                   12414: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12415:     } elsif ($which eq '64bit2') {
                   12416: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12417:     } elsif ($which eq '64bit') {
                   12418: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12419:     }
                   12420:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12421: }
                   12422: 
                   12423: sub rndseed_32bit {
                   12424:     my ($symb,$courseid,$domain,$username)=@_;
                   12425:     {
                   12426: 	use integer;
                   12427: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12428: 	my $symbseed=numval($symb) << 22;
                   12429: 	my $namechck=unpack("%32C*",$username) << 17;
                   12430: 	my $nameseed=numval($username) << 12;
                   12431: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12432: 	my $courseseed=unpack("%32C*",$courseid);
                   12433: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12434: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12435: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12436: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12437: 	return $num;
                   12438:     }
                   12439: }
                   12440: 
                   12441: sub rndseed_64bit {
                   12442:     my ($symb,$courseid,$domain,$username)=@_;
                   12443:     {
                   12444: 	use integer;
                   12445: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12446: 	my $symbseed=numval($symb) << 10;
                   12447: 	my $namechck=unpack("%32S*",$username);
                   12448: 	
                   12449: 	my $nameseed=numval($username) << 21;
                   12450: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12451: 	my $courseseed=unpack("%32S*",$courseid);
                   12452: 	
                   12453: 	my $num1=$symbchck+$symbseed+$namechck;
                   12454: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12455: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12456: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12457: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12458: 	return "$num1,$num2";
1.155     albertel 12459:     }
1.366     albertel 12460: }
                   12461: 
1.443     albertel 12462: sub rndseed_64bit2 {
                   12463:     my ($symb,$courseid,$domain,$username)=@_;
                   12464:     {
                   12465: 	use integer;
                   12466: 	# strings need to be an even # of cahracters long, it it is odd the
                   12467:         # last characters gets thrown away
                   12468: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12469: 	my $symbseed=numval($symb) << 10;
                   12470: 	my $namechck=unpack("%32S*",$username.' ');
                   12471: 	
                   12472: 	my $nameseed=numval($username) << 21;
1.501     albertel 12473: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12474: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12475: 	
                   12476: 	my $num1=$symbchck+$symbseed+$namechck;
                   12477: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12478: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12479: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12480: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12481: 	return "$num1,$num2";
                   12482:     }
                   12483: }
                   12484: 
                   12485: sub rndseed_64bit3 {
                   12486:     my ($symb,$courseid,$domain,$username)=@_;
                   12487:     {
                   12488: 	use integer;
                   12489: 	# strings need to be an even # of cahracters long, it it is odd the
                   12490:         # last characters gets thrown away
                   12491: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12492: 	my $symbseed=numval2($symb) << 10;
                   12493: 	my $namechck=unpack("%32S*",$username.' ');
                   12494: 	
                   12495: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12496: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12497: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12498: 	
                   12499: 	my $num1=$symbchck+$symbseed+$namechck;
                   12500: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12501: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12502: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12503: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12504: 	
1.503     albertel 12505: 	return "$num1:$num2";
1.443     albertel 12506:     }
                   12507: }
                   12508: 
1.575     albertel 12509: sub rndseed_64bit4 {
                   12510:     my ($symb,$courseid,$domain,$username)=@_;
                   12511:     {
                   12512: 	use integer;
                   12513: 	# strings need to be an even # of cahracters long, it it is odd the
                   12514:         # last characters gets thrown away
                   12515: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12516: 	my $symbseed=numval3($symb) << 10;
                   12517: 	my $namechck=unpack("%32S*",$username.' ');
                   12518: 	
                   12519: 	my $nameseed=numval3($username) << 21;
                   12520: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12521: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12522: 	
                   12523: 	my $num1=$symbchck+$symbseed+$namechck;
                   12524: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12525: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12526: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12527: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12528: 	
1.575     albertel 12529: 	return "$num1:$num2";
                   12530:     }
                   12531: }
                   12532: 
1.675     albertel 12533: sub rndseed_64bit5 {
                   12534:     my ($symb,$courseid,$domain,$username)=@_;
                   12535:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12536:     return "$num1:$num2";
                   12537: }
                   12538: 
1.366     albertel 12539: sub rndseed_CODE_64bit {
                   12540:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12541:     {
1.366     albertel 12542: 	use integer;
1.443     albertel 12543: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12544: 	my $symbseed=numval2($symb);
1.491     albertel 12545: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12546: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12547: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12548: 	my $num1=$symbseed+$CODEchck;
                   12549: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12550: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12551: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12552: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12553: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12554: 	return "$num1:$num2";
1.366     albertel 12555:     }
                   12556: }
                   12557: 
1.575     albertel 12558: sub rndseed_CODE_64bit4 {
                   12559:     my ($symb,$courseid,$domain,$username)=@_;
                   12560:     {
                   12561: 	use integer;
                   12562: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12563: 	my $symbseed=numval3($symb);
                   12564: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12565: 	my $CODEseed=numval3(&getCODE());
                   12566: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12567: 	my $num1=$symbseed+$CODEchck;
                   12568: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12569: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12570: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12571: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12572: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12573: 	return "$num1:$num2";
                   12574:     }
                   12575: }
                   12576: 
1.675     albertel 12577: sub rndseed_CODE_64bit5 {
                   12578:     my ($symb,$courseid,$domain,$username)=@_;
                   12579:     my $code = &getCODE();
                   12580:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12581:     return "$num1:$num2";
                   12582: }
                   12583: 
1.366     albertel 12584: sub setup_random_from_rndseed {
                   12585:     my ($rndseed)=@_;
1.503     albertel 12586:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12587:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12588:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12589:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   12590:         } else {
                   12591:             &Math::Random::random_set_seed($num1,$num2);
                   12592:         }
1.366     albertel 12593:     } else {
                   12594: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 12595:     }
1.36      albertel 12596: }
                   12597: 
1.474     albertel 12598: sub latest_receipt_algorithm_id {
1.835     albertel 12599:     return 'receipt3';
1.474     albertel 12600: }
                   12601: 
1.480     www      12602: sub recunique {
                   12603:     my $fucourseid=shift;
                   12604:     my $unique;
1.835     albertel 12605:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   12606: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12607: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      12608:     } else {
                   12609: 	$unique=$perlvar{'lonReceipt'};
                   12610:     }
                   12611:     return unpack("%32C*",$unique);
                   12612: }
                   12613: 
                   12614: sub recprefix {
                   12615:     my $fucourseid=shift;
                   12616:     my $prefix;
1.835     albertel 12617:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   12618: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 12619: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      12620:     } else {
                   12621: 	$prefix=$perlvar{'lonHostID'};
                   12622:     }
                   12623:     return unpack("%32C*",$prefix);
                   12624: }
                   12625: 
1.76      www      12626: sub ireceipt {
1.474     albertel 12627:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 12628: 
                   12629:     my $return =&recprefix($fucourseid).'-';
                   12630: 
                   12631:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   12632: 	$env{'request.state'} eq 'construct') {
                   12633: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   12634: 	return $return;
                   12635:     }
                   12636: 
1.76      www      12637:     my $cuname=unpack("%32C*",$funame);
                   12638:     my $cudom=unpack("%32C*",$fudom);
                   12639:     my $cucourseid=unpack("%32C*",$fucourseid);
                   12640:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      12641:     my $cunique=&recunique($fucourseid);
1.474     albertel 12642:     my $cpart=unpack("%32S*",$part);
1.835     albertel 12643:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   12644: 
1.790     albertel 12645: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 12646: 			       
                   12647: 	$return.= ($cunique%$cuname+
                   12648: 		   $cunique%$cudom+
                   12649: 		   $cusymb%$cuname+
                   12650: 		   $cusymb%$cudom+
                   12651: 		   $cucourseid%$cuname+
                   12652: 		   $cucourseid%$cudom+
                   12653: 		   $cpart%$cuname+
                   12654: 		   $cpart%$cudom);
                   12655:     } else {
                   12656: 	$return.= ($cunique%$cuname+
                   12657: 		   $cunique%$cudom+
                   12658: 		   $cusymb%$cuname+
                   12659: 		   $cusymb%$cudom+
                   12660: 		   $cucourseid%$cuname+
                   12661: 		   $cucourseid%$cudom);
                   12662:     }
                   12663:     return $return;
1.76      www      12664: }
                   12665: 
                   12666: sub receipt {
1.474     albertel 12667:     my ($part)=@_;
1.790     albertel 12668:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 12669:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      12670: }
1.260     ng       12671: 
1.790     albertel 12672: sub whichuser {
                   12673:     my ($passedsymb)=@_;
                   12674:     my ($symb,$courseid,$domain,$name,$publicuser);
                   12675:     if (defined($env{'form.grade_symb'})) {
                   12676: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   12677: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   12678: 	if (!$allowed &&
                   12679: 	    exists($env{'request.course.sec'}) &&
                   12680: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   12681: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   12682: 			      '/'.$env{'request.course.sec'});
                   12683: 	}
                   12684: 	if ($allowed) {
                   12685: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   12686: 	    $courseid=$tmp_courseid;
                   12687: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   12688: 	    ($name)=&get_env_multiple('form.grade_username');
                   12689: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   12690: 	}
                   12691:     }
                   12692:     if (!$passedsymb) {
                   12693: 	$symb=&symbread();
                   12694:     } else {
                   12695: 	$symb=$passedsymb;
                   12696:     }
                   12697:     $courseid=$env{'request.course.id'};
                   12698:     $domain=$env{'user.domain'};
                   12699:     $name=$env{'user.name'};
                   12700:     if ($name eq 'public' && $domain eq 'public') {
                   12701: 	if (!defined($env{'form.username'})) {
                   12702: 	    $env{'form.username'}.=time.rand(10000000);
                   12703: 	}
                   12704: 	$name.=$env{'form.username'};
                   12705:     }
                   12706:     return ($symb,$courseid,$domain,$name,$publicuser);
                   12707: 
                   12708: }
                   12709: 
1.36      albertel 12710: # ------------------------------------------------------------ Serves up a file
1.472     albertel 12711: # returns either the contents of the file or 
                   12712: # -1 if the file doesn't exist
1.481     raeburn  12713: #
                   12714: # if the target is a file that was uploaded via DOCS, 
                   12715: # a check will be made to see if a current copy exists on the local server,
                   12716: # if it does this will be served, otherwise a copy will be retrieved from
                   12717: # the home server for the course and stored in /home/httpd/html/userfiles on
                   12718: # the local server.   
1.472     albertel 12719: 
1.36      albertel 12720: sub getfile {
1.538     albertel 12721:     my ($file) = @_;
1.609     banghart 12722:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 12723:     &repcopy($file);
                   12724:     return &readfile($file);
                   12725: }
                   12726: 
                   12727: sub repcopy_userfile {
                   12728:     my ($file)=@_;
1.1142    raeburn  12729:     my $londocroot = $perlvar{'lonDocRoot'};
                   12730:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  12731:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 12732:     my ($cdom,$cnum,$filename) = 
1.811     albertel 12733: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 12734:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   12735:     if (-e "$file") {
1.828     www      12736: # we already have a local copy, check it out
1.538     albertel 12737: 	my @fileinfo = stat($file);
1.828     www      12738: 	my $rtncode;
                   12739: 	my $info;
1.538     albertel 12740: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 12741: 	if ($lwpresp ne 'ok') {
1.828     www      12742: # there is no such file anymore, even though we had a local copy
1.482     albertel 12743: 	    if ($rtncode eq '404') {
1.538     albertel 12744: 		unlink($file);
1.482     albertel 12745: 	    }
                   12746: 	    return -1;
                   12747: 	}
                   12748: 	if ($info < $fileinfo[9]) {
1.828     www      12749: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  12750: 	    return 'ok';
1.828     www      12751: 	} else {
                   12752: # the file is outdated, get rid of it
                   12753: 	    unlink($file);
1.482     albertel 12754: 	}
1.828     www      12755:     }
                   12756: # one way or the other, at this point, we don't have the file
                   12757: # construct the correct path for the file
                   12758:     my @parts = ($cdom,$cnum); 
                   12759:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   12760: 	push @parts, split(/\//,$1);
                   12761:     }
                   12762:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   12763:     foreach my $part (@parts) {
                   12764: 	$path .= '/'.$part;
                   12765: 	if (!-e $path) {
                   12766: 	    mkdir($path,0770);
1.482     albertel 12767: 	}
                   12768:     }
1.828     www      12769: # now the path exists for sure
                   12770: # get a user agent
                   12771:     my $transferfile=$file.'.in.transfer';
                   12772: # FIXME: this should flock
                   12773:     if (-e $transferfile) { return 'ok'; }
                   12774:     my $request;
                   12775:     $uri=~s/^\///;
1.980     raeburn  12776:     my $homeserver = &homeserver($cnum,$cdom);
                   12777:     my $protocol = $protocol{$homeserver};
                   12778:     $protocol = 'http' if ($protocol ne 'https');
                   12779:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  12780:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      12781: # did it work?
                   12782:     if ($response->is_error()) {
                   12783: 	unlink($transferfile);
                   12784: 	&logthis("Userfile repcopy failed for $uri");
                   12785: 	return -1;
                   12786:     }
                   12787: # worked, rename the transfer file
                   12788:     rename($transferfile,$file);
1.607     raeburn  12789:     return 'ok';
1.481     raeburn  12790: }
                   12791: 
1.517     albertel 12792: sub tokenwrapper {
                   12793:     my $uri=shift;
1.980     raeburn  12794:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 12795:     $uri=~s|^/||;
1.620     albertel 12796:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 12797:     my $token=$1;
1.552     albertel 12798:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   12799:     if ($udom && $uname && $file) {
                   12800: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  12801:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  12802:         my $homeserver = &homeserver($uname,$udom);
                   12803:         my $protocol = $protocol{$homeserver};
                   12804:         $protocol = 'http' if ($protocol ne 'https');
                   12805:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 12806:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   12807:                                '&tokenissued='.$perlvar{'lonHostID'};
                   12808:     } else {
                   12809:         return '/adm/notfound.html';
                   12810:     }
                   12811: }
                   12812: 
1.828     www      12813: # call with reqtype HEAD: get last modification time
                   12814: # call with reqtype GET: get the file contents
                   12815: # Do not call this with reqtype GET for large files! It loads everything into memory
                   12816: #
1.481     raeburn  12817: sub getuploaded {
                   12818:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   12819:     $uri=~s/^\///;
1.980     raeburn  12820:     my $homeserver = &homeserver($cnum,$cdom);
                   12821:     my $protocol = $protocol{$homeserver};
                   12822:     $protocol = 'http' if ($protocol ne 'https');
                   12823:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  12824:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  12825:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  12826:     $$rtncode = $response->code;
1.482     albertel 12827:     if (! $response->is_success()) {
                   12828: 	return 'failed';
                   12829:     }      
                   12830:     if ($reqtype eq 'HEAD') {
1.486     www      12831: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 12832:     } elsif ($reqtype eq 'GET') {
                   12833: 	$$info = $response->content;
1.472     albertel 12834:     }
1.482     albertel 12835:     return 'ok';
1.36      albertel 12836: }
                   12837: 
1.481     raeburn  12838: sub readfile {
                   12839:     my $file = shift;
                   12840:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   12841:     my $fh;
                   12842:     open($fh,"<$file");
                   12843:     my $a='';
1.800     albertel 12844:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  12845:     return $a;
                   12846: }
                   12847: 
1.36      albertel 12848: sub filelocation {
1.590     banghart 12849:     my ($dir,$file) = @_;
                   12850:     my $location;
                   12851:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 12852: 
                   12853:     if ($file =~ m-^/adm/-) {
                   12854: 	$file=~s-^/adm/wrapper/-/-;
                   12855: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   12856:     }
1.882     albertel 12857: 
1.1139    www      12858:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  12859:         $location = $file;
1.609     banghart 12860:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 12861:         my ($udom,$uname,$filename)=
1.811     albertel 12862:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 12863:         my $home=&homeserver($uname,$udom);
                   12864:         my $is_me=0;
                   12865:         my @ids=&current_machine_ids();
                   12866:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   12867:         if ($is_me) {
1.1117    foxr     12868:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 12869:         } else {
                   12870:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   12871:   	      $udom.'/'.$uname.'/'.$filename;
                   12872:         }
1.882     albertel 12873:     } elsif ($file =~ m-^/adm/-) {
                   12874: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 12875:     } else {
                   12876:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      12877:         $file=~s:^/(res|priv)/:/:;
                   12878:         my $space=$1;
1.590     banghart 12879:         if ( !( $file =~ m:^/:) ) {
                   12880:             $location = $dir. '/'.$file;
                   12881:         } else {
1.1142    raeburn  12882:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 12883:         }
1.59      albertel 12884:     }
1.590     banghart 12885:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 12886:     while ($location=~m{/\.\./}) {
                   12887: 	if ($location =~ m{/[^/]+/\.\./}) {
                   12888: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   12889: 	} else {
                   12890: 	    $location=~ s{/\.\./}{/}g;
                   12891: 	}
                   12892:     } #remove dir/..
1.590     banghart 12893:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   12894:     return $location;
1.46      www      12895: }
1.36      albertel 12896: 
1.46      www      12897: sub hreflocation {
                   12898:     my ($dir,$file)=@_;
1.980     raeburn  12899:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 12900: 	$file=filelocation($dir,$file);
1.700     albertel 12901:     } elsif ($file=~m-^/adm/-) {
                   12902: 	$file=~s-^/adm/wrapper/-/-;
                   12903: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 12904:     }
                   12905:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   12906: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   12907:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  12908: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   12909: 	        {/uploaded/$1/$2/}x;
1.46      www      12910:     }
1.913     albertel 12911:     if ($file=~ m{^/userfiles/}) {
                   12912: 	$file =~ s{^/userfiles/}{/uploaded/};
                   12913:     }
1.462     albertel 12914:     return $file;
1.465     albertel 12915: }
                   12916: 
1.1139    www      12917: 
                   12918: 
                   12919: 
                   12920: 
1.465     albertel 12921: sub current_machine_domains {
1.853     albertel 12922:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   12923: }
                   12924: 
                   12925: sub machine_domains {
                   12926:     my ($hostname) = @_;
1.465     albertel 12927:     my @domains;
1.838     albertel 12928:     my %hostname = &all_hostnames();
1.465     albertel 12929:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  12930: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 12931: 	if ($hostname eq $name) {
1.844     albertel 12932: 	    push(@domains,&host_domain($id));
1.465     albertel 12933: 	}
                   12934:     }
                   12935:     return @domains;
                   12936: }
                   12937: 
                   12938: sub current_machine_ids {
1.853     albertel 12939:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   12940: }
                   12941: 
                   12942: sub machine_ids {
                   12943:     my ($hostname) = @_;
                   12944:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 12945:     my @ids;
1.888     albertel 12946:     my %name_to_host = &all_names();
1.889     albertel 12947:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   12948: 	return @{ $name_to_host{$hostname} };
                   12949:     }
                   12950:     return;
1.31      www      12951: }
                   12952: 
1.824     raeburn  12953: sub additional_machine_domains {
                   12954:     my @domains;
                   12955:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   12956:     while( my $line = <$fh>) {
                   12957:         $line =~ s/\s//g;
                   12958:         push(@domains,$line);
                   12959:     }
                   12960:     return @domains;
                   12961: }
                   12962: 
                   12963: sub default_login_domain {
                   12964:     my $domain = $perlvar{'lonDefDomain'};
                   12965:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   12966:     foreach my $posdom (&current_machine_domains(),
                   12967:                         &additional_machine_domains()) {
                   12968:         if (lc($posdom) eq lc($testdomain)) {
                   12969:             $domain=$posdom;
                   12970:             last;
                   12971:         }
                   12972:     }
                   12973:     return $domain;
                   12974: }
                   12975: 
1.31      www      12976: # ------------------------------------------------------------- Declutters URLs
                   12977: 
                   12978: sub declutter {
                   12979:     my $thisfn=shift;
1.569     albertel 12980:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  12981:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   12982:         $thisfn=~s{^/home/httpd/html}{};
                   12983:     }
1.31      www      12984:     $thisfn=~s/^\///;
1.697     albertel 12985:     $thisfn=~s|^adm/wrapper/||;
                   12986:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      12987:     $thisfn=~s/^res\///;
1.1172    bisitz   12988:     $thisfn=~s/^priv\///;
1.1032    raeburn  12989:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   12990:         $thisfn=~s/\?.+$//;
                   12991:     }
1.268     www      12992:     return $thisfn;
                   12993: }
                   12994: 
                   12995: # ------------------------------------------------------------- Clutter up URLs
                   12996: 
                   12997: sub clutter {
                   12998:     my $thisfn='/'.&declutter(shift);
1.887     albertel 12999:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13000: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13001:        $thisfn='/res'.$thisfn; 
                   13002:     }
1.1031    raeburn  13003:     if ($thisfn !~m|^/adm|) {
                   13004: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13005: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13006: 	} else {
                   13007: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13008: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13009: 	    if ($embstyle eq 'ssi'
                   13010: 		|| ($embstyle eq 'hdn')
                   13011: 		|| ($embstyle eq 'rat')
                   13012: 		|| ($embstyle eq 'prv')
                   13013: 		|| ($embstyle eq 'ign')) {
                   13014: 		#do nothing with these
                   13015: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13016: 		|| ($embstyle eq 'emb')
                   13017: 		|| ($embstyle eq 'wrp')) {
                   13018: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13019: 	    } elsif ($embstyle eq 'unk'
                   13020: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13021: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13022: 	    } else {
1.718     www      13023: #		&logthis("Got a blank emb style");
1.695     albertel 13024: 	    }
1.694     albertel 13025: 	}
1.1343    raeburn  13026:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13027:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13028:     }
1.31      www      13029:     return $thisfn;
1.12      www      13030: }
                   13031: 
1.787     albertel 13032: sub clutter_with_no_wrapper {
                   13033:     my $uri = &clutter(shift);
                   13034:     if ($uri =~ m-^/adm/-) {
                   13035: 	$uri =~ s-^/adm/wrapper/-/-;
                   13036: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13037:     }
                   13038:     return $uri;
                   13039: }
                   13040: 
1.557     albertel 13041: sub freeze_escape {
                   13042:     my ($value)=@_;
                   13043:     if (ref($value)) {
                   13044: 	$value=&nfreeze($value);
                   13045: 	return '__FROZEN__'.&escape($value);
                   13046:     }
                   13047:     return &escape($value);
                   13048: }
                   13049: 
1.11      www      13050: 
1.557     albertel 13051: sub thaw_unescape {
                   13052:     my ($value)=@_;
                   13053:     if ($value =~ /^__FROZEN__/) {
                   13054: 	substr($value,0,10,undef);
                   13055: 	$value=&unescape($value);
                   13056: 	return &thaw($value);
                   13057:     }
                   13058:     return &unescape($value);
                   13059: }
                   13060: 
1.436     albertel 13061: sub correct_line_ends {
                   13062:     my ($result)=@_;
                   13063:     $$result =~s/\r\n/\n/mg;
                   13064:     $$result =~s/\r/\n/mg;
1.415     albertel 13065: }
1.1       albertel 13066: # ================================================================ Main Program
                   13067: 
1.184     www      13068: sub goodbye {
1.204     albertel 13069:    &logthis("Starting Shut down");
1.443     albertel 13070: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13071:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13072: #converted
1.599     albertel 13073: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13074:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13075: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13076: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13077: #1.1 only
1.870     albertel 13078: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13079: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13080: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13081: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13082:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13083:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13084:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13085:    &flushcourselogs();
                   13086:    &logthis("Shutting down");
                   13087: }
                   13088: 
1.852     albertel 13089: sub get_dns {
1.1210    raeburn  13090:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13091:     if (!$ignore_cache) {
                   13092: 	my ($content,$cached)=
                   13093: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13094: 	if ($cached) {
1.1210    raeburn  13095: 	    &$func($content,$hashref);
1.869     albertel 13096: 	    return;
                   13097: 	}
                   13098:     }
                   13099: 
                   13100:     my %alldns;
1.852     albertel 13101:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13102:     foreach my $dns (<$config>) {
                   13103: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13104:         my $line = $1;
                   13105:         my ($host,$protocol) = split(/:/,$line);
                   13106:         if ($protocol ne 'https') {
                   13107:             $protocol = 'http';
                   13108:         }
                   13109: 	$alldns{$host} = $protocol;
1.869     albertel 13110:     }
                   13111:     while (%alldns) {
1.1263    raeburn  13112: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13113: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13114:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13115:         delete($alldns{$dns});
1.852     albertel 13116: 	next if ($response->is_error());
                   13117: 	my @content = split("\n",$response->content);
1.1210    raeburn  13118: 	unless ($nocache) {
1.1219    raeburn  13119: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13120: 	}
                   13121: 	&$func(\@content,$hashref);
1.869     albertel 13122: 	return;
1.852     albertel 13123:     }
                   13124:     close($config);
1.871     albertel 13125:     my $which = (split('/',$url))[3];
                   13126:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   13127:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13128:     my @content = <$config>;
1.1210    raeburn  13129:     &$func(\@content,$hashref);
                   13130:     return;
                   13131: }
                   13132: 
                   13133: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13134: sub parse_dns_checksums_tab {
1.1210    raeburn  13135:     my ($lines,$hashref) = @_;
1.1264    raeburn  13136:     my $lonhost = $perlvar{'lonHostID'};
                   13137:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13138:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13139:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13140:     my $webconfdir = '/etc/httpd/conf';
                   13141:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13142:         $webconfdir = '/etc/apache2';
                   13143:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13144:         if ($1 >= 10) {
                   13145:             $webconfdir = '/etc/apache2';
                   13146:         }
                   13147:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13148:         if ($1 >= 10.0) {
                   13149:             $webconfdir = '/etc/apache2';
                   13150:         }
                   13151:     }
1.1210    raeburn  13152:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13153:     my (%chksum,%revnum);
                   13154:     if (ref($lines) eq 'ARRAY') {
                   13155:         chomp(@{$lines});
1.1238    raeburn  13156:         my $version = shift(@{$lines});
                   13157:         if ($version eq $release) {  
1.1210    raeburn  13158:             foreach my $line (@{$lines}) {
1.1238    raeburn  13159:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13160:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13161:                     if ($webconfdir eq '/etc/apache2') {
                   13162:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13163:                     }
                   13164:                 }
1.1238    raeburn  13165:                 $chksum{$file} = $shasum;
                   13166:                 $revnum{$file} = $version;
1.1210    raeburn  13167:             }
                   13168:             if (ref($hashref) eq 'HASH') {
                   13169:                 %{$hashref} = (
                   13170:                                 sums     => \%chksum,
                   13171:                                 versions => \%revnum,
                   13172:                               );
                   13173:             }
                   13174:         }
                   13175:     }
1.869     albertel 13176:     return;
1.852     albertel 13177: }
1.1210    raeburn  13178: 
                   13179: sub fetch_dns_checksums {
1.1238    raeburn  13180:     my %checksums;
                   13181:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13182:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13183:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13184:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13185:              \%checksums);
1.1210    raeburn  13186:     return \%checksums;
                   13187: }
                   13188: 
1.327     albertel 13189: # ------------------------------------------------------------ Read domain file
                   13190: {
1.852     albertel 13191:     my $loaded;
1.846     albertel 13192:     my %domain;
                   13193: 
1.852     albertel 13194:     sub parse_domain_tab {
                   13195: 	my ($lines) = @_;
                   13196: 	foreach my $line (@$lines) {
                   13197: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13198: 
1.846     albertel 13199: 	    chomp($line);
1.852     albertel 13200: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13201: 	    my %this_domain;
                   13202: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13203: 			       'lang_def', 'city', 'longi', 'lati',
                   13204: 			       'primary') {
                   13205: 		$this_domain{$field} = shift(@elements);
                   13206: 	    }
                   13207: 	    $domain{$name} = \%this_domain;
1.852     albertel 13208: 	}
                   13209:     }
1.864     albertel 13210: 
                   13211:     sub reset_domain_info {
                   13212: 	undef($loaded);
                   13213: 	undef(%domain);
                   13214:     }
                   13215: 
1.852     albertel 13216:     sub load_domain_tab {
1.1293    raeburn  13217: 	my ($ignore_cache,$nocache) = @_;
                   13218: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13219: 	my $fh;
                   13220: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   13221: 	    my @lines = <$fh>;
                   13222: 	    &parse_domain_tab(\@lines);
1.448     albertel 13223: 	}
1.852     albertel 13224: 	close($fh);
                   13225: 	$loaded = 1;
1.327     albertel 13226:     }
1.846     albertel 13227: 
                   13228:     sub domain {
1.852     albertel 13229: 	&load_domain_tab() if (!$loaded);
                   13230: 
1.846     albertel 13231: 	my ($name,$what) = @_;
                   13232: 	return if ( !exists($domain{$name}) );
                   13233: 
                   13234: 	if (!$what) {
                   13235: 	    return $domain{$name}{'description'};
                   13236: 	}
                   13237: 	return $domain{$name}{$what};
                   13238:     }
1.974     raeburn  13239: 
                   13240:     sub domain_info {
                   13241:         &load_domain_tab() if (!$loaded);
                   13242:         return %domain;
                   13243:     }
                   13244: 
1.327     albertel 13245: }
                   13246: 
                   13247: 
1.1       albertel 13248: # ------------------------------------------------------------- Read hosts file
                   13249: {
1.838     albertel 13250:     my %hostname;
1.844     albertel 13251:     my %hostdom;
1.845     albertel 13252:     my %libserv;
1.852     albertel 13253:     my $loaded;
1.888     albertel 13254:     my %name_to_host;
1.1074    raeburn  13255:     my %internetdom;
1.1107    raeburn  13256:     my %LC_dns_serv;
1.852     albertel 13257: 
                   13258:     sub parse_hosts_tab {
                   13259: 	my ($file) = @_;
                   13260: 	foreach my $configline (@$file) {
                   13261: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13262:             chomp($configline);
                   13263: 	    if ($configline =~ /^\^/) {
                   13264:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13265:                     $LC_dns_serv{$1} = 1;
                   13266:                 }
                   13267:                 next;
                   13268:             }
1.1074    raeburn  13269: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13270: 	    $name=~s/\s//g;
                   13271: 	    if ($id && $domain && $role && $name) {
                   13272: 		$hostname{$id}=$name;
1.888     albertel 13273: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 13274: 		$hostdom{$id}=$domain;
                   13275: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13276:                 if (defined($protocol)) {
                   13277:                     if ($protocol eq 'https') {
                   13278:                         $protocol{$id} = $protocol;
                   13279:                     } else {
                   13280:                         $protocol{$id} = 'http'; 
                   13281:                     }
1.968     raeburn  13282:                 } else {
1.969     raeburn  13283:                     $protocol{$id} = 'http';
1.968     raeburn  13284:                 }
1.1074    raeburn  13285:                 if (defined($intdom)) {
                   13286:                     $internetdom{$id} = $intdom;
                   13287:                 }
1.852     albertel 13288: 	    }
                   13289: 	}
                   13290:     }
1.864     albertel 13291:     
                   13292:     sub reset_hosts_info {
1.897     albertel 13293: 	&purge_remembered();
1.864     albertel 13294: 	&reset_domain_info();
                   13295: 	&reset_hosts_ip_info();
1.1339    raeburn  13296:         undef(%internetdom);
1.892     albertel 13297: 	undef(%name_to_host);
1.864     albertel 13298: 	undef(%hostname);
                   13299: 	undef(%hostdom);
                   13300: 	undef(%libserv);
                   13301: 	undef($loaded);
                   13302:     }
1.1       albertel 13303: 
1.852     albertel 13304:     sub load_hosts_tab {
1.1293    raeburn  13305: 	my ($ignore_cache,$nocache) = @_;
                   13306: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.852     albertel 13307: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   13308: 	my @config = <$config>;
                   13309: 	&parse_hosts_tab(\@config);
                   13310: 	close($config);
                   13311: 	$loaded=1;
1.1       albertel 13312:     }
1.852     albertel 13313: 
1.838     albertel 13314:     sub hostname {
1.852     albertel 13315: 	&load_hosts_tab() if (!$loaded);
                   13316: 
1.838     albertel 13317: 	my ($lonid) = @_;
                   13318: 	return $hostname{$lonid};
                   13319:     }
1.845     albertel 13320: 
1.838     albertel 13321:     sub all_hostnames {
1.852     albertel 13322: 	&load_hosts_tab() if (!$loaded);
                   13323: 
1.838     albertel 13324: 	return %hostname;
                   13325:     }
1.845     albertel 13326: 
1.888     albertel 13327:     sub all_names {
1.1293    raeburn  13328:         my ($ignore_cache,$nocache) = @_;
                   13329: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13330: 
                   13331: 	return %name_to_host;
                   13332:     }
                   13333: 
1.974     raeburn  13334:     sub all_host_domain {
                   13335:         &load_hosts_tab() if (!$loaded);
                   13336:         return %hostdom;
                   13337:     }
                   13338: 
1.1339    raeburn  13339:     sub all_host_intdom {
                   13340:         &load_hosts_tab() if (!$loaded);
                   13341:         return %internetdom;
                   13342:     }
                   13343: 
1.845     albertel 13344:     sub is_library {
1.852     albertel 13345: 	&load_hosts_tab() if (!$loaded);
                   13346: 
1.845     albertel 13347: 	return exists($libserv{$_[0]});
                   13348:     }
                   13349: 
                   13350:     sub all_library {
1.852     albertel 13351: 	&load_hosts_tab() if (!$loaded);
                   13352: 
1.845     albertel 13353: 	return %libserv;
                   13354:     }
                   13355: 
1.1062    droeschl 13356:     sub unique_library {
                   13357: 	#2x reverse removes all hostnames that appear more than once
                   13358:         my %unique = reverse &all_library();
                   13359:         return reverse %unique;
                   13360:     }
                   13361: 
1.841     albertel 13362:     sub get_servers {
1.852     albertel 13363: 	&load_hosts_tab() if (!$loaded);
                   13364: 
1.841     albertel 13365: 	my ($domain,$type) = @_;
                   13366: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13367: 	                                          : %hostname;
                   13368: 	my %result;
1.842     albertel 13369: 	if (ref($domain) eq 'ARRAY') {
                   13370: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13371: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13372: 		    $result{$host} = $hostname;
                   13373: 		}
                   13374: 	    }
                   13375: 	} else {
                   13376: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13377: 		if ($hostdom{$host} eq $domain) {
                   13378: 		    $result{$host} = $hostname;
                   13379: 		}
1.841     albertel 13380: 	    }
                   13381: 	}
                   13382: 	return %result;
                   13383:     }
1.845     albertel 13384: 
1.1062    droeschl 13385:     sub get_unique_servers {
                   13386:         my %unique = reverse &get_servers(@_);
                   13387: 	return reverse %unique;
                   13388:     }
                   13389: 
1.844     albertel 13390:     sub host_domain {
1.852     albertel 13391: 	&load_hosts_tab() if (!$loaded);
                   13392: 
1.844     albertel 13393: 	my ($lonid) = @_;
                   13394: 	return $hostdom{$lonid};
                   13395:     }
                   13396: 
1.841     albertel 13397:     sub all_domains {
1.852     albertel 13398: 	&load_hosts_tab() if (!$loaded);
                   13399: 
1.841     albertel 13400: 	my %seen;
                   13401: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13402: 	return @uniq;
                   13403:     }
1.1074    raeburn  13404: 
                   13405:     sub internet_dom {
                   13406:         &load_hosts_tab() if (!$loaded);
                   13407: 
                   13408:         my ($lonid) = @_;
                   13409:         return $internetdom{$lonid};
                   13410:     }
1.1107    raeburn  13411: 
                   13412:     sub is_LC_dns {
                   13413:         &load_hosts_tab() if (!$loaded);
                   13414: 
                   13415:         my ($hostname) = @_;
                   13416:         return exists($LC_dns_serv{$hostname});
                   13417:     }
                   13418: 
1.1       albertel 13419: }
                   13420: 
1.847     albertel 13421: { 
                   13422:     my %iphost;
1.856     albertel 13423:     my %name_to_ip;
                   13424:     my %lonid_to_ip;
1.869     albertel 13425: 
1.847     albertel 13426:     sub get_hosts_from_ip {
                   13427: 	my ($ip) = @_;
                   13428: 	my %iphosts = &get_iphost();
                   13429: 	if (ref($iphosts{$ip})) {
                   13430: 	    return @{$iphosts{$ip}};
                   13431: 	}
                   13432: 	return;
1.839     albertel 13433:     }
1.864     albertel 13434:     
                   13435:     sub reset_hosts_ip_info {
                   13436: 	undef(%iphost);
                   13437: 	undef(%name_to_ip);
                   13438: 	undef(%lonid_to_ip);
                   13439:     }
1.856     albertel 13440: 
                   13441:     sub get_host_ip {
                   13442: 	my ($lonid) = @_;
                   13443: 	if (exists($lonid_to_ip{$lonid})) {
                   13444: 	    return $lonid_to_ip{$lonid};
                   13445: 	}
                   13446: 	my $name=&hostname($lonid);
                   13447:    	my $ip = gethostbyname($name);
                   13448: 	return if (!$ip || length($ip) ne 4);
                   13449: 	$ip=inet_ntoa($ip);
                   13450: 	$name_to_ip{$name}   = $ip;
                   13451: 	$lonid_to_ip{$lonid} = $ip;
                   13452: 	return $ip;
                   13453:     }
1.847     albertel 13454:     
                   13455:     sub get_iphost {
1.1293    raeburn  13456: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13457: 
1.869     albertel 13458: 	if (!$ignore_cache) {
                   13459: 	    if (%iphost) {
                   13460: 		return %iphost;
                   13461: 	    }
                   13462: 	    my ($ip_info,$cached)=
                   13463: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13464: 	    if ($cached) {
                   13465: 		%iphost      = %{$ip_info->[0]};
                   13466: 		%name_to_ip  = %{$ip_info->[1]};
                   13467: 		%lonid_to_ip = %{$ip_info->[2]};
                   13468: 		return %iphost;
                   13469: 	    }
                   13470: 	}
1.894     albertel 13471: 
                   13472: 	# get yesterday's info for fallback
                   13473: 	my %old_name_to_ip;
                   13474: 	my ($ip_info,$cached)=
                   13475: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13476: 	if ($cached) {
                   13477: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13478: 	}
                   13479: 
1.1293    raeburn  13480: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13481: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13482: 	    my $ip;
                   13483: 	    if (!exists($name_to_ip{$name})) {
                   13484: 		$ip = gethostbyname($name);
                   13485: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13486: 		    if (defined($old_name_to_ip{$name})) {
                   13487: 			$ip = $old_name_to_ip{$name};
                   13488: 			&logthis("Can't find $name defaulting to old $ip");
                   13489: 		    } else {
                   13490: 			&logthis("Name $name no IP found");
                   13491: 			next;
                   13492: 		    }
                   13493: 		} else {
                   13494: 		    $ip=inet_ntoa($ip);
1.847     albertel 13495: 		}
                   13496: 		$name_to_ip{$name} = $ip;
                   13497: 	    } else {
                   13498: 		$ip = $name_to_ip{$name};
1.653     albertel 13499: 	    }
1.888     albertel 13500: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13501: 		$lonid_to_ip{$id} = $ip;
                   13502: 	    }
                   13503: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13504: 	}
1.1293    raeburn  13505:         unless ($nocache) {
                   13506: 	    &do_cache_new('iphost','iphost',
                   13507: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13508: 		          48*60*60);
                   13509:         }
1.869     albertel 13510: 
1.847     albertel 13511: 	return %iphost;
1.598     albertel 13512:     }
                   13513: 
1.992     raeburn  13514:     #
                   13515:     #  Given a DNS returns the loncapa host name for that DNS 
                   13516:     # 
                   13517:     sub host_from_dns {
                   13518:         my ($dns) = @_;
                   13519:         my @hosts;
                   13520:         my $ip;
                   13521: 
1.993     raeburn  13522:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13523:             $ip = $name_to_ip{$dns};
                   13524:         }
                   13525:         if (!$ip) {
                   13526:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13527:             if (length($ip) == 4) { 
                   13528: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13529:             }
                   13530:         }
                   13531:         if ($ip) {
                   13532: 	    @hosts = get_hosts_from_ip($ip);
                   13533: 	    return $hosts[0];
                   13534:         }
                   13535:         return undef;
1.986     foxr     13536:     }
1.992     raeburn  13537: 
1.1074    raeburn  13538:     sub get_internet_names {
                   13539:         my ($lonid) = @_;
                   13540:         return if ($lonid eq '');
                   13541:         my ($idnref,$cached)=
                   13542:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13543:         if ($cached) {
                   13544:             return $idnref;
                   13545:         }
                   13546:         my $ip = &get_host_ip($lonid);
                   13547:         my @hosts = &get_hosts_from_ip($ip);
                   13548:         my %iphost = &get_iphost();
                   13549:         my (@idns,%seen);
                   13550:         foreach my $id (@hosts) {
                   13551:             my $dom = &host_domain($id);
                   13552:             my $prim_id = &domain($dom,'primary');
                   13553:             my $prim_ip = &get_host_ip($prim_id);
                   13554:             next if ($seen{$prim_ip});
                   13555:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13556:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13557:                     my $intdom = &internet_dom($id);
                   13558:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13559:                         push(@idns,$intdom);
                   13560:                     }
                   13561:                 }
                   13562:             }
                   13563:             $seen{$prim_ip} = 1;
                   13564:         }
1.1219    raeburn  13565:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13566:     }
                   13567: 
1.986     foxr     13568: }
                   13569: 
1.1079    raeburn  13570: sub all_loncaparevs {
1.1249    raeburn  13571:     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  13572: }
                   13573: 
1.1227    raeburn  13574: # ---------------------------------------------------------- Read loncaparev table
                   13575: {
                   13576:     sub load_loncaparevs { 
                   13577:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   13578:             if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   13579:                 while (my $configline=<$config>) {
                   13580:                     chomp($configline);
                   13581:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   13582:                     $loncaparevs{$hostid}=$loncaparev;
                   13583:                 }
                   13584:                 close($config);
                   13585:             }
                   13586:         }
                   13587:     }
                   13588: }
                   13589: 
                   13590: # ---------------------------------------------------------- Read serverhostID table
                   13591: {
                   13592:     sub load_serverhomeIDs {
                   13593:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   13594:             if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   13595:                 while (my $configline=<$config>) {
                   13596:                     chomp($configline);
                   13597:                     my ($name,$id)=split(/:/,$configline);
                   13598:                     $serverhomeIDs{$name}=$id;
                   13599:                 }
                   13600:                 close($config);
                   13601:             }
                   13602:         }
                   13603:     }
                   13604: }
                   13605: 
                   13606: 
1.862     albertel 13607: BEGIN {
                   13608: 
                   13609: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   13610:     unless ($readit) {
                   13611: {
                   13612:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   13613:     %perlvar = (%perlvar,%{$configvars});
                   13614: }
                   13615: 
                   13616: 
1.1       albertel 13617: # ------------------------------------------------------ Read spare server file
                   13618: {
1.448     albertel 13619:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 13620: 
                   13621:     while (my $configline=<$config>) {
                   13622:        chomp($configline);
1.284     matthew  13623:        if ($configline) {
1.784     albertel 13624: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 13625: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 13626: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 13627:        }
                   13628:     }
1.448     albertel 13629:     close($config);
1.1       albertel 13630: }
1.11      www      13631: # ------------------------------------------------------------ Read permissions
                   13632: {
1.448     albertel 13633:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      13634: 
                   13635:     while (my $configline=<$config>) {
1.448     albertel 13636: 	chomp($configline);
                   13637: 	if ($configline) {
                   13638: 	    my ($role,$perm)=split(/ /,$configline);
                   13639: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   13640: 	}
1.11      www      13641:     }
1.448     albertel 13642:     close($config);
1.11      www      13643: }
                   13644: 
                   13645: # -------------------------------------------- Read plain texts for permissions
                   13646: {
1.448     albertel 13647:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      13648: 
                   13649:     while (my $configline=<$config>) {
1.448     albertel 13650: 	chomp($configline);
                   13651: 	if ($configline) {
1.742     raeburn  13652: 	    my ($short,@plain)=split(/:/,$configline);
                   13653:             %{$prp{$short}} = ();
                   13654: 	    if (@plain > 0) {
                   13655:                 $prp{$short}{'std'} = $plain[0];
                   13656:                 for (my $i=1; $i<@plain; $i++) {
                   13657:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   13658:                 }
                   13659:             }
1.448     albertel 13660: 	}
1.135     www      13661:     }
1.448     albertel 13662:     close($config);
1.135     www      13663: }
                   13664: 
                   13665: # ---------------------------------------------------------- Read package table
                   13666: {
1.448     albertel 13667:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      13668: 
                   13669:     while (my $configline=<$config>) {
1.483     albertel 13670: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 13671: 	chomp($configline);
                   13672: 	my ($short,$plain)=split(/:/,$configline);
                   13673: 	my ($pack,$name)=split(/\&/,$short);
                   13674: 	if ($plain ne '') {
                   13675: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   13676: 	    $packagetab{$short}=$plain; 
                   13677: 	}
1.11      www      13678:     }
1.448     albertel 13679:     close($config);
1.329     matthew  13680: }
                   13681: 
1.1073    raeburn  13682: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  13683: 
                   13684: &load_loncaparevs();
1.1073    raeburn  13685: 
1.1074    raeburn  13686: # ---------------------------------------------------------- Read serverhostID table
                   13687: 
1.1227    raeburn  13688: &load_serverhomeIDs();
                   13689: 
                   13690: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  13691: {
                   13692:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   13693:     if (-e $file) {
                   13694:         my $parser = HTML::LCParser->new($file);
                   13695:         while (my $token = $parser->get_token()) {
                   13696:             if ($token->[0] eq 'S') {
                   13697:                 my $item = $token->[1];
                   13698:                 my $name = $token->[2]{'name'};
                   13699:                 my $value = $token->[2]{'value'};
1.1285    raeburn  13700:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  13701:                 my $namematch = $token->[2]{'namematch'};
                   13702:                 if ($item eq 'parameter') {
                   13703:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   13704:                         my $release = $parser->get_text();
                   13705:                         $release =~ s/(^\s*|\s*$ )//gx;
                   13706:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   13707:                     }
                   13708:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  13709:                     my $release = $parser->get_text();
                   13710:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  13711:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  13712:                 }
                   13713:             }
                   13714:         }
                   13715:     }
1.1073    raeburn  13716: }
                   13717: 
1.1138    raeburn  13718: # ---------------------------------------------------------- Read managers table
                   13719: {
                   13720:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   13721:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   13722:             while (my $configline=<$config>) {
                   13723:                 chomp($configline);
                   13724:                 next if ($configline =~ /^\#/);
                   13725:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   13726:                     $managerstab{$configline} = 1;
                   13727:                 }
                   13728:             }
                   13729:             close($config);
                   13730:         }
                   13731:     }
                   13732: }
                   13733: 
1.329     matthew  13734: # ------------- set up temporary directory
                   13735: {
1.1117    foxr     13736:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  13737: 
1.11      www      13738: }
                   13739: 
1.794     albertel 13740: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   13741: 				'compress_threshold'=> 20_000,
                   13742:  			        });
1.185     www      13743: 
1.281     www      13744: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      13745: $dumpcount=0;
1.958     www      13746: $locknum=0;
1.22      www      13747: 
1.163     harris41 13748: &logtouch();
1.672     albertel 13749: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      13750: $readit=1;
1.564     albertel 13751:     {
                   13752: 	use integer;
                   13753: 	my $test=(2**32)+1;
1.568     albertel 13754: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 13755: 	&logthis(" Detected 64bit platform ($_64bit)");
                   13756:     }
1.195     www      13757: }
1.1       albertel 13758: }
1.179     www      13759: 
1.1       albertel 13760: 1;
1.191     harris41 13761: __END__
                   13762: 
1.243     albertel 13763: =pod
                   13764: 
1.191     harris41 13765: =head1 NAME
                   13766: 
1.243     albertel 13767: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 13768: 
                   13769: =head1 SYNOPSIS
                   13770: 
1.243     albertel 13771: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 13772: 
                   13773:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   13774: 
1.243     albertel 13775: Common parameters:
                   13776: 
                   13777: =over 4
                   13778: 
                   13779: =item *
                   13780: 
                   13781: $uname : an internal username (if $cname expecting a course Id specifically)
                   13782: 
                   13783: =item *
                   13784: 
                   13785: $udom : a domain (if $cdom expecting a course's domain specifically)
                   13786: 
                   13787: =item *
                   13788: 
                   13789: $symb : a resource instance identifier
                   13790: 
                   13791: =item *
                   13792: 
                   13793: $namespace : the name of a .db file that contains the data needed or
                   13794: being set.
                   13795: 
                   13796: =back
                   13797: 
1.394     bowersj2 13798: =head1 OVERVIEW
1.191     harris41 13799: 
1.394     bowersj2 13800: lonnet provides subroutines which interact with the
                   13801: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   13802: about classes, users, and resources.
1.243     albertel 13803: 
                   13804: For many of these objects you can also use this to store data about
                   13805: them or modify them in various ways.
1.191     harris41 13806: 
1.394     bowersj2 13807: =head2 Symbs
1.191     harris41 13808: 
1.394     bowersj2 13809: To identify a specific instance of a resource, LON-CAPA uses symbols
                   13810: or "symbs"X<symb>. These identifiers are built from the URL of the
                   13811: map, the resource number of the resource in the map, and the URL of
                   13812: the resource itself. The latter is somewhat redundant, but might help
                   13813: if maps change.
                   13814: 
                   13815: An example is
                   13816: 
                   13817:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   13818: 
                   13819: The respective map entry is
                   13820: 
                   13821:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   13822:   title="Problem 2">
                   13823:  </resource>
                   13824: 
                   13825: Symbs are used by the random number generator, as well as to store and
                   13826: restore data specific to a certain instance of for example a problem.
                   13827: 
                   13828: =head2 Storing And Retrieving Data
                   13829: 
                   13830: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   13831: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   13832: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   13833: is is the non-critical message twin of cstore. These functions are for
                   13834: handlers to store a perl hash to a user's permanent data space in an
                   13835: easy manner, and to retrieve it again on another call. It is expected
                   13836: that a handler would use this once at the beginning to retrieve data,
                   13837: and then again once at the end to send only the new data back.
                   13838: 
                   13839: The data is stored in the user's data directory on the user's
                   13840: homeserver under the ID of the course.
                   13841: 
                   13842: The hash that is returned by restore will have all of the previous
                   13843: value for all of the elements of the hash.
                   13844: 
                   13845: Example:
                   13846: 
                   13847:  #creating a hash
                   13848:  my %hash;
                   13849:  $hash{'foo'}='bar';
                   13850: 
                   13851:  #storing it
                   13852:  &Apache::lonnet::cstore(\%hash);
                   13853: 
                   13854:  #changing a value
                   13855:  $hash{'foo'}='notbar';
                   13856: 
                   13857:  #adding a new value
                   13858:  $hash{'bar'}='foo';
                   13859:  &Apache::lonnet::cstore(\%hash);
                   13860: 
                   13861:  #retrieving the hash
                   13862:  my %history=&Apache::lonnet::restore();
                   13863: 
                   13864:  #print the hash
                   13865:  foreach my $key (sort(keys(%history))) {
                   13866:    print("\%history{$key} = $history{$key}");
                   13867:  }
                   13868: 
                   13869: Will print out:
1.191     harris41 13870: 
1.394     bowersj2 13871:  %history{1:foo} = bar
                   13872:  %history{1:keys} = foo:timestamp
                   13873:  %history{1:timestamp} = 990455579
                   13874:  %history{2:bar} = foo
                   13875:  %history{2:foo} = notbar
                   13876:  %history{2:keys} = foo:bar:timestamp
                   13877:  %history{2:timestamp} = 990455580
                   13878:  %history{bar} = foo
                   13879:  %history{foo} = notbar
                   13880:  %history{timestamp} = 990455580
                   13881:  %history{version} = 2
                   13882: 
                   13883: Note that the special hash entries C<keys>, C<version> and
                   13884: C<timestamp> were added to the hash. C<version> will be equal to the
                   13885: total number of versions of the data that have been stored. The
                   13886: C<timestamp> attribute will be the UNIX time the hash was
                   13887: stored. C<keys> is available in every historical section to list which
                   13888: keys were added or changed at a specific historical revision of a
                   13889: hash.
                   13890: 
                   13891: B<Warning>: do not store the hash that restore returns directly. This
                   13892: will cause a mess since it will restore the historical keys as if the
                   13893: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 13894: 
1.394     bowersj2 13895: Calling convention:
1.191     harris41 13896: 
1.1225    raeburn  13897:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  13898:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 13899: 
1.394     bowersj2 13900: For more detailed information, see lonnet specific documentation.
1.191     harris41 13901: 
1.394     bowersj2 13902: =head1 RETURN MESSAGES
1.191     harris41 13903: 
1.394     bowersj2 13904: =over 4
1.191     harris41 13905: 
1.394     bowersj2 13906: =item * B<con_lost>: unable to contact remote host
1.191     harris41 13907: 
1.394     bowersj2 13908: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   13909: when the connection is brought back up
1.191     harris41 13910: 
1.394     bowersj2 13911: =item * B<con_failed>: unable to contact remote host and unable to save message
                   13912: for later delivery
1.191     harris41 13913: 
1.967     bisitz   13914: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 13915: 
1.394     bowersj2 13916: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 13917: that was requested
1.191     harris41 13918: 
1.243     albertel 13919: =back
1.191     harris41 13920: 
1.243     albertel 13921: =head1 PUBLIC SUBROUTINES
1.191     harris41 13922: 
1.243     albertel 13923: =head2 Session Environment Functions
1.191     harris41 13924: 
1.243     albertel 13925: =over 4
1.191     harris41 13926: 
1.394     bowersj2 13927: =item * 
                   13928: X<appenv()>
1.949     raeburn  13929: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 13930: the user envirnoment file, and will be restored for each access this
1.620     albertel 13931: user makes during this session, also modifies the %env for the current
1.949     raeburn  13932: process. Optional rolesarrayref - if defined contains a reference to an array
                   13933: of roles which are exempt from the restriction on modifying user.role entries 
                   13934: in the user's environment.db and in %env.    
1.191     harris41 13935: 
                   13936: =item *
1.394     bowersj2 13937: X<delenv()>
1.987     raeburn  13938: B<delenv($delthis,$regexp)>: removes all items from the session
                   13939: environment file that begin with $delthis. If the 
                   13940: optional second arg - $regexp - is true, $delthis is treated as a 
                   13941: regular expression, otherwise \Q$delthis\E is used. 
                   13942: The values are also deleted from the current processes %env.
1.191     harris41 13943: 
1.795     albertel 13944: =item * get_env_multiple($name) 
                   13945: 
                   13946: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   13947: values may be defined and end up as an array ref.
                   13948: 
                   13949: returns an array of values
                   13950: 
1.243     albertel 13951: =back
                   13952: 
                   13953: =head2 User Information
1.191     harris41 13954: 
1.243     albertel 13955: =over 4
1.191     harris41 13956: 
                   13957: =item *
1.394     bowersj2 13958: X<queryauthenticate()>
                   13959: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 13960: authentication scheme
                   13961: 
                   13962: =item *
1.394     bowersj2 13963: X<authenticate()>
1.1073    raeburn  13964: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 13965: authenticate user from domain's lib servers (first use the current
                   13966: one). C<$upass> should be the users password.
1.1073    raeburn  13967: $checkdefauth is optional (value is 1 if a check should be made to
                   13968:    authenticate user using default authentication method, and allow
                   13969:    account creation if username does not have account in the domain).
                   13970: $clientcancheckhost is optional (value is 1 if checking whether the
                   13971:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 13972: 
                   13973: =item *
1.394     bowersj2 13974: X<homeserver()>
                   13975: B<homeserver($uname,$udom)>: find the server which has
                   13976: the user's directory and files (there must be only one), this caches
                   13977: the answer, and also caches if there is a borken connection.
1.191     harris41 13978: 
                   13979: =item *
1.394     bowersj2 13980: X<idget()>
1.1300    raeburn  13981: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   13982: a list of student/employee IDs or clicker IDs
                   13983: (student/employee IDs are a unique resource in a domain, there must be 
                   13984: only 1 ID per username, and only 1 username per ID in a specific domain).
                   13985: clickerIDs are not necessarily unique, as students might share clickers.
                   13986: (returns hash: id=>name,id=>name)
1.191     harris41 13987: 
                   13988: =item *
1.394     bowersj2 13989: X<idrget()>
                   13990: B<idrget($udom,@unames)>: find the IDs behind a list of
                   13991: usernames (returns hash: name=>id,name=>id)
1.191     harris41 13992: 
                   13993: =item *
1.394     bowersj2 13994: X<idput()>
1.1300    raeburn  13995: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   13996: names and associated student/employee IDs or clicker IDs.
                   13997: 
                   13998: =item *
                   13999: X<iddel()>
                   14000: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14001: student/employee ID or clicker ID username look-ups from domain.
                   14002: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14003: If no $uhome is provided, it will be determined usig &homeserver()
                   14004: for each user.  If no $namespace is provided, the default is ids.
                   14005: 
                   14006: =item *
                   14007: X<updateclickers()>
                   14008: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14009: clicker ID-to-username look-ups in clickers.db on library server.
                   14010: Permitted actions are add or del (i.e., add or delete). The 
                   14011: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14012: value is an escaped comma-separated list of usernames (for whom the
                   14013: library server is the homeserver), who registered that particular ID.
                   14014: If $critical is true, the update will be sent via &critical, otherwise
                   14015: &reply() will be used.
1.191     harris41 14016: 
                   14017: =item *
1.394     bowersj2 14018: X<rolesinit()>
1.1169    droeschl 14019: B<rolesinit($udom,$username)>: get user privileges.
                   14020: returns user role, first access and timer interval hashes
1.243     albertel 14021: 
                   14022: =item *
1.1171    droeschl 14023: X<privileged()>
                   14024: B<privileged($username,$domain)>: returns a true if user has a
                   14025: privileged and active role (i.e. su or dc), false otherwise.
                   14026: 
                   14027: =item *
1.551     albertel 14028: X<getsection()>
                   14029: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14030: course $cname, return section name/number or '' for "not in course"
                   14031: and '-1' for "no section"
                   14032: 
                   14033: =item *
1.394     bowersj2 14034: X<userenvironment()>
                   14035: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14036: passed in @what from the requested user's environment, returns a hash
                   14037: 
1.858     raeburn  14038: =item * 
                   14039: X<userlog_query()>
1.859     albertel 14040: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14041: activity.log file. %filters defines filters applied when parsing the
                   14042: log file. These can be start or end timestamps, or the type of action
                   14043: - log to look for Login or Logout events, check for Checkin or
                   14044: Checkout, role for role selection. The response is in the form
                   14045: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14046: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14047: 
1.243     albertel 14048: =back
                   14049: 
                   14050: =head2 User Roles
                   14051: 
                   14052: =over 4
                   14053: 
                   14054: =item *
                   14055: 
1.1284    raeburn  14056: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14057: returns codes for allowed actions.
                   14058: 
                   14059: The first argument is required, all others are optional.
                   14060: 
                   14061: $priv is the privilege being checked.
                   14062: $uri contains additional information about what is being checked for access (e.g.,
                   14063: URL, course ID etc.). 
                   14064: $symb is the unique resource instance identifier in a course; if needed,
                   14065: but not provided, it will be retrieved via a call to &symbread(). 
                   14066: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14067: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14068: files).
                   14069: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14070: prevents recursive calls to &allowed.
                   14071: 
1.243     albertel 14072:  F: full access
                   14073:  U,I,K: authentication modes (cxx only)
                   14074:  '': forbidden
                   14075:  1: user needs to choose course
                   14076:  2: browse allowed
1.766     albertel 14077:  A: passphrase authentication needed
1.1284    raeburn  14078:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14079: 
                   14080: =item *
                   14081: 
1.1192    raeburn  14082: constructaccess($url,$setpriv) : check for access to construction space URL
                   14083: 
                   14084: See if the owner domain and name in the URL match those in the
                   14085: expected environment.  If so, return three element list
                   14086: ($ownername,$ownerdomain,$ownerhome).
                   14087: 
                   14088: Otherwise return the null string.
                   14089: 
                   14090: If second argument 'setpriv' is true, it assigns the privileges,
                   14091: and returns the same three element list, unless the owner has
                   14092: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14093: in which case the null string is returned.
                   14094: 
                   14095: =item *
                   14096: 
1.1326    raeburn  14097: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14098: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14099: for system, domain, and course level. $uname and $udom are optional (current
                   14100: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14101: 
                   14102: =item *
                   14103: 
1.988     raeburn  14104: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14105: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14106: $type is Course (default) or Community.
1.988     raeburn  14107: If $forcedefault evaluates to true, text returned will be default 
                   14108: text for $type. Otherwise, if this is a course, the text returned 
                   14109: will be a custom name for the role (if defined in the course's 
                   14110: environment).  If no custom name is defined the default is returned.
                   14111:    
1.832     raeburn  14112: =item *
                   14113: 
1.1219    raeburn  14114: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14115: All arguments are optional. Returns a hash of a roles, either for
                   14116: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14117: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14118: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14119: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14120: For each key, value is set to colon-separated start and end times for
                   14121: the role.  If no username and domain are specified, will default to
1.934     raeburn  14122: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14123: of role statuses (active, future or previous), roles 
                   14124: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14125: to restrict the list of roles reported. If no array ref is 
                   14126: provided for types, will default to return only active roles.
1.834     albertel 14127: 
1.1195    raeburn  14128: =item *
                   14129: 
                   14130: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14131: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14132: 
                   14133: Additional optional arguments are: $type (if role checking is to be restricted 
                   14134: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14135: available roles) or future (roles available in the future), and
                   14136: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14137: have active Domain Coordinator role in course's domain or in additional
                   14138: domains (specified in 'Domains to check for privileged users' in course
                   14139: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14140: 
                   14141: =item *
                   14142: 
                   14143: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14144: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14145: $possdomains and $possroles are optional array refs -- to domains to check and
                   14146: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14147: users' roles.db to check for a dc or su role in any domain. This can be
                   14148: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14149: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14150: this then allows &privileged_by_domain() to be used, which caches the identity
                   14151: of privileged users, eliminating the need for repeated calls to &dump().
                   14152: 
                   14153: =item *
                   14154: 
                   14155: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14156: where the outer hash keys are domains specified in the $possdomains array ref,
                   14157: next inner hash keys are privileged roles specified in the $roles array ref,
                   14158: and the innermost hash contains key = value pairs for username:domain = end:start
                   14159: for active or future "privileged" users with that role in that domain. To avoid
                   14160: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14161: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14162: 
1.243     albertel 14163: =back
                   14164: 
                   14165: =head2 User Modification
                   14166: 
                   14167: =over 4
                   14168: 
                   14169: =item *
                   14170: 
1.957     raeburn  14171: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14172: user for the level given by URL.  Optional start and end dates (leave empty
                   14173: string or zero for "no date")
1.191     harris41 14174: 
                   14175: =item *
                   14176: 
1.243     albertel 14177: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14178: change a users, password, possible return values are: ok,
                   14179: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14180: refused
1.191     harris41 14181: 
                   14182: =item *
                   14183: 
1.243     albertel 14184: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14185: 
                   14186: =item *
                   14187: 
1.1058    raeburn  14188: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14189:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14190: 
                   14191: will update user information (firstname,middlename,lastname,generation,
                   14192: permanentemail), and if forceid is true, student/employee ID also.
                   14193: A user's institutional affiliation(s) can also be updated.
                   14194: User information fields will not be overwritten with empty entries 
                   14195: unless the field is included in the $candelete array reference.
                   14196: This array is included when a single user is modified via "Manage Users",
                   14197: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14198: 
                   14199: =item *
                   14200: 
1.286     matthew  14201: modifystudent
                   14202: 
1.957     raeburn  14203: modify a student's enrollment and identification information.
1.1235    raeburn  14204: The course id is resolved based on the current user's environment.  
                   14205: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14206: associated with a course.
                   14207: 
1.297     matthew  14208: This call is essentially a wrapper for lonnet::modifyuser and
                   14209: lonnet::modify_student_enrollment
1.286     matthew  14210: 
                   14211: Inputs: 
                   14212: 
                   14213: =over 4
                   14214: 
1.957     raeburn  14215: =item B<$udom> Student's loncapa domain
1.286     matthew  14216: 
1.957     raeburn  14217: =item B<$uname> Student's loncapa login name
1.286     matthew  14218: 
1.964     bisitz   14219: =item B<$uid> Student/Employee ID
1.286     matthew  14220: 
1.957     raeburn  14221: =item B<$umode> Student's authentication mode
1.286     matthew  14222: 
1.957     raeburn  14223: =item B<$upass> Student's password
1.286     matthew  14224: 
1.957     raeburn  14225: =item B<$first> Student's first name
1.286     matthew  14226: 
1.957     raeburn  14227: =item B<$middle> Student's middle name
1.286     matthew  14228: 
1.957     raeburn  14229: =item B<$last> Student's last name
1.286     matthew  14230: 
1.957     raeburn  14231: =item B<$gene> Student's generation
1.286     matthew  14232: 
1.957     raeburn  14233: =item B<$usec> Student's section in course
1.286     matthew  14234: 
                   14235: =item B<$end> Unix time of the roles expiration
                   14236: 
                   14237: =item B<$start> Unix time of the roles start date
                   14238: 
                   14239: =item B<$forceid> If defined, allow $uid to be changed
                   14240: 
                   14241: =item B<$desiredhome> server to use as home server for student
                   14242: 
1.957     raeburn  14243: =item B<$email> Student's permanent e-mail address
                   14244: 
                   14245: =item B<$type> Type of enrollment (auto or manual)
                   14246: 
1.963     raeburn  14247: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14248: 
                   14249: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14250: 
1.963     raeburn  14251: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14252: 
1.963     raeburn  14253: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14254: 
1.1216    raeburn  14255: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14256: 
                   14257: =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  14258: 
1.286     matthew  14259: =back
1.297     matthew  14260: 
                   14261: =item *
                   14262: 
                   14263: modify_student_enrollment
                   14264: 
1.1235    raeburn  14265: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14266: 'role.request.course' must be defined for this function to proceed.
                   14267: 
                   14268: Inputs:
                   14269: 
                   14270: =over 4
                   14271: 
1.1235    raeburn  14272: =item $udom, student's domain
1.297     matthew  14273: 
1.1235    raeburn  14274: =item $uname, student's name
1.297     matthew  14275: 
1.1235    raeburn  14276: =item $uid, student's user id
1.297     matthew  14277: 
1.1235    raeburn  14278: =item $first, student's first name
1.297     matthew  14279: 
                   14280: =item $middle
                   14281: 
                   14282: =item $last
                   14283: 
                   14284: =item $gene
                   14285: 
                   14286: =item $usec
                   14287: 
                   14288: =item $end
                   14289: 
                   14290: =item $start
                   14291: 
1.957     raeburn  14292: =item $type
                   14293: 
                   14294: =item $locktype
                   14295: 
                   14296: =item $cid
                   14297: 
                   14298: =item $selfenroll
                   14299: 
                   14300: =item $context
                   14301: 
1.1216    raeburn  14302: =item $credits, number of credits student will earn from this class
                   14303: 
1.1314    raeburn  14304: =item $instsec, institutional course section code for student
                   14305: 
1.297     matthew  14306: =back
                   14307: 
1.191     harris41 14308: 
                   14309: =item *
                   14310: 
1.243     albertel 14311: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14312: custom role; give a custom role to a user for the level given by URL.  Specify
                   14313: name and domain of role author, and role name
1.191     harris41 14314: 
                   14315: =item *
                   14316: 
1.243     albertel 14317: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14318: 
                   14319: =item *
                   14320: 
1.243     albertel 14321: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14322: 
                   14323: =back
                   14324: 
                   14325: =head2 Course Infomation
                   14326: 
                   14327: =over 4
1.191     harris41 14328: 
                   14329: =item *
                   14330: 
1.1118    foxr     14331: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14332: specified course id, including all environment settings for the
                   14333: course, the description of the course will be in the hash under the
                   14334: key 'description'
1.191     harris41 14335: 
1.1118    foxr     14336: $options is an optional parameter that if supplied is a hash reference that controls
                   14337: what how this function works.  It has the following key/values:
                   14338: 
                   14339: =over 4
                   14340: 
                   14341: =item freshen_cache
                   14342: 
                   14343: If defined, and the environment cache for the course is valid, it is 
                   14344: returned in the returned hash.
                   14345: 
                   14346: =item one_time
                   14347: 
                   14348: If defined, the last cache time is set to _now_
                   14349: 
                   14350: =item user
                   14351: 
                   14352: If defined, the supplied username is used instead of the current user.
                   14353: 
                   14354: 
                   14355: =back
                   14356: 
1.191     harris41 14357: =item *
                   14358: 
1.624     albertel 14359: resdata($name,$domain,$type,@which) : request for current parameter
                   14360: setting for a specific $type, where $type is either 'course' or 'user',
                   14361: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14362: answers for 10 minutes.
1.243     albertel 14363: 
1.877     foxr     14364: =item *
                   14365: 
                   14366: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14367: data base, returning a hash that is keyed by the resource name and has
                   14368: values that are the resource value.  I believe that the timestamps and
                   14369: versions are also returned.
                   14370: 
1.1236    raeburn  14371: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14372: supplemental content area. This routine caches the number of files for 
                   14373: 10 minutes.
                   14374: 
1.243     albertel 14375: =back
                   14376: 
                   14377: =head2 Course Modification
                   14378: 
                   14379: =over 4
1.191     harris41 14380: 
                   14381: =item *
                   14382: 
1.243     albertel 14383: writecoursepref($courseid,%prefs) : write preferences (environment
                   14384: database) for a course
1.191     harris41 14385: 
                   14386: =item *
                   14387: 
1.1011    raeburn  14388: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14389: 
                   14390: =item *
                   14391: 
1.1038    raeburn  14392: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14393: 
1.1167    droeschl 14394: =item *
                   14395: 
                   14396: is_course($courseid), is_course($cdom, $cnum)
                   14397: 
                   14398: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14399: two component version $cdom, $cnum. It checks if the specified course exists.
                   14400: 
                   14401: Returns:
                   14402:     undef if the course doesn't exist, otherwise
                   14403:     in scalar context the combined courseid.
                   14404:     in list context the two components of the course identifier, domain and 
                   14405:     courseid.    
                   14406: 
1.243     albertel 14407: =back
                   14408: 
                   14409: =head2 Resource Subroutines
                   14410: 
                   14411: =over 4
1.191     harris41 14412: 
                   14413: =item *
                   14414: 
1.243     albertel 14415: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14416: 
                   14417: =item *
                   14418: 
1.243     albertel 14419: repcopy($filename) : subscribes to the requested file, and attempts to
                   14420: replicate from the owning library server, Might return
1.607     raeburn  14421: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14422: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14423: resource. Expects the local filesystem pathname
                   14424: (/home/httpd/html/res/....)
                   14425: 
                   14426: =back
                   14427: 
                   14428: =head2 Resource Information
                   14429: 
                   14430: =over 4
1.191     harris41 14431: 
                   14432: =item *
                   14433: 
1.1228    raeburn  14434: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14435: and returns the value of a variety of different possible values,
                   14436: $varname should be a request string, and the other parameters can be
                   14437: used to specify who and what one is asking about. Ordinarily, $cid 
                   14438: does not need to be specified, as it is retrived from 
                   14439: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14440: within lonuserstate::loadmap() when initializing a course, before
                   14441: $env{'request.course.id'} has been set, so it needs to be provided
                   14442: in that one case.
1.243     albertel 14443: 
                   14444: Possible values for $varname are environment.lastname (or other item
                   14445: from the envirnment hash), user.name (or someother aspect about the
                   14446: user), resource.0.maxtries (or some other part and parameter of a
                   14447: resource)
1.204     albertel 14448: 
                   14449: =item *
                   14450: 
1.243     albertel 14451: directcondval($number) : get current value of a condition; reads from a state
                   14452: string
1.204     albertel 14453: 
                   14454: =item *
                   14455: 
1.243     albertel 14456: condval($condidx) : value of condition index based on state
1.204     albertel 14457: 
                   14458: =item *
                   14459: 
1.243     albertel 14460: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   14461: resource's metadata, $what should be either a specific key, or either
                   14462: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   14463: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   14464: 
                   14465: this function automatically caches all requests
1.191     harris41 14466: 
                   14467: =item *
                   14468: 
1.243     albertel 14469: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14470: network of library servers; returns file handle of where SQL and regex results
                   14471: will be stored for query
1.191     harris41 14472: 
                   14473: =item *
                   14474: 
1.1282    raeburn  14475: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14476: return symbolic list entry (all arguments optional). 
                   14477: 
                   14478: Args: filename is the filename (including path) for the file for which a symb 
                   14479: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14480: to check access status if more than one resource was found in the bighash 
                   14481: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14482: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14483: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14484: cause possible symbs to be checked to determine if they are subject to content
                   14485: blocking, if so they will not be included as possible symbs; possibles is a
                   14486: ref to a hash, which, as a side effect, will be populated with all possible 
                   14487: symbs (content blocking not tested).
                   14488:  
1.243     albertel 14489: returns the data handle
1.191     harris41 14490: 
                   14491: =item *
                   14492: 
1.1190    raeburn  14493: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14494: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14495: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14496: on failure, user must be in a course, as it assumes the existence of
                   14497: the course initial hash, and uses $env('request.course.id'}.  The third
                   14498: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14499: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14500: encrypted; otherwise it will be null.  
1.191     harris41 14501: 
                   14502: =item *
                   14503: 
1.243     albertel 14504: symbclean($symb) : removes versions numbers from a symb, returns the
                   14505: cleaned symb
1.191     harris41 14506: 
                   14507: =item *
                   14508: 
1.243     albertel 14509: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14510: course map, user must be in a course for it to work.
1.191     harris41 14511: 
                   14512: =item *
                   14513: 
1.243     albertel 14514: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14515: 
                   14516: =item *
                   14517: 
1.243     albertel 14518: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14519: a random seed, all arguments are optional, if they aren't sent it uses the
                   14520: environment to derive them. Note: if symb isn't sent and it can't get one
                   14521: from &symbread it will use the current time as its return value
1.191     harris41 14522: 
                   14523: =item *
                   14524: 
1.243     albertel 14525: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14526: unfakeable, receipt
1.191     harris41 14527: 
                   14528: =item *
                   14529: 
1.620     albertel 14530: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14531: 
                   14532: =item *
                   14533: 
1.243     albertel 14534: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14535: 
                   14536: =item *
                   14537: 
1.243     albertel 14538: 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 14539: 
                   14540: =item *
                   14541: 
1.243     albertel 14542: 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 14543: 
                   14544: =item *
                   14545: 
1.243     albertel 14546: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14547: 
                   14548: =item *
                   14549: 
1.243     albertel 14550: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14551: forcing spreadsheet to reevaluate the resource scores next time.
                   14552: 
1.1195    raeburn  14553: =item * 
                   14554: 
1.1196    raeburn  14555: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14556: when viewing in course context.
1.1195    raeburn  14557: 
1.1196    raeburn  14558:  input: six args -- filename (decluttered), course number, course domain,
                   14559:                     url, symb (if registered) and group (if this is a 
                   14560:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14561: 
1.1196    raeburn  14562:  output: array of five scalars --
1.1195    raeburn  14563:          $cfile -- url for file editing if editable on current server
                   14564:          $home -- homeserver of resource (i.e., for author if published,
                   14565:                                           or course if uploaded.).
                   14566:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14567:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14568:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  14569: 
                   14570: =item *
                   14571: 
                   14572: is_course_upload($file,$cnum,$cdom)
                   14573: 
                   14574: Used in course context to determine if current file was uploaded to 
                   14575: the course (i.e., would be found in /userfiles/docs on the course's 
                   14576: homeserver.
                   14577: 
                   14578:   input: 3 args -- filename (decluttered), course number and course domain.
                   14579:   output: boolean -- 1 if file was uploaded.
                   14580: 
1.243     albertel 14581: =back
                   14582: 
                   14583: =head2 Storing/Retreiving Data
                   14584: 
                   14585: =over 4
1.191     harris41 14586: 
                   14587: =item *
                   14588: 
1.1269    raeburn  14589: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   14590: permanently for this url; hashref needs to be given and should be a \%hashname;
                   14591: the remaining args aren't required and if they aren't passed or are '' they will
                   14592: be derived from the env (with the exception of $laststore, which is an 
                   14593: optional arg used when a user's submission is stored in grading).
                   14594: $laststore is $version=$timestamp, where $version is the most recent version
                   14595: number retrieved for the corresponding $symb in the $namespace db file, and
                   14596: $timestamp is the timestamp for that transaction (UNIX time).
                   14597: $laststore is currently only passed when cstore() is called by 
                   14598: structuretags::finalize_storage().
1.191     harris41 14599: 
                   14600: =item *
                   14601: 
1.1269    raeburn  14602: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   14603: but uses critical subroutine
1.191     harris41 14604: 
                   14605: =item *
                   14606: 
1.243     albertel 14607: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   14608: all args are optional
1.191     harris41 14609: 
                   14610: =item *
                   14611: 
1.717     albertel 14612: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   14613: dumps the complete (or key matching regexp) namespace into a hash
                   14614: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   14615: normally &store()ed into
                   14616: 
                   14617: $range should be either an integer '100' (give me the first 100
                   14618:                                            matching records)
                   14619:               or be  two integers sperated by a - with no spaces
                   14620:                  '30-50' (give me the 30th through the 50th matching
                   14621:                           records)
                   14622: 
                   14623: 
                   14624: =item *
                   14625: 
1.1269    raeburn  14626: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 14627: replaces a &store() version of data with a replacement set of data
                   14628: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  14629: reference. If $tolog is true, the transaction is logged in the courselog
                   14630: with an action=PUTSTORE.
1.717     albertel 14631: 
                   14632: =item *
                   14633: 
1.243     albertel 14634: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   14635: works very similar to store/cstore, but all data is stored in a
                   14636: temporary location and can be reset using tmpreset, $storehash should
                   14637: be a hash reference, returns nothing on success
1.191     harris41 14638: 
                   14639: =item *
                   14640: 
1.243     albertel 14641: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   14642: similar to restore, but all data is stored in a temporary location and
                   14643: can be reset using tmpreset. Returns a hash of values on success,
                   14644: error string otherwise.
1.191     harris41 14645: 
                   14646: =item *
                   14647: 
1.243     albertel 14648: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   14649: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 14650: 
                   14651: =item *
                   14652: 
1.243     albertel 14653: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14654: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 14655: 
                   14656: =item *
                   14657: 
1.243     albertel 14658: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   14659: namesp ($udom and $uname are optional)
1.191     harris41 14660: 
                   14661: =item *
                   14662: 
1.702     albertel 14663: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 14664: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 14665: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  14666: 
1.702     albertel 14667: $range should be either an integer '100' (give me the first 100
                   14668:                                            matching records)
                   14669:               or be  two integers sperated by a - with no spaces
                   14670:                  '30-50' (give me the 30th through the 50th matching
                   14671:                           records)
1.449     matthew  14672: =item *
                   14673: 
                   14674: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   14675: $store can be a scalar, an array reference, or if the amount to be 
                   14676: incremented is > 1, a hash reference.
                   14677: 
                   14678: ($udom and $uname are optional)
1.191     harris41 14679: 
                   14680: =item *
                   14681: 
1.243     albertel 14682: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   14683: ($udom and $uname are optional)
1.191     harris41 14684: 
                   14685: =item *
                   14686: 
1.243     albertel 14687: cput($namespace,$storehash,$udom,$uname) : critical put
                   14688: ($udom and $uname are optional)
1.191     harris41 14689: 
                   14690: =item *
                   14691: 
1.748     albertel 14692: newput($namespace,$storehash,$udom,$uname) :
                   14693: 
                   14694: Attempts to store the items in the $storehash, but only if they don't
                   14695: currently exist, if this succeeds you can be certain that you have 
                   14696: successfully created a new key value pair in the $namespace db.
                   14697: 
                   14698: 
                   14699: Args:
                   14700:  $namespace: name of database to store values to
                   14701:  $storehash: hashref to store to the db
                   14702:  $udom: (optional) domain of user containing the db
                   14703:  $uname: (optional) name of user caontaining the db
                   14704: 
                   14705: Returns:
                   14706:  'ok' -> succeeded in storing all keys of $storehash
                   14707:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   14708:                         least <key> already existed in the db (other
                   14709:                         requested keys may also already exist)
1.967     bisitz   14710:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 14711:  'con_lost' -> unable to contact request server
                   14712:  'refused' -> action was not allowed by remote machine
                   14713: 
                   14714: 
                   14715: =item *
                   14716: 
1.243     albertel 14717: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   14718: reference filled in from namesp (encrypts the return communication)
                   14719: ($udom and $uname are optional)
1.191     harris41 14720: 
                   14721: =item *
                   14722: 
1.243     albertel 14723: log($udom,$name,$home,$message) : write to permanent log for user; use
                   14724: critical subroutine
                   14725: 
1.806     raeburn  14726: =item *
                   14727: 
1.860     raeburn  14728: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   14729: array reference filled in from namespace found in domain level on either
                   14730: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  14731: 
                   14732: =item *
                   14733: 
1.860     raeburn  14734: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   14735: domain level either on specified domain server ($uhome) or primary domain 
                   14736: server ($udom and $uhome are optional)
1.806     raeburn  14737: 
1.943     raeburn  14738: =item * 
                   14739: 
1.1240    raeburn  14740: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   14741: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   14742: the target domain.
                   14743: 
                   14744: May also include additional key => value pairs for the following groups:
                   14745: 
                   14746: =over
                   14747: 
                   14748: =item
                   14749: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   14750: 
                   14751: =over
                   14752: 
                   14753: =item defaultquota, authorquota
                   14754: 
                   14755: =back
                   14756: 
                   14757: =item
                   14758: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   14759: portfolio for users).
                   14760: 
                   14761: =over
                   14762: 
                   14763: =item
                   14764: aboutme, blog, webdav, portfolio
                   14765: 
                   14766: =back
                   14767: 
                   14768: =item
                   14769: requestcourses: ability to request courses, and how requests are processed.
                   14770: 
                   14771: =over
                   14772: 
                   14773: =item
1.1305    raeburn  14774: official, unofficial, community, textbook, placement
1.1240    raeburn  14775: 
                   14776: =back
                   14777: 
                   14778: =item
                   14779: inststatus: types of institutional affiliation, and order in which they are displayed.
                   14780: 
                   14781: =over
                   14782: 
                   14783: =item
1.1256    raeburn  14784: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  14785: 
                   14786: =back
                   14787: 
                   14788: =item
                   14789: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   14790: for course's uploaded content.
                   14791: 
                   14792: =over
                   14793: 
                   14794: =item
1.1246    raeburn  14795: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  14796: communityquota, textbookquota, placementquota
1.1240    raeburn  14797: 
                   14798: =back
                   14799: 
                   14800: =item
                   14801: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   14802: on your servers.
                   14803: 
                   14804: =over
                   14805: 
                   14806: =item 
                   14807: remotesessions, hostedsessions
                   14808: 
                   14809: =back
                   14810: 
                   14811: =back
                   14812: 
                   14813: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   14814: utility to create a configuration.db file on a domain's primary library server 
                   14815: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   14816: -- corresponding values are authentication type (internal, krb4, krb5,
                   14817: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   14818: will be available. Values are retrieved from cache (if current), unless the
                   14819: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   14820: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   14821: 
                   14822: Typical usage:
1.943     raeburn  14823: 
1.1240    raeburn  14824: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  14825: 
1.243     albertel 14826: =back
                   14827: 
                   14828: =head2 Network Status Functions
                   14829: 
                   14830: =over 4
1.191     harris41 14831: 
                   14832: =item *
                   14833: 
1.1137    raeburn  14834: dirlist() : return directory list based on URI (first arg).
                   14835: 
                   14836: Inputs: 1 required, 5 optional.
                   14837: 
                   14838: =over
                   14839: 
                   14840: =item 
                   14841: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   14842: 
                   14843: =item
                   14844: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   14845: 
                   14846: =item
                   14847: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   14848: 
                   14849: =item
                   14850: $getpropath - boolean: 1 if prepend path using &propath(). 
                   14851: 
                   14852: =item
                   14853: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   14854: 
                   14855: =item 
                   14856: $alternateRoot - path to prepend in place of path from $uri.
                   14857: 
                   14858: =back
                   14859: 
                   14860: Returns: Array of up to two items.
                   14861: 
                   14862: =over
                   14863: 
                   14864: a reference to an array of files/subdirectories
                   14865: 
                   14866: =over
                   14867: 
                   14868: Each element in the array of files/subdirectories is a & separated list of
                   14869: item name and the result of running stat on the item.  If dirlist was requested
                   14870: for a file instead of a directory, the item name will be ''. For a directory 
                   14871: listing, if the item is a metadata file, the element will end &N&M 
                   14872: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   14873: default copyright set (1).  
                   14874: 
                   14875: =back
                   14876: 
                   14877: a scalar containing error condition (if encountered).
                   14878: 
                   14879: =over
                   14880: 
                   14881: =item 
                   14882: no_host (no homeserver identified for $username:$domain).
                   14883: 
                   14884: =item 
                   14885: no_such_host (server contacted for listing not identified as valid host).
                   14886: 
                   14887: =item 
                   14888: con_lost (connection to remote server failed).
                   14889: 
                   14890: =item 
                   14891: refused (invalid $username:$domain received on lond side).
                   14892: 
                   14893: =item 
                   14894: no_such_dir (directory at specified path on lond side does not exist). 
                   14895: 
                   14896: =item 
                   14897: empty (directory at specified path on lond side is empty).
                   14898: 
                   14899: =over
                   14900: 
                   14901: This is currently not encountered because the &ls3, &ls2, 
                   14902: &ls (_handler) routines on the lond side do not filter out
                   14903: . and .. from a directory listing. 
                   14904: 
                   14905: =back
                   14906: 
                   14907: =back
                   14908: 
                   14909: =back
1.191     harris41 14910: 
                   14911: =item *
                   14912: 
1.243     albertel 14913: spareserver() : find server with least workload from spare.tab
                   14914: 
1.986     foxr     14915: 
                   14916: =item *
                   14917: 
                   14918: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   14919: if there is no corresponding loncapa host.
                   14920: 
1.243     albertel 14921: =back
                   14922: 
1.986     foxr     14923: 
1.243     albertel 14924: =head2 Apache Request
                   14925: 
                   14926: =over 4
1.191     harris41 14927: 
                   14928: =item *
                   14929: 
1.243     albertel 14930: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   14931: localhost, posts hash
                   14932: 
                   14933: =back
                   14934: 
                   14935: =head2 Data to String to Data
                   14936: 
                   14937: =over 4
1.191     harris41 14938: 
                   14939: =item *
                   14940: 
1.243     albertel 14941: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   14942: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 14943: 
                   14944: =item *
                   14945: 
1.243     albertel 14946: hashref2str($hashref) : convert a hashref into a string complete with
                   14947: escaping and '=' and '&' separators, supports elements that are
                   14948: arrayrefs and hashrefs
1.191     harris41 14949: 
                   14950: =item *
                   14951: 
1.243     albertel 14952: arrayref2str($arrayref) : convert an arrayref into a string complete
                   14953: with escaping and '&' separators, supports elements that are arrayrefs
                   14954: and hashrefs
1.191     harris41 14955: 
                   14956: =item *
                   14957: 
1.243     albertel 14958: str2hash($string) : convert string to hash using unescaping and
                   14959: splitting on '=' and '&', supports elements that are arrayrefs and
                   14960: hashrefs
1.191     harris41 14961: 
                   14962: =item *
                   14963: 
1.243     albertel 14964: str2array($string) : convert string to hash using unescaping and
                   14965: splitting on '&', supports elements that are arrayrefs and hashrefs
                   14966: 
                   14967: =back
                   14968: 
                   14969: =head2 Logging Routines
                   14970: 
                   14971: 
                   14972: These routines allow one to make log messages in the lonnet.log and
                   14973: lonnet.perm logfiles.
1.191     harris41 14974: 
1.1119    foxr     14975: =over 4
                   14976: 
1.191     harris41 14977: =item *
                   14978: 
1.243     albertel 14979: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 14980: 
                   14981: =item *
                   14982: 
1.243     albertel 14983: logthis() : append message to the normal lonnet.log file, it gets
                   14984: preiodically rolled over and deleted.
1.191     harris41 14985: 
                   14986: =item *
                   14987: 
1.243     albertel 14988: logperm() : append a permanent message to lonnet.perm.log, this log
                   14989: file never gets deleted by any automated portion of the system, only
                   14990: messages of critical importance should go in here.
                   14991: 
1.1119    foxr     14992: 
1.243     albertel 14993: =back
                   14994: 
                   14995: =head2 General File Helper Routines
                   14996: 
                   14997: =over 4
1.191     harris41 14998: 
                   14999: =item *
                   15000: 
1.481     raeburn  15001: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15002: (a) files in /uploaded
                   15003:   (i) If a local copy of the file exists - 
                   15004:       compares modification date of local copy with last-modified date for 
                   15005:       definitive version stored on home server for course. If local copy is 
                   15006:       stale, requests a new version from the home server and stores it. 
                   15007:       If the original has been removed from the home server, then local copy 
                   15008:       is unlinked.
                   15009:   (ii) If local copy does not exist -
                   15010:       requests the file from the home server and stores it. 
                   15011:   
                   15012:   If $caller is 'uploadrep':  
                   15013:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15014:     for request for files originally uploaded via DOCS. 
                   15015:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15016:   
                   15017:   Otherwise:
                   15018:      This indicates a call from the content generation phase of the request.
                   15019:      -  returns the entire contents of the file or -1.
                   15020:      
                   15021: (b) files in /res
                   15022:    - returns the entire contents of a file or -1; 
                   15023:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15024: 
1.712     albertel 15025: 
                   15026: =item *
                   15027: 
                   15028: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15029:                   reference
                   15030: 
                   15031: returns either a stat() list of data about the file or an empty list
                   15032: if the file doesn't exist or couldn't find out about it (connection
                   15033: problems or user unknown)
                   15034: 
1.191     harris41 15035: =item *
                   15036: 
1.243     albertel 15037: filelocation($dir,$file) : returns file system location of a file
                   15038: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15039: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15040: and a file of ../bob will become /a/bob)
1.191     harris41 15041: 
                   15042: =item *
                   15043: 
                   15044: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15045: filelocation except for hrefs
                   15046: 
                   15047: =item *
                   15048: 
1.1261    raeburn  15049: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15050: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15051: 
1.243     albertel 15052: =back
                   15053: 
1.608     albertel 15054: =head2 Usererfile file routines (/uploaded*)
                   15055: 
                   15056: =over 4
                   15057: 
                   15058: =item *
                   15059: 
                   15060: userfileupload(): main rotine for putting a file in a user or course's
                   15061:                   filespace, arguments are,
                   15062: 
1.620     albertel 15063:  formname - required - this is the name of the element in $env where the
1.608     albertel 15064:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15065:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15066:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15067:  context - if coursedoc, store the file in the course of the active role
                   15068:              of the current user; 
                   15069:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15070:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15071:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15072:          if undefined, it will be placed in "unknown"
                   15073: 
                   15074:  (This routine calls clean_filename() to remove any dangerous
                   15075:  characters from the filename, and then calls finuserfileupload() to
                   15076:  complete the transaction)
                   15077: 
                   15078:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15079:  and /adm/notfound.html if unsuccessful
                   15080: 
                   15081: =item *
                   15082: 
                   15083: clean_filename(): routine for cleaing a filename up for storage in
                   15084:                  userfile space, argument is:
                   15085: 
                   15086:  filename - proposed filename
                   15087: 
                   15088: returns: the new clean filename
                   15089: 
                   15090: =item *
                   15091: 
1.1090    raeburn  15092: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15093: userspace, probably shouldn't be called directly
                   15094: 
                   15095:   docuname: username or courseid of destination for the file
                   15096:   docudom: domain of user/course of destination for the file
                   15097:   formname: same as for userfileupload()
1.1090    raeburn  15098:   fname: filename (including subdirectories) for the file
                   15099:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15100:   allfiles: reference to hash used to store objects found by parser
                   15101:   codebase: reference to hash used for codebases of java objects found by parser
                   15102:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15103:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15104:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15105:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15106:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15107:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15108:   mimetype: reference to scalar to accommodate mime type determined
                   15109:             from File::MMagic if $parser = parse.
1.608     albertel 15110: 
                   15111:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15112:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15113:  was 'overwrite').
                   15114:  
1.608     albertel 15115: 
                   15116: =item *
                   15117: 
                   15118: renameuserfile(): renames an existing userfile to a new name
                   15119: 
                   15120:   Args:
                   15121:    docuname: username or courseid of destination for the file
                   15122:    docudom: domain of user/course of destination for the file
                   15123:    old: current file name (including any subdirs under userfiles)
                   15124:    new: desired file name (including any subdirs under userfiles)
                   15125: 
                   15126: =item *
                   15127: 
                   15128: mkdiruserfile(): creates a directory is a userfiles dir
                   15129: 
                   15130:   Args:
                   15131:    docuname: username or courseid of destination for the file
                   15132:    docudom: domain of user/course of destination for the file
                   15133:    dir: dir to create (including any subdirs under userfiles)
                   15134: 
                   15135: =item *
                   15136: 
                   15137: removeuserfile(): removes a file that exists in userfiles
                   15138: 
                   15139:   Args:
                   15140:    docuname: username or courseid of destination for the file
                   15141:    docudom: domain of user/course of destination for the file
                   15142:    fname: filname to delete (including any subdirs under userfiles)
                   15143: 
                   15144: =item *
                   15145: 
                   15146: removeuploadedurl(): convience function for removeuserfile()
                   15147: 
                   15148:   Args:
                   15149:    url:  a full /uploaded/... url to delete
                   15150: 
1.747     albertel 15151: =item * 
                   15152: 
                   15153: get_portfile_permissions():
                   15154:   Args:
                   15155:     domain: domain of user or course contain the portfolio files
                   15156:     user: name of user or num of course contain the portfolio files
                   15157:   Returns:
                   15158:     hashref of a dump of the proper file_permissions.db
                   15159:    
                   15160: 
                   15161: =item * 
                   15162: 
                   15163: get_access_controls():
                   15164: 
                   15165: Args:
                   15166:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15167:   group: (optional) the group you want the files associated with
                   15168:   file: (optional) the file you want access info on
                   15169: 
                   15170: Returns:
1.749     raeburn  15171:     a hash (keys are file names) of hashes containing
                   15172:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15173:         values are XML containing access control settings (see below) 
1.747     albertel 15174: 
                   15175: Internal notes:
                   15176: 
1.749     raeburn  15177:  access controls are stored in file_permissions.db as key=value pairs.
                   15178:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15179:         where scope -> public,guest,course,group,domains or users.
                   15180:               end -> UNIX time for end of access (0 -> no end date)
                   15181:               start -> UNIX time for start of access
                   15182: 
                   15183:     value -> XML description of access control
                   15184:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15185:             <start></start>
                   15186:             <end></end>
                   15187: 
                   15188:             <password></password>  for scope type = guest
                   15189: 
                   15190:             <domain></domain>     for scope type = course or group
                   15191:             <number></number>
                   15192:             <roles id="">
                   15193:              <role></role>
                   15194:              <access></access>
                   15195:              <section></section>
                   15196:              <group></group>
                   15197:             </roles>
                   15198: 
                   15199:             <dom></dom>         for scope type = domains
                   15200: 
                   15201:             <users>             for scope type = users
                   15202:              <user>
                   15203:               <uname></uname>
                   15204:               <udom></udom>
                   15205:              </user>
                   15206:             </users>
                   15207:            </scope> 
                   15208:               
                   15209:  Access data is also aggregated for each file in an additional key=value pair:
                   15210:  key -> path to file/file_name\0accesscontrol 
                   15211:  value -> reference to hash
                   15212:           hash contains key = value pairs
                   15213:           where key = uniqueID:scope_end_start
                   15214:                 value = UNIX time record was last updated
                   15215: 
                   15216:           Used to improve speed of look-ups of access controls for each file.  
                   15217:  
                   15218:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15219: 
1.1198    raeburn  15220: =item *
                   15221: 
1.749     raeburn  15222: modify_access_controls():
                   15223: 
                   15224: Modifies access controls for a portfolio file
                   15225: Args
                   15226: 1. file name
                   15227: 2. reference to hash of required changes,
                   15228: 3. domain
                   15229: 4. username
                   15230:   where domain,username are the domain of the portfolio owner 
                   15231:   (either a user or a course) 
                   15232: 
                   15233: Returns:
                   15234: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15235: 2. result of deletions ('ok' or 'error', with error message).
                   15236: 3. reference to hash of any new or updated access controls.
                   15237: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15238:    key = integer (inbound ID)
1.1198    raeburn  15239:    value = uniqueID
                   15240: 
                   15241: =item *
                   15242: 
                   15243: get_timebased_id():
                   15244: 
                   15245: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15246: course via the Course Editor (e.g., folders, composite pages, 
                   15247: group bulletin boards).
                   15248: 
                   15249: Args: (first three required; six others optional)
                   15250: 
                   15251: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15252:    docssequence, or name of group
                   15253: 
                   15254: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15255:    e.g., num, boardids
                   15256: 
                   15257: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15258:    file will be named nohist_namespace.db
                   15259: 
                   15260: 4. cdom: domain of course; default is current course domain from %env
                   15261: 
                   15262: 5. cnum: course number; default is current course number from %env
                   15263: 
                   15264: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15265:    unix timestamp to form the suffix, if the plain timestamp is already
                   15266:    in use.  Default is to not do this, but simply increment the unix 
                   15267:    timestamp by 1 until a unique key is obtained.
                   15268: 
                   15269: 7. who: holder of locking key; defaults to user:domain for user.
                   15270: 
                   15271: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15272:    retrying); default is 3.
                   15273: 
                   15274: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15275: 
                   15276: Returns:
                   15277: 
                   15278: 1. suffix obtained (numeric)
                   15279: 
                   15280: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15281: 
                   15282: 3. error: contains (localized) error message if an error occurred.
                   15283: 
1.747     albertel 15284: 
1.608     albertel 15285: =back
                   15286: 
1.243     albertel 15287: =head2 HTTP Helper Routines
                   15288: 
                   15289: =over 4
                   15290: 
1.191     harris41 15291: =item *
                   15292: 
                   15293: escape() : unpack non-word characters into CGI-compatible hex codes
                   15294: 
                   15295: =item *
                   15296: 
                   15297: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15298: 
1.243     albertel 15299: =back
                   15300: 
                   15301: =head1 PRIVATE SUBROUTINES
                   15302: 
                   15303: =head2 Underlying communication routines (Shouldn't call)
                   15304: 
                   15305: =over 4
                   15306: 
                   15307: =item *
                   15308: 
                   15309: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15310: 
                   15311: =item *
                   15312: 
                   15313: reply() : uses subreply to send a message to remote machine, logs all failures
                   15314: 
                   15315: =item *
                   15316: 
                   15317: critical() : passes a critical message to another server; if cannot
                   15318: get through then place message in connection buffer directory and
                   15319: returns con_delayed, if incapable of saving message, returns
                   15320: con_failed
                   15321: 
                   15322: =item *
                   15323: 
                   15324: reconlonc() : tries to reconnect lonc client processes.
                   15325: 
                   15326: =back
                   15327: 
                   15328: =head2 Resource Access Logging
                   15329: 
                   15330: =over 4
                   15331: 
                   15332: =item *
                   15333: 
                   15334: flushcourselogs() : flush (save) buffer logs and access logs
                   15335: 
                   15336: =item *
                   15337: 
                   15338: courselog($what) : save message for course in hash
                   15339: 
                   15340: =item *
                   15341: 
                   15342: courseacclog($what) : save message for course using &courselog().  Perform
                   15343: special processing for specific resource types (problems, exams, quizzes, etc).
                   15344: 
1.191     harris41 15345: =item *
                   15346: 
                   15347: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15348: as a PerlChildExitHandler
1.243     albertel 15349: 
                   15350: =back
                   15351: 
                   15352: =head2 Other
                   15353: 
                   15354: =over 4
                   15355: 
                   15356: =item *
                   15357: 
                   15358: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15359: 
                   15360: =back
                   15361: 
                   15362: =cut
1.877     foxr     15363: 

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