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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1376  ! raeburn     4: # $Id: lonnet.pm,v 1.1375 2018/04/14 02:30:01 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.486     www        74: use HTTP::Date;
1.977     amueller   75: use Image::Magick;
                     76: 
1.1182    foxr       77: 
1.1173    foxr       78: use Encode;
                     79: 
1.1245    raeburn    80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     82:             %managerstab);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.1289    damieng    94: use Time::HiRes qw( sleep gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.807     albertel   99: use LONCAPA qw(:DEFAULT :match);
1.740     www       100: use LONCAPA::Configuration;
1.1160    www       101: use LONCAPA::lonmetadata;
1.1167    droeschl  102: use LONCAPA::Lond;
1.1345    raeburn   103: use LONCAPA::LWPReq;
1.1117    foxr      104: 
1.1090    raeburn   105: use File::Copy;
1.676     albertel  106: 
1.195     www       107: my $readit;
1.1288    damieng   108: my $max_connection_retries = 20;     # Or some such value.
1.1       albertel  109: 
1.619     albertel  110: require Exporter;
                    111: 
                    112: our @ISA = qw (Exporter);
                    113: our @EXPORT = qw(%env);
                    114: 
1.449     matthew   115: 
1.1187    raeburn   116: # ------------------------------------ Logging (parameters, docs, slots, roles)
1.729     www       117: {
                    118:     my $logid;
1.1187    raeburn   119:     sub write_log {
1.1188    raeburn   120: 	my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
1.1184    raeburn   121:         if ($context eq 'course') {
                    122:             if (($cnum eq '') || ($cdom eq '')) {
                    123:                 $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    124:                 $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    125:             }
1.957     raeburn   126:         }
1.1184    raeburn   127: 	$logid ++;
1.957     raeburn   128:         my $now = time();
                    129: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.1184    raeburn   130:         my $logentry = { 
                    131:                           $id => {
                    132:                                    'exe_uname' => $env{'user.name'},
                    133:                                    'exe_udom'  => $env{'user.domain'},
                    134:                                    'exe_time'  => $now,
                    135:                                    'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    136:                                    'delflag'   => $delflag,
                    137:                                    'logentry'  => $storehash,
                    138:                                    'uname'     => $uname,
                    139:                                    'udom'      => $udom,
                    140:                                   }
                    141:                        };
                    142: 	return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
1.729     www       143:     }
                    144: }
1.1       albertel  145: 
1.163     harris41  146: sub logtouch {
                    147:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  148:     unless (-e "$execdir/logs/lonnet.log") {	
1.1359    raeburn   149: 	open(my $fh,">>","$execdir/logs/lonnet.log");
1.163     harris41  150: 	close $fh;
                    151:     }
                    152:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    153:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    154: }
                    155: 
1.1       albertel  156: sub logthis {
                    157:     my $message=shift;
                    158:     my $execdir=$perlvar{'lonDaemons'};
                    159:     my $now=time;
                    160:     my $local=localtime($now);
1.1359    raeburn   161:     if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
1.986     foxr      162: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    163: 	print $fh $logstring;
1.448     albertel  164: 	close($fh);
                    165:     }
1.1       albertel  166:     return 1;
                    167: }
                    168: 
                    169: sub logperm {
                    170:     my $message=shift;
                    171:     my $execdir=$perlvar{'lonDaemons'};
                    172:     my $now=time;
                    173:     my $local=localtime($now);
1.1359    raeburn   174:     if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
1.448     albertel  175: 	print $fh "$now:$message:$local\n";
                    176: 	close($fh);
                    177:     }
1.1       albertel  178:     return 1;
                    179: }
                    180: 
1.850     albertel  181: sub create_connection {
1.853     albertel  182:     my ($hostname,$lonid) = @_;
1.851     albertel  183:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  184: 				     Type    => SOCK_STREAM,
                    185: 				     Timeout => 10);
                    186:     return 0 if (!$client);
1.890     albertel  187:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  188:     my $result = <$client>;
                    189:     chomp($result);
                    190:     return 1 if ($result eq 'done');
                    191:     return 0;
                    192: }
                    193: 
1.983     raeburn   194: sub get_server_timezone {
                    195:     my ($cnum,$cdom) = @_;
                    196:     my $home=&homeserver($cnum,$cdom);
                    197:     if ($home ne 'no_host') {
                    198:         my $cachetime = 24*3600;
                    199:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    200:         if (defined($cached)) {
                    201:             return $timezone;
                    202:         } else {
                    203:             my $timezone = &reply('servertimezone',$home);
                    204:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    205:         }
                    206:     }
                    207: }
1.850     albertel  208: 
1.1106    raeburn   209: sub get_server_distarch {
                    210:     my ($lonhost,$ignore_cache) = @_;
                    211:     if (defined($lonhost)) {
                    212:         if (!defined(&hostname($lonhost))) {
                    213:             return;
                    214:         }
                    215:         my $cachetime = 12*3600;
                    216:         if (!$ignore_cache) {
                    217:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    218:             if (defined($cached)) {
                    219:                 return $distarch;
                    220:             }
                    221:         }
                    222:         my $rep = &reply('serverdistarch',$lonhost);
                    223:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    224:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    225:                 $rep eq '') {
                    226:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    227:         }
                    228:     }
                    229:     return;
                    230: }
                    231: 
1.1315    raeburn   232: sub get_servercerts_info {
                    233:     my ($lonhost,$context) = @_;
                    234:     my ($rep,$uselocal);
                    235:     if (grep { $_ eq $lonhost } &current_machine_ids()) {
                    236:         $uselocal = 1;
                    237:     }
1.1316    raeburn   238:     if (($context ne 'cgi') && ($uselocal)) {
1.1315    raeburn   239:         my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
1.1323    raeburn   240:         if ($distro eq '') {
                    241:             $uselocal = 0;
                    242:         } elsif ($distro =~ /^(?:centos|redhat|scientific)(\d+)$/) {
1.1315    raeburn   243:             if ($1 < 6) {
                    244:                 $uselocal = 0;
                    245:             }
1.1346    raeburn   246:         }  elsif ($distro =~ /^(?:sles)(\d+)$/) {
                    247:             if ($1 < 12) {
                    248:                 $uselocal = 0;
                    249:             }
1.1315    raeburn   250:         }
                    251:     }
                    252:     if ($uselocal) {
                    253:         $rep = LONCAPA::Lond::server_certs(\%perlvar);
                    254:     } else {
                    255:         $rep=&reply('servercerts',$lonhost);
                    256:     }
                    257:     my ($result,%returnhash);
                    258:     if (defined($lonhost)) {
                    259:         if (!defined(&hostname($lonhost))) {
                    260:             return;
                    261:         }
                    262:     }
                    263:     if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    264:         ($rep eq 'unknown_cmd')) {
                    265:         $result = $rep;
                    266:     } else {
                    267:         $result = 'ok';
                    268:         my @pairs=split(/\&/,$rep);
                    269:         foreach my $item (@pairs) {
                    270:             my ($key,$value)=split(/=/,$item,2);
                    271:             my $what = &unescape($key);
                    272:             $returnhash{$what}=&thaw_unescape($value);
                    273:         }
                    274:     }
                    275:     return ($result,\%returnhash);
                    276: }
                    277: 
1.993     raeburn   278: sub get_server_loncaparev {
1.1073    raeburn   279:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   280:     if (defined($lonhost)) {
                    281:         if (!defined(&hostname($lonhost))) {
                    282:             undef($lonhost);
                    283:         }
                    284:     }
                    285:     if (!defined($lonhost)) {
                    286:         if (defined(&domain($dom,'primary'))) {
                    287:             $lonhost=&domain($dom,'primary');
                    288:             if ($lonhost eq 'no_host') {
                    289:                 undef($lonhost);
                    290:             }
                    291:         }
                    292:     }
                    293:     if (defined($lonhost)) {
1.1073    raeburn   294:         my $cachetime = 12*3600;
                    295:         if (!$ignore_cache) {
                    296:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    297:             if (defined($cached)) {
                    298:                 return $loncaparev;
                    299:             }
                    300:         }
                    301:         my ($answer,$loncaparev);
                    302:         my @ids=&current_machine_ids();
                    303:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    304:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   305:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   306:                 $loncaparev = $1;
                    307:             }
                    308:         } else {
                    309:             $answer = &reply('serverloncaparev',$lonhost);
                    310:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    311:                 if ($caller eq 'loncron') {
                    312:                     my $protocol = $protocol{$lonhost};
                    313:                     $protocol = 'http' if ($protocol ne 'https');
                    314:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    315:                     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn   316:                     my $response=&LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar,4,1);
1.1073    raeburn   317:                     unless ($response->is_error()) {
                    318:                         my $content = $response->content;
1.1081    raeburn   319:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   320:                             $loncaparev = $1;
                    321:                         }
                    322:                     }
                    323:                 } else {
                    324:                     $loncaparev = $loncaparevs{$lonhost};
                    325:                 }
1.1081    raeburn   326:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   327:                 $loncaparev = $1;
                    328:             }
1.993     raeburn   329:         }
1.1073    raeburn   330:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   331:     }
                    332: }
                    333: 
1.1074    raeburn   334: sub get_server_homeID {
                    335:     my ($hostname,$ignore_cache,$caller) = @_;
                    336:     unless ($ignore_cache) {
                    337:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    338:         if (defined($cached)) {
                    339:             return $serverhomeID;
                    340:         }
                    341:     }
                    342:     my $cachetime = 12*3600;
                    343:     my $serverhomeID;
                    344:     if ($caller eq 'loncron') { 
                    345:         my @machine_ids = &machine_ids($hostname);
                    346:         foreach my $id (@machine_ids) {
                    347:             my $response = &reply('serverhomeID',$id);
                    348:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    349:                 $serverhomeID = $response;
                    350:                 last;
                    351:             }
                    352:         }
                    353:         if ($serverhomeID eq '') {
                    354:             $serverhomeID = $machine_ids[-1];
                    355:         }
                    356:     } else {
                    357:         $serverhomeID = $serverhomeIDs{$hostname};
                    358:     }
                    359:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    360: }
                    361: 
1.1121    raeburn   362: sub get_remote_globals {
                    363:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   364:     my ($result,%returnhash,%whatneeded);
                    365:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   366:         foreach my $what (sort(keys(%{$whathash}))) {
                    367:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   368:             my ($response,$cached);
1.1121    raeburn   369:             unless ($ignore_cache) {
1.1125    raeburn   370:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   371:             }
                    372:             if (defined($cached)) {
1.1125    raeburn   373:                 $returnhash{$what} = $response;
1.1121    raeburn   374:             } else {
1.1125    raeburn   375:                 $whatneeded{$what} = 1;
1.1121    raeburn   376:             }
                    377:         }
1.1125    raeburn   378:         if (keys(%whatneeded) == 0) {
                    379:             $result = 'ok';
                    380:         } else {
1.1121    raeburn   381:             my $requested = &freeze_escape(\%whatneeded);
                    382:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   383:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    384:                 ($rep eq 'unknown_cmd')) {
                    385:                 $result = $rep;
                    386:             } else {
                    387:                 $result = 'ok';
1.1121    raeburn   388:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   389:                 foreach my $item (@pairs) {
                    390:                     my ($key,$value)=split(/=/,$item,2);
                    391:                     my $what = &unescape($key);
                    392:                     my $hashid = $lonhost.'-'.$what;
                    393:                     $returnhash{$what}=&thaw_unescape($value);
                    394:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   395:                 }
                    396:             }
                    397:         }
                    398:     }
1.1125    raeburn   399:     return ($result,\%returnhash);
1.1121    raeburn   400: }
                    401: 
1.1124    raeburn   402: sub remote_devalidate_cache {
1.1241    raeburn   403:     my ($lonhost,$cachekeys) = @_;
                    404:     my $items;
                    405:     return unless (ref($cachekeys) eq 'ARRAY');
                    406:     my $cachestr = join('&',@{$cachekeys});
                    407:     my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
1.1124    raeburn   408:     return $response;
                    409: }
                    410: 
1.1       albertel  411: # -------------------------------------------------- Non-critical communication
                    412: sub subreply {
                    413:     my ($cmd,$server)=@_;
1.838     albertel  414:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      415:     #
                    416:     #  With loncnew process trimming, there's a timing hole between lonc server
                    417:     #  process exit and the master server picking up the listen on the AF_UNIX
                    418:     #  socket.  In that time interval, a lock file will exist:
                    419: 
                    420:     my $lockfile=$peerfile.".lock";
                    421:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
1.1289    damieng   422: 	sleep(0.1);
1.549     foxr      423:     }
                    424:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      425:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      426:     #
1.550     foxr      427:     #   We'll give the connection a few tries before abandoning it.  If
                    428:     #   connection is not possible, we'll con_lost back to the client.
                    429:     #   
                    430:     my $client;
                    431:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    432: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    433: 				      Type    => SOCK_STREAM,
                    434: 				      Timeout => 10);
1.869     albertel  435: 	if ($client) {
1.550     foxr      436: 	    last;		# Connected!
1.850     albertel  437: 	} else {
1.853     albertel  438: 	    &create_connection(&hostname($server),$server);
1.550     foxr      439: 	}
1.1289    damieng   440:         sleep(0.1);	# Try again later if failed connection.
1.550     foxr      441:     }
                    442:     my $answer;
                    443:     if ($client) {
1.704     albertel  444: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      445: 	$answer=<$client>;
                    446: 	if (!$answer) { $answer="con_lost"; }
                    447: 	chomp($answer);
                    448:     } else {
                    449: 	$answer = 'con_lost';	# Failed connection.
                    450:     }
1.1       albertel  451:     return $answer;
                    452: }
                    453: 
                    454: sub reply {
                    455:     my ($cmd,$server)=@_;
1.838     albertel  456:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  457:     my $answer=subreply($cmd,$server);
1.65      www       458:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  459:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       460:                 " $cmd to $server returned $answer</font>");
                    461:     }
1.1       albertel  462:     return $answer;
                    463: }
                    464: 
                    465: # ----------------------------------------------------------- Send USR1 to lonc
                    466: 
                    467: sub reconlonc {
1.891     albertel  468:     my ($lonid) = @_;
                    469:     if ($lonid) {
1.1295    raeburn   470:         my $hostname = &hostname($lonid);
1.891     albertel  471: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    472: 	if ($hostname && -e $peerfile) {
                    473: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    474: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    475: 					     Type    => SOCK_STREAM,
                    476: 					     Timeout => 10);
                    477: 	    if ($client) {
                    478: 		print $client ("reset_retries\n");
                    479: 		my $answer=<$client>;
                    480: 		#reset just this one.
                    481: 	    }
                    482: 	}
                    483: 	return;
                    484:     }
                    485: 
1.836     www       486:     &logthis("Trying to reconnect lonc");
1.1       albertel  487:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.1359    raeburn   488:     if (open(my $fh,"<",$loncfile)) {
1.1       albertel  489: 	my $loncpid=<$fh>;
                    490:         chomp($loncpid);
                    491:         if (kill 0 => $loncpid) {
                    492: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    493:             kill USR1 => $loncpid;
                    494:             sleep 1;
1.1295    raeburn   495:         } else {
1.12      www       496: 	    &logthis(
1.672     albertel  497:                "<font color=\"blue\">WARNING:".
1.12      www       498:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  499:         }
                    500:     } else {
1.836     www       501: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  502:     }
                    503: }
                    504: 
                    505: # ------------------------------------------------------ Critical communication
1.12      www       506: 
1.1       albertel  507: sub critical {
                    508:     my ($cmd,$server)=@_;
1.838     albertel  509:     unless (&hostname($server)) {
1.672     albertel  510:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       511:                " Critical message to unknown server ($server)</font>");
                    512:         return 'no_such_host';
                    513:     }
1.1       albertel  514:     my $answer=reply($cmd,$server);
                    515:     if ($answer eq 'con_lost') {
1.1295    raeburn   516: 	&reconlonc($server);
1.589     albertel  517: 	my $answer=reply($cmd,$server);
1.1       albertel  518:         if ($answer eq 'con_lost') {
                    519:             my $now=time;
                    520:             my $middlename=$cmd;
1.5       www       521:             $middlename=substr($middlename,0,16);
1.1       albertel  522:             $middlename=~s/\W//g;
                    523:             my $dfilename=
1.305     www       524:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    525:             $dumpcount++;
1.1       albertel  526:             {
1.448     albertel  527: 		my $dfh;
1.1359    raeburn   528: 		if (open($dfh,">",$dfilename)) {
1.448     albertel  529: 		    print $dfh "$cmd\n"; 
                    530: 		    close($dfh);
                    531: 		}
1.1       albertel  532:             }
1.1288    damieng   533:             sleep 1;
1.1       albertel  534:             my $wcmd='';
                    535:             {
1.448     albertel  536: 		my $dfh;
1.1359    raeburn   537: 		if (open($dfh,"<",$dfilename)) {
1.448     albertel  538: 		    $wcmd=<$dfh>; 
                    539: 		    close($dfh);
                    540: 		}
1.1       albertel  541:             }
                    542:             chomp($wcmd);
1.7       www       543:             if ($wcmd eq $cmd) {
1.672     albertel  544: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       545:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  546:                 &logperm("D:$server:$cmd");
                    547: 	        return 'con_delayed';
                    548:             } else {
1.672     albertel  549:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       550:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  551:                 &logperm("F:$server:$cmd");
                    552:                 return 'con_failed';
                    553:             }
                    554:         }
                    555:     }
                    556:     return $answer;
1.405     albertel  557: }
                    558: 
1.755     albertel  559: # ------------------------------------------- check if return value is an error
                    560: 
                    561: sub error {
                    562:     my ($result) = @_;
1.756     albertel  563:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  564: 	if ($2 == 2) { return undef; }
                    565: 	return $1;
                    566:     }
                    567:     return undef;
                    568: }
                    569: 
1.783     albertel  570: sub convert_and_load_session_env {
                    571:     my ($lonidsdir,$handle)=@_;
                    572:     my @profile;
                    573:     {
1.917     albertel  574: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    575: 	if (!$opened) {
1.915     albertel  576: 	    return 0;
                    577: 	}
1.783     albertel  578: 	flock($idf,LOCK_SH);
                    579: 	@profile=<$idf>;
                    580: 	close($idf);
                    581:     }
                    582:     my %temp_env;
                    583:     foreach my $line (@profile) {
1.786     albertel  584: 	if ($line !~ m/=/) {
                    585: 	    return 0;
                    586: 	}
1.783     albertel  587: 	chomp($line);
                    588: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    589: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    590:     }
                    591:     unlink("$lonidsdir/$handle.id");
                    592:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    593: 	    0640)) {
                    594: 	%disk_env = %temp_env;
                    595: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    596: 	untie(%disk_env);
                    597:     }
1.786     albertel  598:     return 1;
1.783     albertel  599: }
                    600: 
1.374     www       601: # ------------------------------------------- Transfer profile into environment
1.780     albertel  602: my $env_loaded;
                    603: sub transfer_profile_to_env {
1.788     albertel  604:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    605:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       606: 
1.720     albertel  607:     if (!defined($lonidsdir)) {
                    608: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    609:     }
                    610:     if (!defined($handle)) {
                    611:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    612:     }
                    613: 
1.786     albertel  614:     my $convert;
                    615:     {
1.917     albertel  616:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    617: 	if (!$opened) {
1.915     albertel  618: 	    return;
                    619: 	}
1.786     albertel  620: 	flock($idf,LOCK_SH);
                    621: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    622: 		&GDBM_READER(),0640)) {
                    623: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    624: 	    untie(%disk_env);
                    625: 	} else {
                    626: 	    $convert = 1;
                    627: 	}
                    628:     }
                    629:     if ($convert) {
                    630: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    631: 	    &logthis("Failed to load session, or convert session.");
                    632: 	}
1.374     www       633:     }
1.783     albertel  634: 
1.786     albertel  635:     my %remove;
1.783     albertel  636:     while ( my $envname = each(%env) ) {
1.433     matthew   637:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    638:             if ($time < time-300) {
1.783     albertel  639:                 $remove{$key}++;
1.433     matthew   640:             }
                    641:         }
                    642:     }
1.783     albertel  643: 
1.619     albertel  644:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  645:     $env_loaded=1;
1.783     albertel  646:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   647:         &delenv($expired_key);
1.374     www       648:     }
1.1       albertel  649: }
                    650: 
1.916     albertel  651: # ---------------------------------------------------- Check for valid session 
                    652: sub check_for_valid_session {
1.1355    raeburn   653:     my ($r,$name,$userhashref,$domref) = @_;
1.916     albertel  654:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1337    raeburn   655:     my ($linkname,$pubname);
1.1155    raeburn   656:     if ($name eq '') {
                    657:         $name = 'lonID';
1.1337    raeburn   658:         $linkname = 'lonLinkID';
                    659:         $pubname = 'lonPubID';
1.1155    raeburn   660:     }
                    661:     my $lonid=$cookies{$name};
1.1337    raeburn   662:     if (!$lonid) {
                    663:         if (($name eq 'lonID') && ($ENV{'SERVER_PORT'} != 443) && ($linkname)) {
                    664:             $lonid=$cookies{$linkname};
                    665:         }
                    666:         if (!$lonid) {
                    667:             if (($name eq 'lonID') && ($pubname)) {
                    668:                 $lonid=$cookies{$pubname};
                    669:             }
                    670:         }
                    671:     }
1.916     albertel  672:     return undef if (!$lonid);
                    673: 
                    674:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   675:     my $lonidsdir;
                    676:     if ($name eq 'lonDAV') {
                    677:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    678:     } else {
                    679:         $lonidsdir=$r->dir_config('lonIDsDir');
                    680:     }
1.1355    raeburn   681:     if (!-e "$lonidsdir/$handle.id") {
                    682:         if ((ref($domref)) && ($name eq 'lonID') && 
                    683:             ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
                    684:             my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
                    685:             if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
                    686:                 $$domref = $possudom;
                    687:             }
                    688:         }
                    689:         return undef;
                    690:     }
1.916     albertel  691: 
1.917     albertel  692:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    693:     return undef if (!$opened);
1.916     albertel  694: 
                    695:     flock($idf,LOCK_SH);
                    696:     my %disk_env;
                    697:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    698: 	    &GDBM_READER(),0640)) {
                    699: 	return undef;	
                    700:     }
                    701: 
                    702:     if (!defined($disk_env{'user.name'})
                    703: 	|| !defined($disk_env{'user.domain'})) {
                    704: 	return undef;
                    705:     }
1.1245    raeburn   706: 
                    707:     if (ref($userhashref) eq 'HASH') {
                    708:         $userhashref->{'name'} = $disk_env{'user.name'};
                    709:         $userhashref->{'domain'} = $disk_env{'user.domain'};
1.1361    raeburn   710:         $userhashref->{'lti'} = $disk_env{'request.lti.login'};
1.1375    raeburn   711:         if ($userhashref->{'lti'}) {
                    712:             $userhashref->{'ltitarget'} = $disk_env{'request.lti.target'};
                    713:             $userhashref->{'ltiuri'} = $disk_env{'request.lti.uri'};
                    714:         }
1.1212    raeburn   715:     }
1.1245    raeburn   716: 
1.916     albertel  717:     return $handle;
                    718: }
                    719: 
1.830     albertel  720: sub timed_flock {
                    721:     my ($file,$lock_type) = @_;
                    722:     my $failed=0;
                    723:     eval {
                    724: 	local $SIG{__DIE__}='DEFAULT';
                    725: 	local $SIG{ALRM}=sub {
                    726: 	    $failed=1;
                    727: 	    die("failed lock");
                    728: 	};
                    729: 	alarm(13);
                    730: 	flock($file,$lock_type);
                    731: 	alarm(0);
                    732:     };
                    733:     if ($failed) {
                    734: 	return undef;
                    735:     } else {
                    736: 	return 1;
                    737:     }
                    738: }
                    739: 
1.5       www       740: # ---------------------------------------------------------- Append Environment
                    741: 
                    742: sub appenv {
1.949     raeburn   743:     my ($newenv,$roles) = @_;
                    744:     if (ref($newenv) eq 'HASH') {
                    745:         foreach my $key (keys(%{$newenv})) {
                    746:             my $refused = 0;
                    747: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    748:                 $refused = 1;
                    749:                 if (ref($roles) eq 'ARRAY') {
1.1250    raeburn   750:                     my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
1.949     raeburn   751:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    752:                         $refused = 0;
                    753:                     }
                    754:                 }
                    755:             }
                    756:             if ($refused) {
                    757:                 &logthis("<font color=\"blue\">WARNING: ".
                    758:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    759:                          .'</font>');
                    760: 	        delete($newenv->{$key});
                    761:             } else {
                    762:                 $env{$key}=$newenv->{$key};
                    763:             }
                    764:         }
1.1376  ! raeburn   765:         my $lonids = $perlvar{'lonIDsDir'};
        !           766:         if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
        !           767:             my $opened = open(my $env_file,'+<',$env{'user.environment'});
        !           768:             if ($opened
        !           769: 	        && &timed_flock($env_file,LOCK_EX)
        !           770: 	        &&
        !           771: 	        tie(my %disk_env,'GDBM_File',$env{'user.environment'},
        !           772: 	            (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
        !           773: 	        while (my ($key,$value) = each(%{$newenv})) {
        !           774: 	            $disk_env{$key} = $value;
        !           775: 	        }
        !           776: 	        untie(%disk_env);
        !           777:             }
1.35      www       778:         }
1.191     harris41  779:     }
1.56      www       780:     return 'ok';
                    781: }
                    782: # ----------------------------------------------------- Delete from Environment
                    783: 
                    784: sub delenv {
1.1104    raeburn   785:     my ($delthis,$regexp,$roles) = @_;
                    786:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    787:         my $refused = 1;
                    788:         if (ref($roles) eq 'ARRAY') {
                    789:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    790:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    791:                 $refused = 0;
                    792:             }
                    793:         }
                    794:         if ($refused) {
                    795:             &logthis("<font color=\"blue\">WARNING: ".
                    796:                      "Attempt to delete from environment ".$delthis);
                    797:             return 'error';
                    798:         }
1.56      www       799:     }
1.917     albertel  800:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    801:     if ($opened
1.915     albertel  802: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  803: 	&&
                    804: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    805: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  806: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   807: 	    if ($regexp) {
                    808:                 if ($key=~/^$delthis/) {
                    809:                     delete($env{$key});
                    810:                     delete($disk_env{$key});
                    811:                 } 
                    812:             } else {
                    813:                 if ($key=~/^\Q$delthis\E/) {
                    814: 		    delete($env{$key});
                    815: 		    delete($disk_env{$key});
                    816: 	        }
                    817:             }
1.448     albertel  818: 	}
1.783     albertel  819: 	untie(%disk_env);
1.5       www       820:     }
                    821:     return 'ok';
1.369     albertel  822: }
                    823: 
1.790     albertel  824: sub get_env_multiple {
                    825:     my ($name) = @_;
                    826:     my @values;
                    827:     if (defined($env{$name})) {
                    828:         # exists is it an array
                    829:         if (ref($env{$name})) {
                    830:             @values=@{ $env{$name} };
                    831:         } else {
                    832:             $values[0]=$env{$name};
                    833:         }
                    834:     }
                    835:     return(@values);
                    836: }
                    837: 
1.958     www       838: # ------------------------------------------------------------------- Locking
                    839: 
                    840: sub set_lock {
                    841:     my ($text)=@_;
                    842:     $locknum++;
                    843:     my $id=$$.'-'.$locknum;
                    844:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    845:              'session.lock.'.$id => $text});
                    846:     return $id;
                    847: }
                    848: 
                    849: sub get_locks {
                    850:     my $num=0;
                    851:     my %texts=();
                    852:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    853:        if ($lock=~/\w/) {
                    854:           $num++;
                    855:           $texts{$lock}=$env{'session.lock.'.$lock};
                    856:        }
                    857:    }
                    858:    return ($num,%texts);
                    859: }
                    860: 
                    861: sub remove_lock {
                    862:     my ($id)=@_;
                    863:     my $newlocks='';
                    864:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    865:        if (($lock=~/\w/) && ($lock ne $id)) {
                    866:           $newlocks.=','.$lock;
                    867:        }
                    868:     }
                    869:     &appenv({'session.locks' => $newlocks});
                    870:     &delenv('session.lock.'.$id);
                    871: }
                    872: 
                    873: sub remove_all_locks {
                    874:     my $activelocks=$env{'session.locks'};
                    875:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    876:        if ($lock=~/\w/) {
                    877:           &remove_lock($lock);
                    878:        }
                    879:     }
                    880: }
                    881: 
                    882: 
1.369     albertel  883: # ------------------------------------------ Find out current server userload
                    884: sub userload {
                    885:     my $numusers=0;
                    886:     {
                    887: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    888: 	my $filename;
                    889: 	my $curtime=time;
                    890: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  891: 	    next if ($filename eq '.' || $filename eq '..');
                    892: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  893: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  894: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  895: 	}
                    896: 	closedir(LONIDS);
                    897:     }
                    898:     my $userloadpercent=0;
                    899:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    900:     if ($maxuserload) {
1.371     albertel  901: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  902:     }
1.372     albertel  903:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  904:     return $userloadpercent;
1.283     www       905: }
                    906: 
1.1       albertel  907: # ------------------------------ Find server with least workload from spare.tab
1.11      www       908: 
1.1       albertel  909: sub spareserver {
1.1083    raeburn   910:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  911:     my $spare_server;
1.370     albertel  912:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  913:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    914:                                                      :  $userloadpercent;
1.1083    raeburn   915:     my ($uint_dom,$remotesessions);
                    916:     if (($udom ne '') && (&domain($udom) ne '')) {
                    917:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    918:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    919:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    920:         $remotesessions = $udomdefaults{'remotesessions'};
                    921:     }
1.1123    raeburn   922:     my $spareshash = &this_host_spares($udom);
                    923:     if (ref($spareshash) eq 'HASH') {
                    924:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    925:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   926:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    927:                                              $try_server));
1.1123    raeburn   928: 	        ($spare_server, $lowest_load) =
                    929: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    930:             }
1.1083    raeburn   931:         }
1.784     albertel  932: 
1.1123    raeburn   933:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    934: 
                    935:         if (!$found_server) {
                    936:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    937: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   938:                     next unless (&spare_can_host($udom,$uint_dom,
                    939:                                                  $remotesessions,$try_server));
1.1123    raeburn   940: 	            ($spare_server, $lowest_load) =
                    941: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    942:                 }
                    943: 	    }
                    944:         }
1.784     albertel  945:     }
                    946: 
                    947:     if (!$want_server_name) {
1.968     raeburn   948:         my $protocol = 'http';
                    949:         if ($protocol{$spare_server} eq 'https') {
                    950:             $protocol = $protocol{$spare_server};
                    951:         }
1.1001    raeburn   952:         if (defined($spare_server)) {
                    953:             my $hostname = &hostname($spare_server);
1.1083    raeburn   954:             if (defined($hostname)) {
1.1001    raeburn   955: 	        $spare_server = $protocol.'://'.$hostname;
                    956:             }
                    957:         }
1.784     albertel  958:     }
                    959:     return $spare_server;
                    960: }
                    961: 
                    962: sub compare_server_load {
1.1253    raeburn   963:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    964: 
                    965:     if ($required) {
                    966:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    967:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    968:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    969:         if (($major eq '' && $minor eq '') ||
                    970:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    971:             return ($spare_server,$lowest_load);
                    972:         }
                    973:     }
1.784     albertel  974: 
                    975:     my $loadans     = &reply('load',    $try_server);
                    976:     my $userloadans = &reply('userload',$try_server);
                    977: 
                    978:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   979: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  980:     }
                    981: 
                    982:     my $load;
                    983:     if ($loadans =~ /\d/) {
                    984: 	if ($userloadans =~ /\d/) {
                    985: 	    #both are numbers, pick the bigger one
                    986: 	    $load = ($loadans > $userloadans) ? $loadans 
                    987: 		                              : $userloadans;
1.411     albertel  988: 	} else {
1.784     albertel  989: 	    $load = $loadans;
1.411     albertel  990: 	}
1.784     albertel  991:     } else {
                    992: 	$load = $userloadans;
                    993:     }
                    994: 
                    995:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    996: 	$spare_server = $try_server;
                    997: 	$lowest_load  = $load;
1.370     albertel  998:     }
1.784     albertel  999:     return ($spare_server,$lowest_load);
1.202     matthew  1000: }
1.914     albertel 1001: 
                   1002: # --------------------------- ask offload servers if user already has a session
                   1003: sub find_existing_session {
                   1004:     my ($udom,$uname) = @_;
1.1123    raeburn  1005:     my $spareshash = &this_host_spares($udom);
                   1006:     if (ref($spareshash) eq 'HASH') {
                   1007:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1008:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1009:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1010:             }
                   1011:         }
                   1012:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1013:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1014:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1015:             }
                   1016:         }
1.914     albertel 1017:     }
                   1018:     return;
                   1019: }
                   1020: 
                   1021: # -------------------------------- ask if server already has a session for user
                   1022: sub has_user_session {
                   1023:     my ($lonid,$udom,$uname) = @_;
                   1024:     my $result = &reply(join(':','userhassession',
                   1025: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1026:     return 1 if ($result eq 'ok');
                   1027: 
                   1028:     return 0;
                   1029: }
                   1030: 
1.1076    raeburn  1031: # --------- determine least loaded server in a user's domain which allows login
                   1032: 
                   1033: sub choose_server {
1.1259    raeburn  1034:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1035:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1036:     my %servers = &get_servers($udom);
1.1076    raeburn  1037:     my $lowest_load = 30000;
1.1259    raeburn  1038:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1039:     if ($skiploadbal) {
                   1040:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1041:         unless (defined($cached)) {
                   1042:             my $cachetime = 60*60*24;
                   1043:             my %domconfig =
                   1044:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1045:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1046:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1047:                                            $cachetime);
                   1048:             }
                   1049:         }
                   1050:     }
1.1076    raeburn  1051:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1052:         if ($skiploadbal) {
                   1053:             if (ref($balancers) eq 'HASH') {
                   1054:                 next if (exists($balancers->{$lonhost}));
                   1055:             }
                   1056:         }   
1.1115    raeburn  1057:         my $loginvia;
                   1058:         if ($checkloginvia) {
                   1059:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1060:             if ($loginvia) {
                   1061:                 my ($server,$path) = split(/:/,$loginvia);
                   1062:                 ($login_host, $lowest_load) =
1.1253    raeburn  1063:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1064:                 if ($login_host eq $server) {
                   1065:                     $portal_path = $path;
1.1151    raeburn  1066:                     $isredirect = 1;
1.1116    raeburn  1067:                 }
                   1068:             } else {
                   1069:                 ($login_host, $lowest_load) =
1.1253    raeburn  1070:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1071:                 if ($login_host eq $lonhost) {
                   1072:                     $portal_path = '';
1.1151    raeburn  1073:                     $isredirect = ''; 
1.1116    raeburn  1074:                 }
                   1075:             }
                   1076:         } else {
1.1076    raeburn  1077:             ($login_host, $lowest_load) =
1.1253    raeburn  1078:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1079:         }
                   1080:     }
                   1081:     if ($login_host ne '') {
1.1116    raeburn  1082:         $hostname = &hostname($login_host);
1.1076    raeburn  1083:     }
1.1331    raeburn  1084:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1085: }
                   1086: 
1.202     matthew  1087: # --------------------------------------------- Try to change a user's password
                   1088: 
                   1089: sub changepass {
1.799     raeburn  1090:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1091:     $currentpass = &escape($currentpass);
                   1092:     $newpass     = &escape($newpass);
1.1030    raeburn  1093:     my $lonhost = $perlvar{'lonHostID'};
                   1094:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1095: 		       $server);
                   1096:     if (! $answer) {
                   1097: 	&logthis("No reply on password change request to $server ".
                   1098: 		 "by $uname in domain $udom.");
                   1099:     } elsif ($answer =~ "^ok") {
                   1100:         &logthis("$uname in $udom successfully changed their password ".
                   1101: 		 "on $server.");
                   1102:     } elsif ($answer =~ "^pwchange_failure") {
                   1103: 	&logthis("$uname in $udom was unable to change their password ".
                   1104: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1105: 		 "or pwchange");
                   1106:     } elsif ($answer =~ "^non_authorized") {
                   1107:         &logthis("$uname in $udom did not get their password correct when ".
                   1108: 		 "attempting to change it on $server.");
                   1109:     } elsif ($answer =~ "^auth_mode_error") {
                   1110:         &logthis("$uname in $udom attempted to change their password despite ".
                   1111: 		 "not being locally or internally authenticated on $server.");
                   1112:     } elsif ($answer =~ "^unknown_user") {
                   1113:         &logthis("$uname in $udom attempted to change their password ".
                   1114: 		 "on $server but were unable to because $server is not ".
                   1115: 		 "their home server.");
                   1116:     } elsif ($answer =~ "^refused") {
                   1117: 	&logthis("$server refused to change $uname in $udom password because ".
                   1118: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1119:     } elsif ($answer =~ "invalid_client") {
                   1120:         &logthis("$server refused to change $uname in $udom password because ".
                   1121:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1122:     }
                   1123:     return $answer;
1.1       albertel 1124: }
                   1125: 
1.169     harris41 1126: # ----------------------- Try to determine user's current authentication scheme
                   1127: 
                   1128: sub queryauthenticate {
                   1129:     my ($uname,$udom)=@_;
1.456     albertel 1130:     my $uhome=&homeserver($uname,$udom);
                   1131:     if (!$uhome) {
                   1132: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1133: 	return 'no_host';
                   1134:     }
                   1135:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1136:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1137: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1138:     }
1.456     albertel 1139:     return $answer;
1.169     harris41 1140: }
                   1141: 
1.1       albertel 1142: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1143: 
1.1       albertel 1144: sub authenticate {
1.1073    raeburn  1145:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1146:     $upass=&escape($upass);
                   1147:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1148:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1149:     my $newhome;
1.836     www      1150:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1151: # Maybe the machine was offline and only re-appeared again recently?
                   1152:         &reconlonc();
                   1153: # One more
1.952     raeburn  1154: 	$uhome=&homeserver($uname,$udom,1);
                   1155:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1156:             if (defined(&domain($udom,'primary'))) {
                   1157:                 $newhome=&domain($udom,'primary');
                   1158:             }
                   1159:             if ($newhome ne '') {
                   1160:                 $uhome = $newhome;
                   1161:             }
                   1162:         }
1.836     www      1163: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1164: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1165: 	    return 'no_host';
                   1166:         }
1.1       albertel 1167:     }
1.1073    raeburn  1168:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1169:     if ($answer eq 'authorized') {
1.952     raeburn  1170:         if ($newhome) {
                   1171:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1172:             return 'no_account_on_host'; 
                   1173:         } else {
                   1174:             &logthis("User $uname at $udom authorized by $uhome");
                   1175:             return $uhome;
                   1176:         }
1.471     albertel 1177:     }
                   1178:     if ($answer eq 'non_authorized') {
                   1179: 	&logthis("User $uname at $udom rejected by $uhome");
                   1180: 	return 'no_host'; 
1.9       www      1181:     }
1.471     albertel 1182:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1183:     return 'no_host';
                   1184: }
                   1185: 
1.1073    raeburn  1186: sub can_host_session {
1.1074    raeburn  1187:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1188:     my $canhost = 1;
1.1074    raeburn  1189:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1190:     if (ref($remotesessions) eq 'HASH') {
                   1191:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1192:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1193:                 $canhost = 0;
                   1194:             } else {
                   1195:                 $canhost = 1;
                   1196:             }
                   1197:         }
                   1198:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1199:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1200:                 $canhost = 1;
                   1201:             } else {
                   1202:                 $canhost = 0;
                   1203:             }
                   1204:         }
                   1205:         if ($canhost) {
                   1206:             if ($remotesessions->{'version'} ne '') {
                   1207:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1208:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1209:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1210:                         my $major = $1;
                   1211:                         my $minor = $2;
                   1212:                         if (($major < $reqmajor ) ||
                   1213:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1214:                             $canhost = 0;
                   1215:                         }
                   1216:                     } else {
                   1217:                         $canhost = 0;
                   1218:                     }
                   1219:                 }
                   1220:             }
                   1221:         }
                   1222:     }
                   1223:     if ($canhost) {
                   1224:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1225:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1226:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1227:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1228:                 if (($uint_dom ne '') && 
                   1229:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1230:                     $canhost = 0;
                   1231:                 } else {
                   1232:                     $canhost = 1;
                   1233:                 }
                   1234:             }
                   1235:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1236:                 if (($uint_dom ne '') && 
                   1237:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1238:                     $canhost = 1;
                   1239:                 } else {
                   1240:                     $canhost = 0;
                   1241:                 }
                   1242:             }
                   1243:         }
                   1244:     }
                   1245:     return $canhost;
                   1246: }
                   1247: 
1.1083    raeburn  1248: sub spare_can_host {
                   1249:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1250:     my $canhost=1;
1.1279    raeburn  1251:     my $try_server_hostname = &hostname($try_server);
                   1252:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1253:     my $serverhomedom = &host_domain($serverhomeID);
                   1254:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1255:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1256:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1257:             $canhost = 0;
                   1258:         }
                   1259:     }
                   1260:     if (($canhost) && ($uint_dom)) {
                   1261:         my @intdoms;
                   1262:         my $internet_names = &get_internet_names($try_server);
                   1263:         if (ref($internet_names) eq 'ARRAY') {
                   1264:             @intdoms = @{$internet_names};
                   1265:         }
                   1266:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1267:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1268:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1269:                                          $remotesessions,
                   1270:                                          $defdomdefaults{'hostedsessions'});
                   1271:         }
1.1083    raeburn  1272:     }
                   1273:     return $canhost;
                   1274: }
                   1275: 
1.1123    raeburn  1276: sub this_host_spares {
                   1277:     my ($dom) = @_;
1.1126    raeburn  1278:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1279:     my @hosts = &current_machine_ids();
                   1280:     foreach my $lonhost (@hosts) {
                   1281:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1282:             $dom_in_use = $dom;
                   1283:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1284:             last;
                   1285:         }
                   1286:     }
1.1126    raeburn  1287:     if ($dom_in_use ne '') {
                   1288:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1289:     }
                   1290:     if (ref($result) ne 'HASH') {
                   1291:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1292:         $dom_in_use = &host_domain($lonhost_in_use);
                   1293:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1294:         if (ref($result) ne 'HASH') {
                   1295:             $result = \%spareid;
                   1296:         }
                   1297:     }
                   1298:     return $result;
                   1299: }
                   1300: 
                   1301: sub spares_for_offload  {
                   1302:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1303:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1304:     if (defined($cached)) {
                   1305:         return $result;
                   1306:     } else {
1.1126    raeburn  1307:         my $cachetime = 60*60*24;
                   1308:         my %domconfig =
                   1309:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1310:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1311:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1312:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1313:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1314:                 }
                   1315:             }
                   1316:         }
                   1317:     }
1.1126    raeburn  1318:     return;
1.1123    raeburn  1319: }
                   1320: 
1.1129    raeburn  1321: sub get_lonbalancer_config {
                   1322:     my ($servers) = @_;
                   1323:     my ($currbalancer,$currtargets);
                   1324:     if (ref($servers) eq 'HASH') {
                   1325:         foreach my $server (keys(%{$servers})) {
                   1326:             my %what = (
                   1327:                          spareid => 1,
                   1328:                          perlvar => 1,
                   1329:                        );
                   1330:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1331:             if ($result eq 'ok') {
                   1332:                 if (ref($returnhash) eq 'HASH') {
                   1333:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1334:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1335:                             $currbalancer = $server;
                   1336:                             $currtargets = {};
                   1337:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1338:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1339:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1340:                                 }
                   1341:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1342:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1343:                                 }
                   1344:                             }
                   1345:                             last;
                   1346:                         }
                   1347:                     }
                   1348:                 }
                   1349:             }
                   1350:         }
                   1351:     }
                   1352:     return ($currbalancer,$currtargets);
                   1353: }
                   1354: 
                   1355: sub check_loadbalancing {
1.1331    raeburn  1356:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1357:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1358:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1359:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1360:     my @hosts = &current_machine_ids();
1.1129    raeburn  1361:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1362:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1363:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1364:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1365:     my $domneedscache;
1.1129    raeburn  1366:     my $cachetime = 60*60*24;
                   1367: 
                   1368:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1369:         $dom_in_use = $udom;
                   1370:         $homeintdom = 1;
                   1371:     } else {
                   1372:         $dom_in_use = $serverhomedom;
                   1373:     }
                   1374:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1375:     unless (defined($cached)) {
                   1376:         my %domconfig =
                   1377:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1378:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1379:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1380:         } else {
                   1381:             $domneedscache = $dom_in_use;
1.1129    raeburn  1382:         }
                   1383:     }
                   1384:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1385:         ($is_balancer,$currtargets,$currrules) = 
                   1386:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1387:         if ($is_balancer) {
                   1388:             if (ref($currrules) eq 'HASH') {
                   1389:                 if ($homeintdom) {
                   1390:                     if ($uname ne '') {
                   1391:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1392:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1393:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1394:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1395:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1396:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1397:                             }
                   1398:                         }
                   1399:                         if ($rule_in_effect eq '') {
                   1400:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1401:                             if ($userenv{'inststatus'} ne '') {
                   1402:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1403:                                 my ($othertitle,$usertypes,$types) =
                   1404:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1405:                                 if (ref($types) eq 'ARRAY') {
                   1406:                                     foreach my $type (@{$types}) {
                   1407:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1408:                                             if (exists($currrules->{$type})) {
                   1409:                                                 $rule_in_effect = $currrules->{$type};
                   1410:                                             }
                   1411:                                         }
                   1412:                                     }
                   1413:                                 }
                   1414:                             } else {
                   1415:                                 if (exists($currrules->{'default'})) {
                   1416:                                     $rule_in_effect = $currrules->{'default'};
                   1417:                                 }
                   1418:                             }
                   1419:                         }
                   1420:                     } else {
                   1421:                         if (exists($currrules->{'default'})) {
                   1422:                             $rule_in_effect = $currrules->{'default'};
                   1423:                         }
                   1424:                     }
                   1425:                 } else {
                   1426:                     if ($currrules->{'_LC_external'} ne '') {
                   1427:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1428:                     }
                   1429:                 }
                   1430:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1431:                                                        $uname,$udom);
                   1432:             }
                   1433:         }
                   1434:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1435:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1436:         unless (defined($cached)) {
                   1437:             my %domconfig =
                   1438:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1439:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1440:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1441:             } else {
                   1442:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1443:             }
                   1444:         }
                   1445:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1446:             ($is_balancer,$currtargets,$currrules) = 
                   1447:                 &check_balancer_result($result,@hosts);
                   1448:             if ($is_balancer) {
1.1129    raeburn  1449:                 if (ref($currrules) eq 'HASH') {
                   1450:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1451:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1452:                     }
                   1453:                 }
                   1454:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1455:                                                        $uname,$udom);
                   1456:             }
                   1457:         } else {
                   1458:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1459:                 $is_balancer = 1;
                   1460:                 $offloadto = &this_host_spares($dom_in_use);
                   1461:             }
1.1307    raeburn  1462:             unless (defined($cached)) {
                   1463:                 $domneedscache = $serverhomedom;
                   1464:             }
1.1129    raeburn  1465:         }
                   1466:     } else {
                   1467:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1468:             $is_balancer = 1;
                   1469:             $offloadto = &this_host_spares($dom_in_use);
                   1470:         }
1.1307    raeburn  1471:         unless (defined($cached)) {
                   1472:             $domneedscache = $serverhomedom;
                   1473:         }
                   1474:     }
                   1475:     if ($domneedscache) {
                   1476:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1477:     }
1.1176    raeburn  1478:     if ($is_balancer) {
                   1479:         my $lowest_load = 30000;
                   1480:         if (ref($offloadto) eq 'HASH') {
                   1481:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1482:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1483:                     ($otherserver,$lowest_load) =
                   1484:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1485:                 }
1.1129    raeburn  1486:             }
1.1176    raeburn  1487:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1488: 
1.1176    raeburn  1489:             if (!$found_server) {
                   1490:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1491:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1492:                         ($otherserver,$lowest_load) =
                   1493:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1494:                     }
                   1495:                 }
                   1496:             }
                   1497:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1498:             if (@{$offloadto} == 1) {
                   1499:                 $otherserver = $offloadto->[0];
                   1500:             } elsif (@{$offloadto} > 1) {
                   1501:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1502:                     ($otherserver,$lowest_load) =
                   1503:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1504:                 }
                   1505:             }
                   1506:         }
1.1331    raeburn  1507:         unless ($caller eq 'login') {
                   1508:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1509:                 $is_balancer = 0;
                   1510:                 if ($uname ne '' && $udom ne '') {
                   1511:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1512:                     
1.1331    raeburn  1513:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1514:                                  'user.loadbalcheck.time' => time});
                   1515:                     }
1.1176    raeburn  1516:                 }
1.1129    raeburn  1517:             }
                   1518:         }
                   1519:     }
                   1520:     return ($is_balancer,$otherserver);
                   1521: }
                   1522: 
1.1191    raeburn  1523: sub check_balancer_result {
                   1524:     my ($result,@hosts) = @_;
                   1525:     my ($is_balancer,$currtargets,$currrules);
                   1526:     if (ref($result) eq 'HASH') {
                   1527:         if ($result->{'lonhost'} ne '') {
                   1528:             my $currbalancer = $result->{'lonhost'};
                   1529:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1530:                 $is_balancer = 1;
                   1531:                 $currtargets = $result->{'targets'};
                   1532:                 $currrules = $result->{'rules'};
                   1533:             }
                   1534:         } else {
                   1535:             foreach my $key (keys(%{$result})) {
                   1536:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1537:                     (ref($result->{$key}) eq 'HASH')) {
                   1538:                     $is_balancer = 1;
                   1539:                     $currrules = $result->{$key}{'rules'};
                   1540:                     $currtargets = $result->{$key}{'targets'};
                   1541:                     last;
                   1542:                 }
                   1543:             }
                   1544:         }
                   1545:     }
                   1546:     return ($is_balancer,$currtargets,$currrules);
                   1547: }
                   1548: 
1.1129    raeburn  1549: sub get_loadbalancer_targets {
                   1550:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1551:     my $offloadto;
1.1175    raeburn  1552:     if ($rule_in_effect eq 'none') {
                   1553:         return [$perlvar{'lonHostID'}];
                   1554:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1555:         $offloadto = $currtargets;
                   1556:     } else {
                   1557:         if ($rule_in_effect eq 'homeserver') {
                   1558:             my $homeserver = &homeserver($uname,$udom);
                   1559:             if ($homeserver ne 'no_host') {
                   1560:                 $offloadto = [$homeserver];
                   1561:             }
                   1562:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1563:             my %domconfig =
                   1564:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1565:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1566:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1567:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1568:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1569:                     }
                   1570:                 }
                   1571:             } else {
1.1178    raeburn  1572:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1573:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1574:                 if (&hostname($remotebalancer) ne '') {
                   1575:                     $offloadto = [$remotebalancer];
                   1576:                 }
                   1577:             }
                   1578:         } elsif (&hostname($rule_in_effect) ne '') {
                   1579:             $offloadto = [$rule_in_effect];
                   1580:         }
                   1581:     }
                   1582:     return $offloadto;
                   1583: }
                   1584: 
1.1127    raeburn  1585: sub internet_dom_servers {
                   1586:     my ($dom) = @_;
                   1587:     my (%uniqservers,%servers);
                   1588:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1589:     my @machinedoms = &machine_domains($primaryserver);
                   1590:     foreach my $mdom (@machinedoms) {
                   1591:         my %currservers = %servers;
                   1592:         my %server = &get_servers($mdom);
                   1593:         %servers = (%currservers,%server);
                   1594:     }
                   1595:     my %by_hostname;
                   1596:     foreach my $id (keys(%servers)) {
                   1597:         push(@{$by_hostname{$servers{$id}}},$id);
                   1598:     }
                   1599:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1600:         if (@{$by_hostname{$hostname}} > 1) {
                   1601:             my $match = 0;
                   1602:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1603:                 if (&host_domain($id) eq $dom) {
                   1604:                     $uniqservers{$id} = $hostname;
                   1605:                     $match = 1;
                   1606:                 }
                   1607:             }
                   1608:             unless ($match) {
                   1609:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1610:             }
                   1611:         } else {
                   1612:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1613:         }
                   1614:     }
                   1615:     return %uniqservers;
                   1616: }
                   1617: 
1.1347    raeburn  1618: sub trusted_domains {
                   1619:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1620:     my ($trusted,$untrusted);
1.1347    raeburn  1621:     if (&domain($calldom) eq '') {
1.1349    raeburn  1622:         return ($trusted,$untrusted);
1.1347    raeburn  1623:     }
                   1624:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1625:         return ($trusted,$untrusted);
1.1347    raeburn  1626:     }
                   1627:     my $callprimary = &domain($calldom,'primary');
                   1628:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1629:     if ($intcalldom eq '') {
1.1349    raeburn  1630:         return ($trusted,$untrusted);
1.1347    raeburn  1631:     }
                   1632: 
                   1633:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1634:     unless (defined($cached)) {
                   1635:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1636:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1637:         $trustconfig = $domconfig{'trust'};
                   1638:     }
                   1639:     if (ref($trustconfig)) {
                   1640:         my (%possexc,%possinc,@allexc,@allinc); 
                   1641:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1642:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1643:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1644:             }
                   1645:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1646:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1647:             }
                   1648:         }
                   1649:         if (keys(%possexc)) {
                   1650:             if (keys(%possinc)) {
                   1651:                 foreach my $key (sort(keys(%possexc))) {
                   1652:                     next if ($key eq $intcalldom);
                   1653:                     unless ($possinc{$key}) {
                   1654:                         push(@allexc,$key);
                   1655:                     }
                   1656:                 }
                   1657:             } else {
                   1658:                 @allexc = sort(keys(%possexc));
                   1659:             }
                   1660:         }
                   1661:         if (keys(%possinc)) {
                   1662:             $possinc{$intcalldom} = 1;
                   1663:             @allinc = sort(keys(%possinc));
                   1664:         }
                   1665:         if ((@allexc > 0) || (@allinc > 0)) {
                   1666:             my %doms_by_intdom;
                   1667:             my %allintdoms = &all_host_intdom();
                   1668:             my %alldoms = &all_host_domain();
                   1669:             foreach my $key (%allintdoms) {
                   1670:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1671:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1672:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1673:                     }
                   1674:                 } else {
                   1675:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1676:                 }
                   1677:             }
                   1678:             foreach my $exc (@allexc) {
                   1679:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1680:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1681:                 }
                   1682:             }
                   1683:             foreach my $inc (@allinc) {
                   1684:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1685:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1686:                 }
                   1687:             }
                   1688:         }
                   1689:     }
1.1349    raeburn  1690:     return ($trusted,$untrusted);
1.1347    raeburn  1691: }
                   1692: 
                   1693: sub will_trust {
                   1694:     my ($cmdtype,$domain,$possdom) = @_;
                   1695:     return 1 if ($domain eq $possdom);
                   1696:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1697:     my $willtrust; 
                   1698:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1699:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1700:             $willtrust = 1;
                   1701:         }
                   1702:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1703:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1704:             $willtrust = 1;
                   1705:         }
                   1706:     } else {
                   1707:         $willtrust = 1;
                   1708:     }
                   1709:     return $willtrust;
                   1710: }
                   1711: 
1.1       albertel 1712: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1713: 
1.599     albertel 1714: my %homecache;
1.1       albertel 1715: sub homeserver {
1.230     stredwic 1716:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1717:     my $index="$uname:$udom";
1.426     albertel 1718: 
1.599     albertel 1719:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1720: 
                   1721:     my %servers = &get_servers($udom,'library');
                   1722:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1723:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1724: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1725: 
                   1726: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1727: 	if ($answer eq 'found') {
                   1728: 	    delete($badServerCache{$tryserver}); 
                   1729: 	    return $homecache{$index}=$tryserver;
                   1730: 	} elsif ($answer eq 'no_host') {
                   1731: 	    $badServerCache{$tryserver}=1;
                   1732: 	}
1.1       albertel 1733:     }    
                   1734:     return 'no_host';
1.70      www      1735: }
                   1736: 
1.1300    raeburn  1737: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1738: 
                   1739: sub idget {
1.1300    raeburn  1740:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1741:     my %returnhash=();
1.1300    raeburn  1742:     my @ids=(); 
                   1743:     if (ref($idsref) eq 'ARRAY') {
                   1744:         @ids = @{$idsref};
                   1745:     } else {
                   1746:         return %returnhash; 
                   1747:     }
                   1748:     if ($namespace eq '') {
                   1749:         $namespace = 'ids';
                   1750:     }
1.70      www      1751:     
1.841     albertel 1752:     my %servers = &get_servers($udom,'library');
                   1753:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1754: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1755: 	if ($namespace eq 'ids') {
                   1756: 	    $idlist=~tr/A-Z/a-z/;
                   1757: 	}
                   1758: 	my $reply;
                   1759: 	if ($namespace eq 'ids') {
                   1760: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1761: 	} else {
                   1762: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1763: 	}
1.841     albertel 1764: 	my @answer=();
                   1765: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1766: 	    @answer=split(/\&/,$reply);
                   1767: 	}                    ;
                   1768: 	my $i;
                   1769: 	for ($i=0;$i<=$#ids;$i++) {
                   1770: 	    if ($answer[$i]) {
1.1299    raeburn  1771: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1772: 	    }
1.841     albertel 1773: 	}
1.1300    raeburn  1774:     }
1.70      www      1775:     return %returnhash;
                   1776: }
                   1777: 
                   1778: # ------------------------------------- Find the IDs behind a list of usernames
                   1779: 
                   1780: sub idrget {
                   1781:     my ($udom,@unames)=@_;
                   1782:     my %returnhash=();
1.800     albertel 1783:     foreach my $uname (@unames) {
                   1784:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1785:     }
1.70      www      1786:     return %returnhash;
                   1787: }
                   1788: 
1.1300    raeburn  1789: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1790: 
                   1791: sub idput {
1.1300    raeburn  1792:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1793:     my %servers=();
1.1300    raeburn  1794:     my %ids=();
                   1795:     my %byid = ();
                   1796:     if (ref($idsref) eq 'HASH') {
                   1797:         %ids=%{$idsref};
                   1798:     }
                   1799:     if ($namespace eq '') {
                   1800:         $namespace = 'ids'; 
                   1801:     }
1.800     albertel 1802:     foreach my $uname (keys(%ids)) {
                   1803: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1804:         if ($uhom eq '') {
                   1805:             $uhom=&homeserver($uname,$udom);
                   1806:         }
1.70      www      1807:         if ($uhom ne 'no_host') {
1.800     albertel 1808:             my $esc_unam=&escape($uname);
1.1300    raeburn  1809:             if ($namespace eq 'ids') {
                   1810:                 my $id=&escape($ids{$uname});
                   1811:                 $id=~tr/A-Z/a-z/;
                   1812:                 my $esc_unam=&escape($uname);
                   1813:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1814:             } else {
1.1300    raeburn  1815:                 my @currids = split(/,/,$ids{$uname});
                   1816:                 foreach my $id (@currids) {
                   1817:                     $byid{$uhom}{$id} .= $uname.',';
                   1818:                 }
                   1819:             }
                   1820:         }
                   1821:     }
                   1822:     if ($namespace eq 'clickers') {
                   1823:         foreach my $server (keys(%byid)) {
                   1824:             if (ref($byid{$server}) eq 'HASH') {
                   1825:                 foreach my $id (keys(%{$byid{$server}})) {
                   1826:                     $byid{$server} =~ s/,$//;
                   1827:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1828:                 }
1.70      www      1829:             }
                   1830:         }
1.191     harris41 1831:     }
1.800     albertel 1832:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1833:         $servers{$server} =~ s/\&$//;
                   1834:         if ($namespace eq 'ids') {     
                   1835:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1836:         } else {
                   1837:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1838:         }
1.191     harris41 1839:     }
1.344     www      1840: }
                   1841: 
1.1300    raeburn  1842: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1843: 
                   1844: sub iddel {
1.1300    raeburn  1845:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1846:     my %result=();
1.1300    raeburn  1847:     my %ids=();
                   1848:     my %byid = ();
                   1849:     if (ref($idshashref) eq 'HASH') {
                   1850:         %ids=%{$idshashref};
                   1851:     } else {
1.1231    raeburn  1852:         return %result;
                   1853:     }
1.1300    raeburn  1854:     if ($namespace eq '') {
                   1855:         $namespace = 'ids';
                   1856:     }
1.1231    raeburn  1857:     my %servers=();
1.1300    raeburn  1858:     while (my ($id,$unamestr) = each(%ids)) {
                   1859:         if ($namespace eq 'ids') {
                   1860:             my $uhom = $uhome;
                   1861:             if ($uhom eq '') { 
                   1862:                 $uhom=&homeserver($unamestr,$udom);
                   1863:             }
                   1864:             if ($uhom ne 'no_host') {
                   1865:                 $servers{$uhom}.='&'.&escape($id);
                   1866:             }
                   1867:          } else {
                   1868:             my @curritems = split(/,/,$ids{$id});
                   1869:             foreach my $uname (@curritems) {
                   1870:                 my $uhom = $uhome;
                   1871:                 if ($uhom eq '') {
                   1872:                     $uhom=&homeserver($uname,$udom);
                   1873:                 }
                   1874:                 if ($uhom ne 'no_host') { 
                   1875:                     $byid{$uhom}{$id} .= $uname.',';
                   1876:                 }
                   1877:             }
1.1231    raeburn  1878:         }
1.1300    raeburn  1879:     }
                   1880:     if ($namespace eq 'clickers') {
                   1881:         foreach my $server (keys(%byid)) {
                   1882:             if (ref($byid{$server}) eq 'HASH') {
                   1883:                 foreach my $id (keys(%{$byid{$server}})) {
                   1884:                     $byid{$server}{$id} =~ s/,$//;
                   1885:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1886:                 }
1.1231    raeburn  1887:             }
                   1888:         }
                   1889:     }
                   1890:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1891:         $servers{$server} =~ s/\&$//;
                   1892:         if ($namespace eq 'ids') {
                   1893:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1894:         } elsif ($namespace eq 'clickers') {
                   1895:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1896:         }
1.1231    raeburn  1897:     }
                   1898:     return %result;
                   1899: }
                   1900: 
1.1300    raeburn  1901: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1902: 
                   1903: sub updateclickers {
                   1904:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1905:     my %clickers;
                   1906:     if (ref($idshashref) eq 'HASH') {
                   1907:         %clickers=%{$idshashref};
                   1908:     } else {
                   1909:         return;
                   1910:     }
                   1911:     my $items='';
                   1912:     foreach my $item (keys(%clickers)) {
                   1913:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1914:     }
                   1915:     $items=~s/\&$//;
                   1916:     my $request = "updateclickers:$udom:$action:$items";
                   1917:     if ($critical) {
                   1918:         return &critical($request,$uhome);
                   1919:     } else {
                   1920:         return &reply($request,$uhome);
                   1921:     }
                   1922: }
                   1923: 
1.1023    raeburn  1924: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1925: sub dump_dom {
1.1165    droeschl 1926:     my ($namespace, $udom, $regexp) = @_;
                   1927: 
                   1928:     $udom ||= $env{'user.domain'};
                   1929: 
                   1930:     return () unless $udom;
                   1931: 
                   1932:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1933: }
                   1934: 
1.1023    raeburn  1935: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1936: 
                   1937: sub get_dom {
1.860     raeburn  1938:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1939:     return if ($udom eq 'public');
1.806     raeburn  1940:     my $items='';
                   1941:     foreach my $item (@$storearr) {
                   1942:         $items.=&escape($item).'&';
                   1943:     }
                   1944:     $items=~s/\&$//;
1.860     raeburn  1945:     if (!$udom) {
                   1946:         $udom=$env{'user.domain'};
1.1267    raeburn  1947:         return if ($udom eq 'public');
1.860     raeburn  1948:         if (defined(&domain($udom,'primary'))) {
                   1949:             $uhome=&domain($udom,'primary');
                   1950:         } else {
1.874     albertel 1951:             undef($uhome);
1.860     raeburn  1952:         }
                   1953:     } else {
                   1954:         if (!$uhome) {
                   1955:             if (defined(&domain($udom,'primary'))) {
                   1956:                 $uhome=&domain($udom,'primary');
                   1957:             }
                   1958:         }
                   1959:     }
                   1960:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  1961:         my $rep;
                   1962:         if ($namespace =~ /^enc/) {
                   1963:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1964:         } else {
                   1965:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1966:         }
1.866     raeburn  1967:         my %returnhash;
1.875     albertel 1968:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1969:             return %returnhash;
                   1970:         }
1.806     raeburn  1971:         my @pairs=split(/\&/,$rep);
                   1972:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1973:             return @pairs;
                   1974:         }
                   1975:         my $i=0;
                   1976:         foreach my $item (@$storearr) {
                   1977:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1978:             $i++;
                   1979:         }
                   1980:         return %returnhash;
                   1981:     } else {
1.880     banghart 1982:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1983:     }
                   1984: }
                   1985: 
                   1986: # -------------------------------------------- put items in domain db files 
                   1987: 
                   1988: sub put_dom {
1.860     raeburn  1989:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1990:     if (!$udom) {
                   1991:         $udom=$env{'user.domain'};
                   1992:         if (defined(&domain($udom,'primary'))) {
                   1993:             $uhome=&domain($udom,'primary');
                   1994:         } else {
1.874     albertel 1995:             undef($uhome);
1.860     raeburn  1996:         }
                   1997:     } else {
                   1998:         if (!$uhome) {
                   1999:             if (defined(&domain($udom,'primary'))) {
                   2000:                 $uhome=&domain($udom,'primary');
                   2001:             }
                   2002:         }
                   2003:     } 
                   2004:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2005:         my $items='';
                   2006:         foreach my $item (keys(%$storehash)) {
                   2007:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2008:         }
                   2009:         $items=~s/\&$//;
1.1344    raeburn  2010:         if ($namespace =~ /^enc/) {
                   2011:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2012:         } else {
                   2013:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2014:         }
1.806     raeburn  2015:     } else {
1.860     raeburn  2016:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2017:     }
                   2018: }
                   2019: 
1.1023    raeburn  2020: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2021: sub newput_dom {
1.1023    raeburn  2022:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2023:     my $result;
                   2024:     if (!$udom) {
                   2025:         $udom=$env{'user.domain'};
                   2026:     }
1.1023    raeburn  2027:     if ($udom) {
                   2028:         my $uname = &get_domainconfiguser($udom);
                   2029:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2030:     }
                   2031:     return $result;
                   2032: }
                   2033: 
1.1023    raeburn  2034: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2035: sub del_dom {
1.1023    raeburn  2036:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2037:     if (ref($storearr) eq 'ARRAY') {
                   2038:         if (!$udom) {
                   2039:             $udom=$env{'user.domain'};
                   2040:         }
1.1023    raeburn  2041:         if ($udom) {
                   2042:             my $uname = &get_domainconfiguser($udom); 
                   2043:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2044:         }
                   2045:     }
                   2046: }
                   2047: 
1.1023    raeburn  2048: # ----------------------------------construct domainconfig user for a domain 
                   2049: sub get_domainconfiguser {
                   2050:     my ($udom) = @_;
                   2051:     return $udom.'-domainconfig';
                   2052: }
                   2053: 
1.837     raeburn  2054: sub retrieve_inst_usertypes {
                   2055:     my ($udom) = @_;
                   2056:     my (%returnhash,@order);
1.989     raeburn  2057:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2058:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2059:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2060:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2061:     } else {
                   2062:         if (defined(&domain($udom,'primary'))) {
                   2063:             my $uhome=&domain($udom,'primary');
                   2064:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2065:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2066:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2067:                 return (\%returnhash,\@order);
                   2068:             }
                   2069:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2070:             my @pairs=split(/\&/,$hashitems);
                   2071:             foreach my $item (@pairs) {
                   2072:                 my ($key,$value)=split(/=/,$item,2);
                   2073:                 $key = &unescape($key);
                   2074:                 next if ($key =~ /^error: 2 /);
                   2075:                 $returnhash{$key}=&thaw_unescape($value);
                   2076:             }
                   2077:             my @esc_order = split(/\&/,$orderitems);
                   2078:             foreach my $item (@esc_order) {
                   2079:                 push(@order,&unescape($item));
                   2080:             }
                   2081:         } else {
1.1256    raeburn  2082:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2083:         }
1.1256    raeburn  2084:         return (\%returnhash,\@order);
1.837     raeburn  2085:     }
                   2086: }
                   2087: 
1.868     raeburn  2088: sub is_domainimage {
                   2089:     my ($url) = @_;
1.1306    raeburn  2090:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2091:         if (&domain($1) ne '') {
                   2092:             return '1';
                   2093:         }
                   2094:     }
                   2095:     return;
                   2096: }
                   2097: 
1.899     raeburn  2098: sub inst_directory_query {
                   2099:     my ($srch) = @_;
                   2100:     my $udom = $srch->{'srchdomain'};
                   2101:     my %results;
                   2102:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2103:     my $outcome;
1.899     raeburn  2104:     if ($homeserver ne '') {
1.1357    raeburn  2105:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2106:             if ($srch->{'srchby'} eq 'email') {
                   2107:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2108:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2109:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2110:                     (($major == 2) && ($minor < 12))) {
                   2111:                     return;
                   2112:                 }
                   2113:             }
                   2114:         }
1.904     albertel 2115: 	my $queryid=&reply("querysend:instdirsearch:".
                   2116: 			   &escape($srch->{'srchby'}).':'.
                   2117: 			   &escape($srch->{'srchterm'}).':'.
                   2118: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2119: 	my $host=&hostname($homeserver);
                   2120: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2121: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2122: 	    return;
                   2123: 	}
                   2124: 	my $response = &get_query_reply($queryid);
                   2125: 	my $maxtries = 5;
                   2126: 	my $tries = 1;
                   2127: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2128: 	    $response = &get_query_reply($queryid);
                   2129: 	    $tries ++;
                   2130: 	}
                   2131: 
                   2132:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2133:             if ($response eq 'unavailable') {
                   2134:                 $outcome = $response;
                   2135:             } else {
                   2136:                 $outcome = 'ok';
                   2137:                 my @matches = split(/\n/,$response);
                   2138:                 foreach my $match (@matches) {
                   2139:                     my ($key,$value) = split(/=/,$match);
                   2140:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2141:                 }
1.899     raeburn  2142:             }
                   2143:         }
                   2144:     }
1.909     raeburn  2145:     return ($outcome,%results);
1.899     raeburn  2146: }
                   2147: 
                   2148: sub usersearch {
                   2149:     my ($srch) = @_;
                   2150:     my $dom = $srch->{'srchdomain'};
                   2151:     my %results;
                   2152:     my %libserv = &all_library();
                   2153:     my $query = 'usersearch';
                   2154:     foreach my $tryserver (keys(%libserv)) {
                   2155:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2156:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2157:                 if ($srch->{'srchby'} eq 'email') {
                   2158:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2159:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2160:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2161:                              (($major == 2) && ($minor < 12)));
                   2162:                 }
                   2163:             }
1.899     raeburn  2164:             my $host=&hostname($tryserver);
                   2165:             my $queryid=
1.911     raeburn  2166:                 &reply("querysend:".&escape($query).':'.
                   2167:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2168:                        &escape($srch->{'srchtype'}).':'.
                   2169:                        &escape($srch->{'srchterm'}),$tryserver);
                   2170:             if ($queryid !~/^\Q$host\E\_/) {
                   2171:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2172:                 next;
1.899     raeburn  2173:             }
                   2174:             my $reply = &get_query_reply($queryid);
                   2175:             my $maxtries = 1;
                   2176:             my $tries = 1;
                   2177:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2178:                 $reply = &get_query_reply($queryid);
                   2179:                 $tries ++;
                   2180:             }
                   2181:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2182:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2183:             } else {
1.911     raeburn  2184:                 my @matches;
                   2185:                 if ($reply =~ /\n/) {
                   2186:                     @matches = split(/\n/,$reply);
                   2187:                 } else {
                   2188:                     @matches = split(/\&/,$reply);
                   2189:                 }
1.899     raeburn  2190:                 foreach my $match (@matches) {
                   2191:                     my ($uname,$udom,%userhash);
1.911     raeburn  2192:                     foreach my $entry (split(/:/,$match)) {
                   2193:                         my ($key,$value) =
                   2194:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2195:                         $userhash{$key} = $value;
                   2196:                         if ($key eq 'username') {
                   2197:                             $uname = $value;
                   2198:                         } elsif ($key eq 'domain') {
                   2199:                             $udom = $value;
1.911     raeburn  2200:                         }
1.899     raeburn  2201:                     }
                   2202:                     $results{$uname.':'.$udom} = \%userhash;
                   2203:                 }
                   2204:             }
                   2205:         }
                   2206:     }
                   2207:     return %results;
                   2208: }
                   2209: 
1.912     raeburn  2210: sub get_instuser {
                   2211:     my ($udom,$uname,$id) = @_;
                   2212:     my $homeserver = &domain($udom,'primary');
                   2213:     my ($outcome,%results);
                   2214:     if ($homeserver ne '') {
                   2215:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2216:                            &escape($id).':'.&escape($udom),$homeserver);
                   2217:         my $host=&hostname($homeserver);
                   2218:         if ($queryid !~/^\Q$host\E\_/) {
                   2219:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2220:             return;
                   2221:         }
                   2222:         my $response = &get_query_reply($queryid);
                   2223:         my $maxtries = 5;
                   2224:         my $tries = 1;
                   2225:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2226:             $response = &get_query_reply($queryid);
                   2227:             $tries ++;
                   2228:         }
                   2229:         if (!&error($response) && $response ne 'refused') {
                   2230:             if ($response eq 'unavailable') {
                   2231:                 $outcome = $response;
                   2232:             } else {
                   2233:                 $outcome = 'ok';
                   2234:                 my @matches = split(/\n/,$response);
                   2235:                 foreach my $match (@matches) {
                   2236:                     my ($key,$value) = split(/=/,$match);
                   2237:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2238:                 }
                   2239:             }
                   2240:         }
                   2241:     }
                   2242:     my %userinfo;
                   2243:     if (ref($results{$uname}) eq 'HASH') {
                   2244:         %userinfo = %{$results{$uname}};
                   2245:     } 
                   2246:     return ($outcome,%userinfo);
                   2247: }
                   2248: 
1.1290    raeburn  2249: sub get_multiple_instusers {
                   2250:     my ($udom,$users,$caller) = @_;
                   2251:     my ($outcome,$results);
                   2252:     if (ref($users) eq 'HASH') {
                   2253:         my $count = keys(%{$users}); 
                   2254:         my $requested = &freeze_escape($users);
                   2255:         my $homeserver = &domain($udom,'primary');
                   2256:         if ($homeserver ne '') {
                   2257:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2258:             my $host=&hostname($homeserver);
                   2259:             if ($queryid !~/^\Q$host\E\_/) {
                   2260:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2261:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2262:                 return ($outcome,$results);
                   2263:             }
                   2264:             my $response = &get_query_reply($queryid);
                   2265:             my $maxtries = 5;
                   2266:             if ($count > 100) {
                   2267:                 $maxtries = 1+int($count/20);
                   2268:             }
                   2269:             my $tries = 1;
                   2270:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2271:                 $response = &get_query_reply($queryid);
                   2272:                 $tries ++;
                   2273:             }
                   2274:             if ($response eq '') {
                   2275:                 $results = {};
                   2276:                 foreach my $key (keys(%{$users})) {
                   2277:                     my ($uname,$id);
                   2278:                     if ($caller eq 'id') {
                   2279:                         $id = $key;
                   2280:                     } else {
                   2281:                         $uname = $key;
                   2282:                     }
                   2283:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2284:                     $outcome = $resp;
1.1290    raeburn  2285:                     if ($resp eq 'ok') {
                   2286:                         %{$results} = (%{$results}, %info);
                   2287:                     } else {
                   2288:                         last;
                   2289:                     }
                   2290:                 }
                   2291:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2292:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2293:                     $outcome = $response;
                   2294:                 } else {
1.1291    raeburn  2295:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2296:                     if ($outcome eq 'ok') {
                   2297:                         $results = &thaw_unescape($userdata); 
                   2298:                     }
                   2299:                 }
                   2300:             }
                   2301:         }
                   2302:     }
                   2303:     return ($outcome,$results);
                   2304: }
                   2305: 
1.912     raeburn  2306: sub inst_rulecheck {
1.923     raeburn  2307:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2308:     my %returnhash;
                   2309:     if ($udom ne '') {
                   2310:         if (ref($rules) eq 'ARRAY') {
                   2311:             @{$rules} = map {&escape($_);} (@{$rules});
                   2312:             my $rulestr = join(':',@{$rules});
                   2313:             my $homeserver=&domain($udom,'primary');
                   2314:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2315:                 my $response;
                   2316:                 if ($item eq 'username') {                
                   2317:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2318:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2319:                                               $homeserver));
1.923     raeburn  2320:                 } elsif ($item eq 'id') {
                   2321:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2322:                                               ':'.&escape($id).':'.$rulestr,
                   2323:                                               $homeserver));
1.945     raeburn  2324:                 } elsif ($item eq 'selfcreate') {
                   2325:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2326:                                                &escape($udom).':'.&escape($uname).
                   2327:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2328:                 }
1.912     raeburn  2329:                 if ($response ne 'refused') {
                   2330:                     my @pairs=split(/\&/,$response);
                   2331:                     foreach my $item (@pairs) {
                   2332:                         my ($key,$value)=split(/=/,$item,2);
                   2333:                         $key = &unescape($key);
                   2334:                         next if ($key =~ /^error: 2 /);
                   2335:                         $returnhash{$key}=&thaw_unescape($value);
                   2336:                     }
                   2337:                 }
                   2338:             }
                   2339:         }
                   2340:     }
                   2341:     return %returnhash;
                   2342: }
                   2343: 
                   2344: sub inst_userrules {
1.923     raeburn  2345:     my ($udom,$check) = @_;
1.912     raeburn  2346:     my (%ruleshash,@ruleorder);
                   2347:     if ($udom ne '') {
                   2348:         my $homeserver=&domain($udom,'primary');
                   2349:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2350:             my $response;
                   2351:             if ($check eq 'id') {
                   2352:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2353:                                  $homeserver);
1.943     raeburn  2354:             } elsif ($check eq 'email') {
                   2355:                 $response=&reply('instemailrules:'.&escape($udom),
                   2356:                                  $homeserver);
1.923     raeburn  2357:             } else {
                   2358:                 $response=&reply('instuserrules:'.&escape($udom),
                   2359:                                  $homeserver);
                   2360:             }
1.912     raeburn  2361:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2362:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2363:                 ($response ne 'no_such_host')) {
                   2364:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2365:                 my @pairs=split(/\&/,$hashitems);
                   2366:                 foreach my $item (@pairs) {
                   2367:                     my ($key,$value)=split(/=/,$item,2);
                   2368:                     $key = &unescape($key);
                   2369:                     next if ($key =~ /^error: 2 /);
                   2370:                     $ruleshash{$key}=&thaw_unescape($value);
                   2371:                 }
                   2372:                 my @esc_order = split(/\&/,$orderitems);
                   2373:                 foreach my $item (@esc_order) {
                   2374:                     push(@ruleorder,&unescape($item));
                   2375:                 }
                   2376:             }
                   2377:         }
                   2378:     }
                   2379:     return (\%ruleshash,\@ruleorder);
                   2380: }
                   2381: 
1.976     raeburn  2382: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2383: 
                   2384: sub get_domain_defaults {
1.1240    raeburn  2385:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2386:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2387:     my $cachetime = 60*60*24;
1.1240    raeburn  2388:     unless ($ignore_cache) {
                   2389:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2390:         if (defined($cached)) {
                   2391:             if (ref($result) eq 'HASH') {
                   2392:                 return %{$result};
                   2393:             }
1.943     raeburn  2394:         }
                   2395:     }
                   2396:     my %domdefaults;
                   2397:     my %domconfig =
1.989     raeburn  2398:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2399:                                   'requestcourses','inststatus',
1.1183    raeburn  2400:                                   'coursedefaults','usersessions',
1.1258    raeburn  2401:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2402:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2403:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2404:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2405:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2406:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2407:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2408:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2409:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2410:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2411:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2412:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2413:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2414:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2415:     } else {
                   2416:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2417:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2418:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2419:     }
1.976     raeburn  2420:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2421:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2422:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2423:         } else {
                   2424:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2425:         }
1.1177    raeburn  2426:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2427:         foreach my $item (@usertools) {
                   2428:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2429:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2430:             }
                   2431:         }
1.1229    raeburn  2432:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2433:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2434:         }
1.976     raeburn  2435:     }
1.985     raeburn  2436:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2437:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2438:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2439:         }
                   2440:     }
1.1183    raeburn  2441:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2442:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2443:     }
1.989     raeburn  2444:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2445:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2446:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2447:         }
                   2448:     }
1.1047    raeburn  2449:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2450:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2451:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2452:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2453:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2454:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2455:         }
1.1254    raeburn  2456:         foreach my $type (@coursetypes) {
                   2457:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2458:                 unless ($type eq 'community') {
                   2459:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2460:                 }
                   2461:             }
                   2462:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2463:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2464:             }
1.1277    raeburn  2465:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2466:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2467:                     $domdefaults{$type.'postsubtimeout'} = 
                   2468:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2469:                 }
                   2470:             }
1.1230    raeburn  2471:         }
1.1286    raeburn  2472:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2473:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2474:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2475:                 if (@clonecodes) {
                   2476:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2477:                 }
                   2478:             }
                   2479:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2480:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2481:         }
1.1356    raeburn  2482:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2483:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2484:         } 
1.1047    raeburn  2485:     }
1.1073    raeburn  2486:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2487:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2488:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2489:         }
                   2490:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2491:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2492:         }
1.1279    raeburn  2493:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2494:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2495:         }
1.1073    raeburn  2496:     }
1.1254    raeburn  2497:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2498:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2499:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2500:                             'approval','limit');
                   2501:             foreach my $type (@coursetypes) {
                   2502:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2503:                     my @mgrdc = ();
                   2504:                     foreach my $item (@settings) {
                   2505:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2506:                             push(@mgrdc,$item);
                   2507:                         }
                   2508:                     }
                   2509:                     if (@mgrdc) {
                   2510:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2511:                     }
                   2512:                 }
                   2513:             }
                   2514:         }
                   2515:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2516:             foreach my $type (@coursetypes) {
                   2517:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2518:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2519:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2520:                     }
                   2521:                 }
                   2522:             }
                   2523:         }
                   2524:     }
1.1258    raeburn  2525:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2526:         $domdefaults{'catauth'} = 'std';
                   2527:         $domdefaults{'catunauth'} = 'std';
                   2528:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2529:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2530:         }
                   2531:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2532:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2533:         }
                   2534:     }
1.1315    raeburn  2535:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2536:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2537:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2538:         }
1.1338    raeburn  2539:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2540:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2541:         }
                   2542:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2543:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2544:         }
                   2545:     }
1.1320    raeburn  2546:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2547:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2548:         foreach my $prefix (@prefixes) {
                   2549:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2550:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2551:             }
                   2552:         }
                   2553:     }
1.1314    raeburn  2554:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2555:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2556:     }
1.1332    raeburn  2557:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2558:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2559:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2560:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2561:         }
                   2562:     }
1.1219    raeburn  2563:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2564:     return %domdefaults;
                   2565: }
                   2566: 
1.1311    raeburn  2567: sub course_portal_url {
                   2568:     my ($cnum,$cdom) = @_;
                   2569:     my $chome = &homeserver($cnum,$cdom);
                   2570:     my $hostname = &hostname($chome);
                   2571:     my $protocol = $protocol{$chome};
                   2572:     $protocol = 'http' if ($protocol ne 'https');
                   2573:     my %domdefaults = &get_domain_defaults($cdom);
                   2574:     my $firsturl;
                   2575:     if ($domdefaults{'portal_def'}) {
                   2576:         $firsturl = $domdefaults{'portal_def'};
                   2577:     } else {
                   2578:         $firsturl = $protocol.'://'.$hostname;
                   2579:     }
                   2580:     return $firsturl;
                   2581: }
                   2582: 
1.344     www      2583: # --------------------------------------------------- Assign a key to a student
                   2584: 
                   2585: sub assign_access_key {
1.364     www      2586: #
                   2587: # a valid key looks like uname:udom#comments
                   2588: # comments are being appended
                   2589: #
1.498     www      2590:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2591:     $kdom=
1.620     albertel 2592:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2593:     $knum=
1.620     albertel 2594:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2595:     $cdom=
1.620     albertel 2596:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2597:     $cnum=
1.620     albertel 2598:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2599:     $udom=$env{'user.name'} unless (defined($udom));
                   2600:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2601:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2602:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2603:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2604:                                                   # assigned to this person
                   2605:                                                   # - this should not happen,
1.345     www      2606:                                                   # unless something went wrong
                   2607:                                                   # the first time around
                   2608: # ready to assign
1.364     www      2609:         $logentry=$1.'; '.$logentry;
1.496     www      2610:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2611:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2612: # key now belongs to user
1.346     www      2613: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2614:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2615:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2616:                 return 'ok';
                   2617:             } else {
                   2618:                 return 
                   2619:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2620: 	    }
                   2621:         } else {
                   2622:             return 'error: Could not assign key, try again later.';
                   2623:         }
1.364     www      2624:     } elsif (!$existing{$ckey}) {
1.345     www      2625: # the key does not exist
                   2626: 	return 'error: The key does not exist';
                   2627:     } else {
                   2628: # the key is somebody else's
                   2629: 	return 'error: The key is already in use';
                   2630:     }
1.344     www      2631: }
                   2632: 
1.364     www      2633: # ------------------------------------------ put an additional comment on a key
                   2634: 
                   2635: sub comment_access_key {
                   2636: #
                   2637: # a valid key looks like uname:udom#comments
                   2638: # comments are being appended
                   2639: #
                   2640:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2641:     $cdom=
1.620     albertel 2642:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2643:     $cnum=
1.620     albertel 2644:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2645:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2646:     if ($existing{$ckey}) {
                   2647:         $existing{$ckey}.='; '.$logentry;
                   2648: # ready to assign
1.367     www      2649:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2650:                                                  $cdom,$cnum) eq 'ok') {
                   2651: 	    return 'ok';
                   2652:         } else {
                   2653: 	    return 'error: Count not store comment.';
                   2654:         }
                   2655:     } else {
                   2656: # the key does not exist
                   2657: 	return 'error: The key does not exist';
                   2658:     }
                   2659: }
                   2660: 
1.344     www      2661: # ------------------------------------------------------ Generate a set of keys
                   2662: 
                   2663: sub generate_access_keys {
1.364     www      2664:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2665:     $cdom=
1.620     albertel 2666:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2667:     $cnum=
1.620     albertel 2668:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2669:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2670:     unless (($cdom) && ($cnum)) { return 0; }
                   2671:     if ($number>10000) { return 0; }
                   2672:     sleep(2); # make sure don't get same seed twice
                   2673:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2674:     my $total=0;
                   2675:     for (my $i=1;$i<=$number;$i++) {
                   2676:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2677:                   sprintf("%lx",int(100000*rand)).'-'.
                   2678:                   sprintf("%lx",int(100000*rand));
                   2679:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2680:        $newkey=~s/0/h/g; # and also 0 and O
                   2681:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2682:        if ($existing{$newkey}) {
                   2683:            $i--;
                   2684:        } else {
1.364     www      2685: 	  if (&put('accesskeys',
                   2686:               { $newkey => '# generated '.localtime().
1.620     albertel 2687:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2688:                            '; '.$logentry },
                   2689: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2690:               $total++;
                   2691: 	  }
                   2692:        }
                   2693:     }
1.620     albertel 2694:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2695:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2696:     return $total;
                   2697: }
                   2698: 
                   2699: # ------------------------------------------------------- Validate an accesskey
                   2700: 
                   2701: sub validate_access_key {
                   2702:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2703:     $cdom=
1.620     albertel 2704:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2705:     $cnum=
1.620     albertel 2706:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2707:     $udom=$env{'user.domain'} unless (defined($udom));
                   2708:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2709:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2710:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2711: }
                   2712: 
                   2713: # ------------------------------------- Find the section of student in a course
1.652     albertel 2714: sub devalidate_getsection_cache {
                   2715:     my ($udom,$unam,$courseid)=@_;
                   2716:     my $hashid="$udom:$unam:$courseid";
                   2717:     &devalidate_cache_new('getsection',$hashid);
                   2718: }
1.298     matthew  2719: 
1.815     albertel 2720: sub courseid_to_courseurl {
                   2721:     my ($courseid) = @_;
                   2722:     #already url style courseid
                   2723:     return $courseid if ($courseid =~ m{^/});
                   2724: 
                   2725:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2726: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2727: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2728: 	return "/$cdom/$cnum";
                   2729:     }
                   2730: 
                   2731:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2732:     if (exists($courseinfo{'num'})) {
                   2733: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2734:     }
                   2735: 
                   2736:     return undef;
                   2737: }
                   2738: 
1.298     matthew  2739: sub getsection {
                   2740:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2741:     my $cachetime=1800;
1.551     albertel 2742: 
                   2743:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2744:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2745:     if (defined($cached)) { return $result; }
                   2746: 
1.298     matthew  2747:     my %Pending; 
                   2748:     my %Expired;
                   2749:     #
                   2750:     # Each role can either have not started yet (pending), be active, 
                   2751:     #    or have expired.
                   2752:     #
                   2753:     # If there is an active role, we are done.
                   2754:     #
                   2755:     # If there is more than one role which has not started yet, 
                   2756:     #     choose the one which will start sooner
                   2757:     # If there is one role which has not started yet, return it.
                   2758:     #
                   2759:     # If there is more than one expired role, choose the one which ended last.
                   2760:     # If there is a role which has expired, return it.
                   2761:     #
1.815     albertel 2762:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2763:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2764:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2765:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2766:         my $section=$1;
                   2767:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2768:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2769:         my $now=time;
1.548     albertel 2770:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2771:             $Expired{$end}=$section;
                   2772:             next;
                   2773:         }
1.548     albertel 2774:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2775:             $Pending{$start}=$section;
                   2776:             next;
                   2777:         }
1.599     albertel 2778:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2779:     }
                   2780:     #
                   2781:     # Presumedly there will be few matching roles from the above
                   2782:     # loop and the sorting time will be negligible.
                   2783:     if (scalar(keys(%Pending))) {
                   2784:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2785:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2786:     } 
                   2787:     if (scalar(keys(%Expired))) {
                   2788:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2789:         my $time = pop(@sorted);
1.599     albertel 2790:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2791:     }
1.599     albertel 2792:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2793: }
1.70      www      2794: 
1.599     albertel 2795: sub save_cache {
                   2796:     &purge_remembered();
1.722     albertel 2797:     #&Apache::loncommon::validate_page();
1.620     albertel 2798:     undef(%env);
1.780     albertel 2799:     undef($env_loaded);
1.599     albertel 2800: }
1.452     albertel 2801: 
1.599     albertel 2802: my $to_remember=-1;
                   2803: my %remembered;
                   2804: my %accessed;
                   2805: my $kicks=0;
                   2806: my $hits=0;
1.849     albertel 2807: sub make_key {
                   2808:     my ($name,$id) = @_;
1.872     albertel 2809:     if (length($id) > 65 
                   2810: 	&& length(&escape($id)) > 200) {
                   2811: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2812:     }
1.849     albertel 2813:     return &escape($name.':'.$id);
                   2814: }
                   2815: 
1.599     albertel 2816: sub devalidate_cache_new {
                   2817:     my ($name,$id,$debug) = @_;
                   2818:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2819:     my $remembered_id=$name.':'.$id;
1.849     albertel 2820:     $id=&make_key($name,$id);
1.599     albertel 2821:     $memcache->delete($id);
1.1319    damieng  2822:     delete($remembered{$remembered_id});
                   2823:     delete($accessed{$remembered_id});
1.599     albertel 2824: }
                   2825: 
                   2826: sub is_cached_new {
                   2827:     my ($name,$id,$debug) = @_;
1.1319    damieng  2828:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2829:     if (exists($remembered{$remembered_id})) {
                   2830: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2831: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2832: 	$hits++;
1.1319    damieng  2833: 	return ($remembered{$remembered_id},1);
1.599     albertel 2834:     }
1.1319    damieng  2835:     $id=&make_key($name,$id);
1.599     albertel 2836:     my $value = $memcache->get($id);
                   2837:     if (!(defined($value))) {
                   2838: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2839: 	return (undef,undef);
1.416     albertel 2840:     }
1.599     albertel 2841:     if ($value eq '__undef__') {
                   2842: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2843: 	$value=undef;
                   2844:     }
1.1319    damieng  2845:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2846:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2847:     return ($value,1);
                   2848: }
                   2849: 
                   2850: sub do_cache_new {
                   2851:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2852:     my $remembered_id=$name.':'.$id;
1.849     albertel 2853:     $id=&make_key($name,$id);
1.599     albertel 2854:     my $setvalue=$value;
                   2855:     if (!defined($setvalue)) {
                   2856: 	$setvalue='__undef__';
                   2857:     }
1.623     albertel 2858:     if (!defined($time) ) {
                   2859: 	$time=600;
                   2860:     }
1.599     albertel 2861:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2862:     my $result = $memcache->set($id,$setvalue,$time);
                   2863:     if (! $result) {
1.872     albertel 2864: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2865: 	$memcache->disconnect_all();
1.872     albertel 2866:     }
1.600     albertel 2867:     # need to make a copy of $value
1.1319    damieng  2868:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2869:     return $value;
                   2870: }
                   2871: 
                   2872: sub make_room {
1.1319    damieng  2873:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2874: 
1.1319    damieng  2875:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2876:                                     : $value;
1.599     albertel 2877:     if ($to_remember<0) { return; }
1.1319    damieng  2878:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2879:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2880:     my $to_kick;
                   2881:     my $max_time=0;
                   2882:     foreach my $other (keys(%accessed)) {
                   2883: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2884: 	    $to_kick=$other;
                   2885: 	    $max_time=&tv_interval($accessed{$other});
                   2886: 	}
                   2887:     }
                   2888:     delete($remembered{$to_kick});
                   2889:     delete($accessed{$to_kick});
                   2890:     $kicks++;
                   2891:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2892:     return;
                   2893: }
                   2894: 
1.599     albertel 2895: sub purge_remembered {
1.604     albertel 2896:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2897:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2898:     undef(%remembered);
                   2899:     undef(%accessed);
1.428     albertel 2900: }
1.70      www      2901: # ------------------------------------- Read an entry from a user's environment
                   2902: 
                   2903: sub userenvironment {
                   2904:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2905:     my $items;
                   2906:     foreach my $item (@what) {
                   2907:         $items.=&escape($item).'&';
                   2908:     }
                   2909:     $items=~s/\&$//;
1.70      www      2910:     my %returnhash=();
1.1009    raeburn  2911:     my $uhome = &homeserver($unam,$udom);
                   2912:     unless ($uhome eq 'no_host') {
                   2913:         my @answer=split(/\&/, 
                   2914:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2915:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2916:             return %returnhash;
                   2917:         }
1.1009    raeburn  2918:         my $i;
                   2919:         for ($i=0;$i<=$#what;$i++) {
                   2920: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2921:         }
1.70      www      2922:     }
                   2923:     return %returnhash;
1.1       albertel 2924: }
                   2925: 
1.617     albertel 2926: # ---------------------------------------------------------- Get a studentphoto
                   2927: sub studentphoto {
                   2928:     my ($udom,$unam,$ext) = @_;
                   2929:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2930:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2931:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2932:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2933:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2934:             } else {
                   2935:                 my ($result,$perm_reqd)=
1.707     albertel 2936: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2937:                 if ($result eq 'ok') {
                   2938:                     if (!($perm_reqd eq 'yes')) {
                   2939:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2940:                     }
                   2941:                 }
                   2942:             }
                   2943:         }
                   2944:     } else {
                   2945:         my ($result,$perm_reqd) = 
1.707     albertel 2946: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2947:         if ($result eq 'ok') {
                   2948:             if (!($perm_reqd eq 'yes')) {
                   2949:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2950:             }
                   2951:         }
                   2952:     }
                   2953:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2954: }
                   2955: 
                   2956: sub retrievestudentphoto {
                   2957:     my ($udom,$unam,$ext,$type) = @_;
                   2958:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2959:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2960:     if ($ret eq 'ok') {
                   2961:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2962:         if ($type eq 'thumbnail') {
                   2963:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2964:         }
                   2965:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2966:         return $tokenurl;
                   2967:     } else {
                   2968:         if ($type eq 'thumbnail') {
                   2969:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2970:         } else { 
                   2971:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2972:         }
1.617     albertel 2973:     }
                   2974: }
                   2975: 
1.263     www      2976: # -------------------------------------------------------------------- New chat
                   2977: 
                   2978: sub chatsend {
1.724     raeburn  2979:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2980:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2981:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2982:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2983:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2984: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2985: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2986: }
                   2987: 
                   2988: # ------------------------------------------ Find current version of a resource
                   2989: 
                   2990: sub getversion {
                   2991:     my $fname=&clutter(shift);
1.1189    raeburn  2992:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2993:     return &currentversion(&filelocation('',$fname));
                   2994: }
                   2995: 
                   2996: sub currentversion {
                   2997:     my $fname=shift;
                   2998:     my $author=$fname;
                   2999:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3000:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      3001:     my $home=&homeserver($uname,$udom);
1.292     www      3002:     if ($home eq 'no_host') { 
                   3003:         return -1; 
                   3004:     }
1.1112    www      3005:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3006:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3007: 	return -1;
                   3008:     }
1.1112    www      3009:     return $answer;
1.263     www      3010: }
                   3011: 
1.1111    www      3012: #
                   3013: # Return special version number of resource if set by override, empty otherwise
                   3014: #
                   3015: sub usedversion {
                   3016:     my $fname=shift;
                   3017:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3018:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3019:     if ($urlversion) { return $urlversion; }
                   3020:     return '';
                   3021: }
                   3022: 
1.1       albertel 3023: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3024: 
1.1       albertel 3025: sub subscribe {
                   3026:     my $fname=shift;
1.761     raeburn  3027:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3028:     $fname=~s/[\n\r]//g;
1.1       albertel 3029:     my $author=$fname;
                   3030:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3031:     my ($udom,$uname)=split(/\//,$author);
                   3032:     my $home=homeserver($uname,$udom);
1.335     albertel 3033:     if ($home eq 'no_host') {
                   3034:         return 'not_found';
1.1       albertel 3035:     }
                   3036:     my $answer=reply("sub:$fname",$home);
1.64      www      3037:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3038: 	$answer.=' by '.$home;
                   3039:     }
1.1       albertel 3040:     return $answer;
                   3041: }
                   3042:     
1.8       www      3043: # -------------------------------------------------------------- Replicate file
                   3044: 
                   3045: sub repcopy {
                   3046:     my $filename=shift;
1.23      www      3047:     $filename=~s/\/+/\//g;
1.1142    raeburn  3048:     my $londocroot = $perlvar{'lonDocRoot'};
                   3049:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3050:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3051:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3052: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3053: 	return &repcopy_userfile($filename);
                   3054:     }
1.532     albertel 3055:     $filename=~s/[\n\r]//g;
1.8       www      3056:     my $transname="$filename.in.transfer";
1.828     www      3057: # FIXME: this should flock
1.607     raeburn  3058:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3059:     my $remoteurl=subscribe($filename);
1.64      www      3060:     if ($remoteurl =~ /^con_lost by/) {
                   3061: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3062:            return 'unavailable';
1.8       www      3063:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3064: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3065: 	   return 'not_found';
1.64      www      3066:     } elsif ($remoteurl =~ /^rejected by/) {
                   3067: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3068:            return 'forbidden';
1.20      www      3069:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3070:            return 'ok';
1.8       www      3071:     } else {
1.290     www      3072:         my $author=$filename;
                   3073:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3074:         my ($udom,$uname)=split(/\//,$author);
                   3075:         my $home=homeserver($uname,$udom);
                   3076:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3077:            my @parts=split(/\//,$filename);
                   3078:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3079:            if ($path ne "$londocroot/res") {
1.8       www      3080:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3081: 	       return 'bad_request';
1.8       www      3082:            }
                   3083:            my $count;
                   3084:            for ($count=5;$count<$#parts;$count++) {
                   3085:                $path.="/$parts[$count]";
                   3086:                if ((-e $path)!=1) {
                   3087: 		   mkdir($path,0777);
                   3088:                }
                   3089:            }
                   3090:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3091:            my $response;
                   3092:            if ($remoteurl =~ m{/raw/}) {
                   3093:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3094:            } else {
                   3095:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3096:            }
1.8       www      3097:            if ($response->is_error()) {
                   3098: 	       unlink($transname);
                   3099:                my $message=$response->status_line;
1.672     albertel 3100:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3101:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3102:                return 'unavailable';
1.8       www      3103:            } else {
1.16      www      3104: 	       if ($remoteurl!~/\.meta$/) {
                   3105:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3106:                   my $mresponse;
                   3107:                   if ($remoteurl =~ m{/raw/}) {
                   3108:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3109:                   } else {
                   3110:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3111:                   }
1.16      www      3112:                   if ($mresponse->is_error()) {
                   3113: 		      unlink($filename.'.meta');
                   3114:                       &logthis(
1.672     albertel 3115:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3116:                   }
                   3117: 	       }
1.8       www      3118:                rename($transname,$filename);
1.607     raeburn  3119:                return 'ok';
1.8       www      3120:            }
1.290     www      3121:        }
1.8       www      3122:     }
1.330     www      3123: }
                   3124: 
                   3125: # ------------------------------------------------ Get server side include body
                   3126: sub ssi_body {
1.381     albertel 3127:     my ($filelink,%form)=@_;
1.606     matthew  3128:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3129:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3130:     }
1.953     www      3131:     my $output='';
                   3132:     my $response;
1.980     raeburn  3133:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3134:        ($output,$response)=&externalssi($filelink);
1.953     www      3135:     } else {
1.1004    droeschl 3136:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3137:        $filelink .= 'inhibitmenu=yes';
1.953     www      3138:        ($output,$response)=&ssi($filelink,%form);
                   3139:     }
1.778     albertel 3140:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3141:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3142:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3143:     if (wantarray) {
                   3144:         return ($output, $response);
                   3145:     } else {
                   3146:         return $output;
                   3147:     }
1.8       www      3148: }
                   3149: 
1.15      www      3150: # --------------------------------------------------------- Server Side Include
                   3151: 
1.782     albertel 3152: sub absolute_url {
                   3153:     my ($host_name) = @_;
                   3154:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3155:     if ($host_name eq '') {
                   3156: 	$host_name = $ENV{'SERVER_NAME'};
                   3157:     }
                   3158:     return $protocol.$host_name;
                   3159: }
                   3160: 
1.942     foxr     3161: #
                   3162: #   Server side include.
                   3163: # Parameters:
                   3164: #  fn     Possibly encrypted resource name/id.
                   3165: #  form   Hash that describes how the rendering should be done
                   3166: #         and other things.
1.944     foxr     3167: # Returns:
1.950     raeburn  3168: #   Scalar context: The content of the response.
                   3169: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3170: #     
1.15      www      3171: sub ssi {
                   3172: 
1.944     foxr     3173:     my ($fn,%form)=@_;
1.23      www      3174:     my $request;
1.711     albertel 3175: 
                   3176:     $form{'no_update_last_known'}=1;
1.895     albertel 3177:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3178:     if (%form) {
1.782     albertel 3179:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3180:       $request->content(join('&',map { 
                   3181:             my $name = escape($_);
                   3182:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3183:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3184:             : &escape($form{$_}) );    
                   3185:         } keys(%form)));
1.23      www      3186:     } else {
1.782     albertel 3187:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3188:     }
                   3189: 
1.15      www      3190:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3191:     my $lonhost = $perlvar{'lonHostID'};
                   3192:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
1.1182    foxr     3193: 
1.944     foxr     3194:     if (wantarray) {
1.1345    raeburn  3195: 	return ($response->content, $response);
1.944     foxr     3196:     } else {
1.1345    raeburn  3197: 	return $response->content;
1.942     foxr     3198:     }
1.324     www      3199: }
                   3200: 
                   3201: sub externalssi {
                   3202:     my ($url)=@_;
                   3203:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3204:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3205:     if (wantarray) {
                   3206:         return ($response->content, $response);
                   3207:     } else {
                   3208:         return $response->content;
                   3209:     }
1.15      www      3210: }
1.254     www      3211: 
1.1354    raeburn  3212: 
                   3213: # If the local copy of a replicated resource is outdated, trigger a  
                   3214: # connection from the homeserver to flush the delayed queue. If no update 
                   3215: # happens, remove local copies of outdated resource (and corresponding
                   3216: # metadata file).
                   3217: 
1.1352    raeburn  3218: sub remove_stale_resfile {
                   3219:     my ($url) = @_;
1.1354    raeburn  3220:     my $removed;
1.1352    raeburn  3221:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3222:         my $audom = $1;
                   3223:         my $auname = $2;
1.1353    raeburn  3224:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3225:             my $homeserver = &homeserver($auname,$audom);
                   3226:             unless (($homeserver eq 'no_host') ||
                   3227:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3228:                 my $fname = &filelocation('',$url);
                   3229:                 if (-e $fname) {
                   3230:                     my $protocol = $protocol{$homeserver};
                   3231:                     $protocol = 'http' if ($protocol ne 'https');
                   3232:                     my $hostname = &hostname($homeserver);
                   3233:                     if ($hostname) {
                   3234:                         my $uri = &declutter($url);
                   3235:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3236:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3237:                         if ($response->is_success()) {
                   3238:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3239:                             my $locmodtime = (stat($fname))[9];
                   3240:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3241:                                 my $stale;
                   3242:                                 my $answer = &reply('pong',$homeserver);
                   3243:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3244:                                     sleep(0.2);
                   3245:                                     $locmodtime = (stat($fname))[9];
                   3246:                                     if ($locmodtime < $remmodtime) {
                   3247:                                         my $posstransfer = $fname.'.in.transfer';
                   3248:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3249:                                             $removed = 1;
                   3250:                                         } else {
                   3251:                                             $stale = 1;
                   3252:                                         }
                   3253:                                     } else {
                   3254:                                         $removed = 1;
                   3255:                                     }
                   3256:                                 } else {
                   3257:                                     $stale = 1;
                   3258:                                 }
                   3259:                                 if ($stale) {
                   3260:                                     unlink($fname);
                   3261:                                     if ($uri!~/\.meta$/) {
                   3262:                                         unlink($fname.'.meta');
                   3263:                                     }
                   3264:                                     &reply("unsub:$fname",$homeserver);
                   3265:                                     $removed = 1;
1.1352    raeburn  3266:                                 }
                   3267:                             }
                   3268:                         }
                   3269:                     }
                   3270:                 }
                   3271:             }
                   3272:         }
                   3273:     }
1.1354    raeburn  3274:     return $removed;
1.1352    raeburn  3275: }
                   3276: 
1.492     albertel 3277: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3278: 
                   3279: sub allowuploaded {
                   3280:     my ($srcurl,$url)=@_;
                   3281:     $url=&clutter(&declutter($url));
                   3282:     my $dir=$url;
                   3283:     $dir=~s/\/[^\/]+$//;
                   3284:     my %httpref=();
                   3285:     my $httpurl=&hreflocation('',$url);
                   3286:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3287:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3288: }
1.477     raeburn  3289: 
1.1193    raeburn  3290: #
                   3291: # Determine if the current user should be able to edit a particular resource,
                   3292: # when viewing in course context.
                   3293: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3294: #     Functions.
                   3295: # (b) When displaying folder contents in course editor, used to determine if
                   3296: #     "Edit" link will be displayed alongside resource.
                   3297: #
1.1196    raeburn  3298: #  input: six args -- filename (decluttered), course number, course domain,
                   3299: #                   url, symb (if registered) and group (if this is a group
                   3300: #                   item -- e.g., bulletin board, group page etc.).
                   3301: #  output: array of five scalars -- 
1.1193    raeburn  3302: #          $cfile -- url for file editing if editable on current server
                   3303: #          $home -- homeserver of resource (i.e., for author if published,
                   3304: #                                           or course if uploaded.).
                   3305: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3306: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3307: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3308: #
                   3309: 
                   3310: sub can_edit_resource {
1.1194    raeburn  3311:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3312:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3313: #
                   3314: # For aboutme pages user can only edit his/her own.
                   3315: #
1.1199    raeburn  3316:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3317:         my ($sdom,$sname) = ($1,$2);
                   3318:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3319:             $home = $env{'user.home'};
                   3320:             $cfile = $resurl;
                   3321:             if ($env{'form.forceedit'}) {
                   3322:                 $forceview = 1;
                   3323:             } else {
                   3324:                 $forceedit = 1;
                   3325:             }
                   3326:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3327:         } else {
                   3328:             return;
                   3329:         }
                   3330:     }
                   3331: 
                   3332:     if ($env{'request.course.id'}) {
                   3333:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3334:         if ($group ne '') {
                   3335: # if this is a group homepage or group bulletin board, check group privs
                   3336:             my $allowed = 0;
1.1197    raeburn  3337:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3338:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3339:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3340:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3341:                     $allowed = 1;
                   3342:                 }
1.1197    raeburn  3343:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3344:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3345:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3346:                     $allowed = 1;
                   3347:                 }
                   3348:             }
                   3349:             if ($allowed) {
                   3350:                 $home=&homeserver($cnum,$cdom);
                   3351:                 if ($env{'form.forceedit'}) {
                   3352:                     $forceview = 1;
                   3353:                 } else {
                   3354:                     $forceedit = 1;
                   3355:                 }
                   3356:                 $cfile = $resurl;
                   3357:             } else {
                   3358:                 return;
                   3359:             }
                   3360:         } else {
1.1208    raeburn  3361:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3362:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3363:                     return;
                   3364:                 }
                   3365:             } elsif (!$crsedit) {
1.1194    raeburn  3366: #
                   3367: # No edit allowed where CC has switched to student role.
                   3368: #
                   3369:                 return;
                   3370:             }
                   3371:         }
                   3372:     }
                   3373: 
1.1193    raeburn  3374:     if ($file ne '') {
                   3375:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3376:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3377:                 $uploaded = 1;
                   3378:                 $incourse = 1;
1.1193    raeburn  3379:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3380:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3381:                     if ($env{'form.forceedit'}) {
                   3382:                         $forceview = 1;
                   3383:                     } else {
                   3384:                         $forceedit = 1;
                   3385:                     }
1.1194    raeburn  3386:                 }
                   3387:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3388:                 $incourse = 1;
                   3389:                 if ($env{'form.forceedit'}) {
                   3390:                     $forceview = 1;
                   3391:                 } else {
                   3392:                     $forceedit = 1;
                   3393:                 }
                   3394:                 $cfile = $resurl;
                   3395:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3396:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3397:                     $incourse = 1;
                   3398:                     if ($env{'form.forceedit'}) {
                   3399:                         $forceview = 1;
                   3400:                     } else {
                   3401:                         $forceedit = 1;
                   3402:                     }
                   3403:                     $cfile = $resurl;
1.1199    raeburn  3404:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3405:                     $incourse = 1;
                   3406:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3407:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3408:                     $incourse = 1;
1.1199    raeburn  3409:                     if ($env{'form.forceedit'}) {
                   3410:                         $forceview = 1;
                   3411:                     } else {
                   3412:                         $forceedit = 1;
                   3413:                     }
                   3414:                     $cfile = $resurl;
1.1343    raeburn  3415:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3416:                     $incourse = 1;
                   3417:                     if ($env{'form.forceedit'}) {
                   3418:                         $forceview = 1;
                   3419:                     } else {
                   3420:                         $forceedit = 1;
                   3421:                     }
                   3422:                     $cfile = $resurl;
1.1208    raeburn  3423:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3424:                     $incourse = 1;
                   3425:                     if ($env{'form.forceedit'}) {
                   3426:                         $forceview = 1;
                   3427:                     } else {
                   3428:                         $forceedit = 1;
                   3429:                     }
                   3430:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3431:                 }
                   3432:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3433:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3434:                 if (&is_on_map($template)) { 
                   3435:                     $incourse = 1;
                   3436:                     $forceview = 1;
                   3437:                     $cfile = $template;
1.1193    raeburn  3438:                 }
1.1199    raeburn  3439:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3440:                     $incourse = 1;
                   3441:                     if ($env{'form.forceedit'}) {
                   3442:                         $forceview = 1;
                   3443:                     } else {
                   3444:                         $forceedit = 1;
                   3445:                     }
                   3446:                     $cfile = $resurl;
1.1343    raeburn  3447:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3448:                 $incourse = 1;
                   3449:                 if ($env{'form.forceedit'}) {
                   3450:                     $forceview = 1;
                   3451:                 } else {
                   3452:                     $forceedit = 1;
                   3453:                 }
                   3454:                 $cfile = $resurl;
1.1199    raeburn  3455:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3456:                 $incourse = 1;
                   3457:                 $forceview = 1;
                   3458:                 if ($symb) {
                   3459:                     my ($map,$id,$res)=&decode_symb($symb);
                   3460:                     $env{'request.symb'} = $symb;
                   3461:                     $cfile = &clutter($res);
                   3462:                 } else {
                   3463:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3464:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3465:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3466:                         $cfile = '/adm/wrapper'.$escfile;
                   3467:                     } else {
                   3468:                         $escfile =~ s{^http://}{};
                   3469:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3470:                     }
1.1199    raeburn  3471:                 }
1.1234    raeburn  3472:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3473:                 if ($env{'form.forceedit'}) {
                   3474:                     $forceview = 1;
                   3475:                 } else {
                   3476:                     $forceedit = 1;
                   3477:                 }
                   3478:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3479:             }
                   3480:         }
1.1194    raeburn  3481:         if ($uploaded || $incourse) {
                   3482:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3483:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3484:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3485:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3486:             # Check that the user has permission to edit this resource
                   3487:             my $setpriv = 1;
                   3488:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3489:             if (defined($cfudom)) {
                   3490:                 $home=&homeserver($cfuname,$cfudom);
                   3491:                 $cfile=$file;
                   3492:             }
                   3493:         }
1.1194    raeburn  3494:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3495:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3496:             my @ids=&current_machine_ids();
                   3497:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3498:                 $switchserver=1;
                   3499:             }
                   3500:         }
                   3501:     }
1.1194    raeburn  3502:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3503: }
                   3504: 
                   3505: sub is_course_upload {
                   3506:     my ($file,$cnum,$cdom) = @_;
                   3507:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3508:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3509:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3510:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3511:         return 1;
                   3512:     }
                   3513:     return;
                   3514: }
                   3515: 
1.1194    raeburn  3516: sub in_course {
1.1195    raeburn  3517:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3518:     if ($hideprivileged) {
                   3519:         my $skipuser;
1.1219    raeburn  3520:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3521:         my @possdoms = ($cdom);  
                   3522:         if ($coursehash{'checkforpriv'}) { 
                   3523:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3524:         }
                   3525:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3526:             $skipuser = 1;
                   3527:             if ($coursehash{'nothideprivileged'}) {
                   3528:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3529:                     my $user;
                   3530:                     if ($item =~ /:/) {
                   3531:                         $user = $item;
                   3532:                     } else {
                   3533:                         $user = join(':',split(/[\@]/,$item));
                   3534:                     }
                   3535:                     if ($user eq $uname.':'.$udom) {
                   3536:                         undef($skipuser);
                   3537:                         last;
                   3538:                     }
                   3539:                 }
                   3540:             }
                   3541:             if ($skipuser) {
                   3542:                 return 0;
                   3543:             }
                   3544:         }
                   3545:     }
1.1194    raeburn  3546:     $type ||= 'any';
                   3547:     if (!defined($cdom) || !defined($cnum)) {
                   3548:         my $cid  = $env{'request.course.id'};
                   3549:         $cdom = $env{'course.'.$cid.'.domain'};
                   3550:         $cnum = $env{'course.'.$cid.'.num'};
                   3551:     }
                   3552:     my $typesref;
1.1195    raeburn  3553:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3554:         $typesref = ['active','previous','future'];
                   3555:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3556:         $typesref = [$type];
                   3557:     }
                   3558:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3559:                               $typesref,undef,[$cdom]);
                   3560:     my ($tmp) = keys(%roles);
                   3561:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3562:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3563:     if (@course_roles > 0) {
                   3564:         return 1;
                   3565:     }
                   3566:     return 0;
                   3567: }
                   3568: 
1.478     albertel 3569: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3570: # input: action, courseID, current domain, intended
1.637     raeburn  3571: #        path to file, source of file, instruction to parse file for objects,
                   3572: #        ref to hash for embedded objects,
                   3573: #        ref to hash for codebase of java objects.
1.1095    raeburn  3574: #        reference to scalar to accommodate mime type determined
                   3575: #          from File::MMagic if $parser = parse.
1.637     raeburn  3576: #
1.485     raeburn  3577: # output: url to file (if action was uploaddoc), 
                   3578: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3579: #
1.478     albertel 3580: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3581: # course.
1.477     raeburn  3582: #
1.478     albertel 3583: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3584: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3585: #          course's home server.
1.477     raeburn  3586: #
1.478     albertel 3587: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3588: #          be copied from $source (current location) to 
                   3589: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3590: #         and will then be copied to
                   3591: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3592: #         course's home server.
1.485     raeburn  3593: #
1.481     raeburn  3594: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3595: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3596: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3597: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3598: #         in course's home server.
1.637     raeburn  3599: #
1.477     raeburn  3600: 
                   3601: sub process_coursefile {
1.1095    raeburn  3602:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3603:         $mimetype)=@_;
1.477     raeburn  3604:     my $fetchresult;
1.638     albertel 3605:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3606:     if ($action eq 'propagate') {
1.638     albertel 3607:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3608: 			     $home);
1.481     raeburn  3609:     } else {
1.477     raeburn  3610:         my $fpath = '';
                   3611:         my $fname = $file;
1.478     albertel 3612:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3613:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3614:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3615:         if ($action eq 'copy') {
                   3616:             if ($source eq '') {
                   3617:                 $fetchresult = 'no source file';
                   3618:                 return $fetchresult;
                   3619:             } else {
                   3620:                 my $destination = $filepath.'/'.$fname;
                   3621:                 rename($source,$destination);
                   3622:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3623:                                  $home);
1.481     raeburn  3624:             }
                   3625:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3626:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3627:             print $fh $env{'form.'.$source};
1.481     raeburn  3628:             close($fh);
1.637     raeburn  3629:             if ($parser eq 'parse') {
1.1024    raeburn  3630:                 my $mm = new File::MMagic;
1.1095    raeburn  3631:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3632:                 if ($type eq 'text/html') {
1.1024    raeburn  3633:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3634:                     unless ($parse_result eq 'ok') {
                   3635:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3636:                     }
1.637     raeburn  3637:                 }
1.1095    raeburn  3638:                 if (ref($mimetype)) {
                   3639:                     $$mimetype = $type;
                   3640:                 } 
1.637     raeburn  3641:             }
1.477     raeburn  3642:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3643:                                  $home);
1.481     raeburn  3644:             if ($fetchresult eq 'ok') {
                   3645:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3646:             } else {
                   3647:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3648:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3649:                 return '/adm/notfound.html';
                   3650:             }
1.477     raeburn  3651:         }
                   3652:     }
1.485     raeburn  3653:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3654:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3655:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3656:     }
                   3657:     return $fetchresult;
                   3658: }
                   3659: 
1.637     raeburn  3660: sub build_filepath {
                   3661:     my ($fpath) = @_;
                   3662:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3663:     unless ($fpath eq '') {
                   3664:         my @parts=split('/',$fpath);
                   3665:         foreach my $part (@parts) {
                   3666:             $filepath.= '/'.$part;
                   3667:             if ((-e $filepath)!=1) {
                   3668:                 mkdir($filepath,0777);
                   3669:             }
                   3670:         }
                   3671:     }
                   3672:     return $filepath;
                   3673: }
                   3674: 
                   3675: sub store_edited_file {
1.638     albertel 3676:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3677:     my $file = $primary_url;
                   3678:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3679:     my $fpath = '';
                   3680:     my $fname = $file;
                   3681:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3682:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3683:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3684:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3685:     print $fh $content;
                   3686:     close($fh);
1.638     albertel 3687:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3688:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3689: 			  $home);
1.637     raeburn  3690:     if ($$fetchresult eq 'ok') {
                   3691:         return '/uploaded/'.$fpath.'/'.$fname;
                   3692:     } else {
1.638     albertel 3693:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3694: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3695:         return '/adm/notfound.html';
                   3696:     }
                   3697: }
                   3698: 
1.531     albertel 3699: sub clean_filename {
1.831     albertel 3700:     my ($fname,$args)=@_;
1.315     www      3701: # Replace Windows backslashes by forward slashes
1.257     www      3702:     $fname=~s/\\/\//g;
1.831     albertel 3703:     if (!$args->{'keep_path'}) {
                   3704:         # Get rid of everything but the actual filename
                   3705: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3706:     }
1.315     www      3707: # Replace spaces by underscores
                   3708:     $fname=~s/\s+/\_/g;
                   3709: # Replace all other weird characters by nothing
1.831     albertel 3710:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3711: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3712: # numbers
                   3713:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3714:     return $fname;
                   3715: }
1.1051    raeburn  3716: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3717: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3718: # image with the same aspect ratio as the original, but with dimensions which do 
                   3719: # not exceed $resizewidth and $resizeheight.
                   3720:  
1.984     neumanie 3721: sub resizeImage {
1.1051    raeburn  3722:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3723:     my $ima = Image::Magick->new;
                   3724:     my $resized;
                   3725:     if (-e $img_path) {
                   3726:         $ima->Read($img_path);
                   3727:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3728:             my $width = $ima->Get('width');
                   3729:             my $height = $ima->Get('height');
                   3730:             if ($width > $resizewidth) {
                   3731: 	        my $factor = $width/$resizewidth;
                   3732:                 my $newheight = $height/$factor;
                   3733:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3734:                 $resized = 1;
                   3735:             }
                   3736:         }
                   3737:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3738:             my $width = $ima->Get('width');
                   3739:             my $height = $ima->Get('height');
                   3740:             if ($height > $resizeheight) {
                   3741:                 my $factor = $height/$resizeheight;
                   3742:                 my $newwidth = $width/$factor;
                   3743:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3744:                 $resized = 1;
                   3745:             }
                   3746:         }
                   3747:         if ($resized) {
                   3748:             $ima->Write($img_path);
                   3749:         }
                   3750:     }
                   3751:     return;
1.977     amueller 3752: }
                   3753: 
1.608     albertel 3754: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3755: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3756: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3757: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3758: #                                    canceloverwrite, or ''. 
                   3759: #                   if 'coursedoc': upload to the current course
                   3760: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3761: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3762: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3763: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3764: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3765: #        $allfiles - reference to hash for embedded objects
                   3766: #        $codebase - reference to hash for codebase of java objects
                   3767: #        $desuname - username for permanent storage of uploaded file
                   3768: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3769: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3770: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3771: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3772: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3773: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3774: #                    from File::MMagic.
1.858     raeburn  3775: # 
1.686     albertel 3776: # output: url of file in userspace, or error: <message> 
                   3777: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3778: 
1.531     albertel 3779: sub userfileupload {
1.1090    raeburn  3780:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3781:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3782:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3783:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3784:     $fname=&clean_filename($fname);
1.1090    raeburn  3785:     # See if there is anything left
1.257     www      3786:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3787:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3788:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3789:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3790:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3791:         my $now = time;
1.1090    raeburn  3792:         my $filepath;
1.1095    raeburn  3793:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3794:              $filepath = 'tmp/helprequests/'.$now;
                   3795:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3796:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3797:                          '_'.$env{'user.domain'}.'/pending';
                   3798:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3799:             my ($docuname,$docudom);
1.1350    raeburn  3800:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3801:                 $docudom = $destudom;
                   3802:             } else {
                   3803:                 $docudom = $env{'user.domain'};
                   3804:             }
1.1350    raeburn  3805:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3806:                 $docuname = $destuname;
                   3807:             } else {
                   3808:                 $docuname = $env{'user.name'};
                   3809:             }
                   3810:             if (exists($env{'form.group'})) {
                   3811:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3812:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3813:             }
                   3814:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3815:             if ($context eq 'canceloverwrite') {
                   3816:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3817:                 if (-e  $tempfile) {
                   3818:                     my @info = stat($tempfile);
                   3819:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3820:                         unlink($tempfile);
                   3821:                     }
                   3822:                 }
                   3823:                 return;
1.523     raeburn  3824:             }
                   3825:         }
1.1090    raeburn  3826:         # Create the directory if not present
1.741     raeburn  3827:         my @parts=split(/\//,$filepath);
                   3828:         my $fullpath = $perlvar{'lonDaemons'};
                   3829:         for (my $i=0;$i<@parts;$i++) {
                   3830:             $fullpath .= '/'.$parts[$i];
                   3831:             if ((-e $fullpath)!=1) {
                   3832:                 mkdir($fullpath,0777);
                   3833:             }
                   3834:         }
1.1359    raeburn  3835:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3836:         print $fh $env{'form.'.$formname};
                   3837:         close($fh);
1.1090    raeburn  3838:         if ($context eq 'existingfile') {
                   3839:             my @info = stat($fullpath.'/'.$fname);
                   3840:             return ($fullpath.'/'.$fname,$info[9]);
                   3841:         } else {
                   3842:             return $fullpath.'/'.$fname;
                   3843:         }
1.523     raeburn  3844:     }
1.995     raeburn  3845:     if ($subdir eq 'scantron') {
                   3846:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3847:     } else {
1.995     raeburn  3848:         $fname="$subdir/$fname";
                   3849:     }
1.1090    raeburn  3850:     if ($context eq 'coursedoc') {
1.638     albertel 3851: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3852: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3853:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3854:             return &finishuserfileupload($docuname,$docudom,
                   3855: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3856: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3857:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3858:         } else {
1.1218    raeburn  3859:             if ($env{'form.folder'}) {
                   3860:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3861:             }
1.638     albertel 3862:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3863: 				       $fname,$formname,$parser,
1.1095    raeburn  3864: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3865:         }
1.719     banghart 3866:     } elsif (defined($destuname)) {
                   3867:         my $docuname=$destuname;
                   3868:         my $docudom=$destudom;
1.860     raeburn  3869: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3870: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3871:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3872:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3873:     } else {
1.638     albertel 3874:         my $docuname=$env{'user.name'};
                   3875:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3876:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3877:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3878:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3879:         }
1.860     raeburn  3880: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3881: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3882:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3883:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3884:     }
1.271     www      3885: }
                   3886: 
                   3887: sub finishuserfileupload {
1.860     raeburn  3888:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3889:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3890:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3891:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3892:   
1.860     raeburn  3893:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3894:     $file=$fname;
                   3895:     if ($fname=~m|/|) {
                   3896:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3897: 	$path.=$fnamepath.'/';
                   3898:     }
1.259     www      3899:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3900:     my $count;
                   3901:     for ($count=4;$count<=$#parts;$count++) {
                   3902:         $filepath.="/$parts[$count]";
                   3903:         if ((-e $filepath)!=1) {
                   3904: 	    mkdir($filepath,0777);
                   3905:         }
                   3906:     }
1.984     neumanie 3907: 
1.258     www      3908: # Save the file
                   3909:     {
1.1359    raeburn  3910: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3911: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3912: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3913: 	    return '/adm/notfound.html';
                   3914: 	}
1.1090    raeburn  3915:         if ($context eq 'overwrite') {
1.1117    foxr     3916:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3917:             my $target = $filepath.'/'.$file;
                   3918:             if (-e $source) {
                   3919:                 my @info = stat($source);
                   3920:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3921:                     unless (&File::Copy::move($source,$target)) {
                   3922:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3923:                         return "Moving from $source failed";
                   3924:                     }
                   3925:                 } else {
                   3926:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3927:                 }
                   3928:             } else {
                   3929:                 return "Temporary file: $source missing";
                   3930:             }
                   3931:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3932: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3933: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3934: 	    return '/adm/notfound.html';
                   3935: 	}
1.570     albertel 3936: 	close(FH);
1.1051    raeburn  3937:         if ($resizewidth && $resizeheight) {
                   3938:             my $mm = new File::MMagic;
                   3939:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3940:             if ($mime_type =~ m{^image/}) {
                   3941: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3942:             }  
1.977     amueller 3943: 	}
1.258     www      3944:     }
1.1152    raeburn  3945:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3946:         if (ref($mimetype)) {
                   3947:             if ($$mimetype eq '') {
                   3948:                 my $mm = new File::MMagic;
                   3949:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3950:                 $$mimetype = $type;
                   3951:             }
                   3952:         }
                   3953:     }
1.637     raeburn  3954:     if ($parser eq 'parse') {
1.1152    raeburn  3955:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3956:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3957:                                                        $allfiles,$codebase);
                   3958:             unless ($parse_result eq 'ok') {
                   3959:                 &logthis('Failed to parse '.$filepath.$file.
                   3960: 	   	         ' for embedded media: '.$parse_result); 
                   3961:             }
1.637     raeburn  3962:         }
                   3963:     }
1.860     raeburn  3964:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3965:         my $input = $filepath.'/'.$file;
                   3966:         my $output = $filepath.'/'.'tn-'.$file;
                   3967:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  3968:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3969:         system({$args[0]} @args);
1.860     raeburn  3970:         if (-e $filepath.'/'.'tn-'.$file) {
                   3971:             $fetchthumb  = 1; 
                   3972:         }
                   3973:     }
1.858     raeburn  3974:  
1.259     www      3975: # Notify homeserver to grep it
                   3976: #
1.984     neumanie 3977:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3978:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3979:     if ($fetchresult eq 'ok') {
1.860     raeburn  3980:         if ($fetchthumb) {
                   3981:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3982:             if ($thumbresult ne 'ok') {
                   3983:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3984:                          $docuhome.': '.$thumbresult);
                   3985:             }
                   3986:         }
1.259     www      3987: #
1.258     www      3988: # Return the URL to it
1.494     albertel 3989:         return '/uploaded/'.$path.$file;
1.263     www      3990:     } else {
1.494     albertel 3991:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3992: 		 ': '.$fetchresult);
1.263     www      3993:         return '/adm/notfound.html';
1.858     raeburn  3994:     }
1.493     albertel 3995: }
                   3996: 
1.637     raeburn  3997: sub extract_embedded_items {
1.961     raeburn  3998:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3999:     my @state = ();
1.1164    raeburn  4000:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  4001:     my %javafiles = (
                   4002:                       codebase => '',
                   4003:                       code => '',
                   4004:                       archive => ''
                   4005:                     );
                   4006:     my %mediafiles = (
                   4007:                       src => '',
                   4008:                       movie => '',
                   4009:                      );
1.648     raeburn  4010:     my $p;
                   4011:     if ($content) {
                   4012:         $p = HTML::LCParser->new($content);
                   4013:     } else {
1.961     raeburn  4014:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4015:     }
1.641     albertel 4016:     while (my $t=$p->get_token()) {
1.640     albertel 4017: 	if ($t->[0] eq 'S') {
                   4018: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4019: 	    push(@state, $tagname);
1.648     raeburn  4020:             if (lc($tagname) eq 'allow') {
                   4021:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4022:             }
1.640     albertel 4023: 	    if (lc($tagname) eq 'img') {
                   4024: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4025: 	    }
1.886     albertel 4026: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4027:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4028:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4029:                 }
1.886     albertel 4030: 	    }
1.645     raeburn  4031:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4032:                 my $src;
1.645     raeburn  4033:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4034:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4035:                 } else {
1.1164    raeburn  4036:                     if ($attr->{'src'} ne '') {
                   4037:                         $src = $attr->{'src'};
                   4038:                         &add_filetype($allfiles,$src,'src');
                   4039:                     }
                   4040:                 }
                   4041:                 my $text = $p->get_trimmed_text();
                   4042:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4043:                     my @swfargs = split(/,/,$1);
                   4044:                     foreach my $item (@swfargs) {
                   4045:                         $item =~ s/["']//g;
                   4046:                         $item =~ s/^\s+//;
                   4047:                         $item =~ s/\s+$//;
                   4048:                     }
                   4049:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4050:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4051:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4052:                         } else {
                   4053:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4054:                         }
                   4055:                     }
1.645     raeburn  4056:                 }
                   4057:             }
                   4058:             if (lc($tagname) eq 'link') {
                   4059:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4060:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4061:                 }
                   4062:             }
1.640     albertel 4063: 	    if (lc($tagname) eq 'object' ||
                   4064: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4065: 		foreach my $item (keys(%javafiles)) {
                   4066: 		    $javafiles{$item} = '';
                   4067: 		}
1.1164    raeburn  4068:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4069:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4070:                 }
1.640     albertel 4071: 	    }
                   4072: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4073: 		my $name = lc($attr->{'name'});
                   4074: 		foreach my $item (keys(%javafiles)) {
                   4075: 		    if ($name eq $item) {
                   4076: 			$javafiles{$item} = $attr->{'value'};
                   4077: 			last;
                   4078: 		    }
                   4079: 		}
1.1164    raeburn  4080:                 my $pathfrom;
1.640     albertel 4081: 		foreach my $item (keys(%mediafiles)) {
                   4082: 		    if ($name eq $item) {
1.1164    raeburn  4083:                         $pathfrom = $attr->{'value'};
                   4084:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4085: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4086: 			last;
                   4087: 		    }
                   4088: 		}
1.1164    raeburn  4089:                 if ($name eq 'flashvars') {
                   4090:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4091:                 }
                   4092:                 if ($pathfrom ne '') {
                   4093:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4094:                                          $pathfrom);
                   4095:                 }
1.640     albertel 4096: 	    }
                   4097: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4098: 		foreach my $item (keys(%javafiles)) {
                   4099: 		    if ($attr->{$item}) {
                   4100: 			$javafiles{$item} = $attr->{$item};
                   4101: 			last;
                   4102: 		    }
                   4103: 		}
                   4104: 		foreach my $item (keys(%mediafiles)) {
                   4105: 		    if ($attr->{$item}) {
                   4106: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4107: 			last;
                   4108: 		    }
                   4109: 		}
1.1164    raeburn  4110:                 if (lc($tagname) eq 'embed') {
                   4111:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4112:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4113:                                              $attr->{'src'});
                   4114:                     }
                   4115:                 }
1.640     albertel 4116: 	    }
1.1243    raeburn  4117:             if (lc($tagname) eq 'iframe') {
                   4118:                 my $src = $attr->{'src'} ;
                   4119:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4120:                     &add_filetype($allfiles,$src,'src');
                   4121:                 } elsif ($src =~ m{^/}) {
                   4122:                     if ($env{'request.course.id'}) {
                   4123:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4124:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4125:                         my $url = &hreflocation('',$fullpath);
                   4126:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4127:                             my $relpath = $1;
                   4128:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4129:                                 &add_filetype($allfiles,$1,'src');
                   4130:                             }
                   4131:                         }
                   4132:                     }
                   4133:                 }
                   4134:             }
1.1164    raeburn  4135:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4136:                 pop(@state);
1.1164    raeburn  4137:             }
1.640     albertel 4138: 	} elsif ($t->[0] eq 'E') {
                   4139: 	    my ($tagname) = ($t->[1]);
                   4140: 	    if ($javafiles{'codebase'} ne '') {
                   4141: 		$javafiles{'codebase'} .= '/';
                   4142: 	    }  
                   4143: 	    if (lc($tagname) eq 'applet' ||
                   4144: 		lc($tagname) eq 'object' ||
                   4145: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4146: 		) {
                   4147: 		foreach my $item (keys(%javafiles)) {
                   4148: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4149: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4150: 			&add_filetype($allfiles,$file,$item);
                   4151: 		    }
                   4152: 		}
                   4153: 	    } 
                   4154: 	    pop @state;
                   4155: 	}
                   4156:     }
1.1164    raeburn  4157:     foreach my $id (sort(keys(%flashvars))) {
                   4158:         if ($shockwave{$id} ne '') {
                   4159:             my @pairs = split(/\&/,$flashvars{$id});
                   4160:             foreach my $pair (@pairs) {
                   4161:                 my ($key,$value) = split(/\=/,$pair);
                   4162:                 if ($key eq 'thumb') {
                   4163:                     &add_filetype($allfiles,$value,$key);
                   4164:                 } elsif ($key eq 'content') {
                   4165:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4166:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4167:                     if ($ext ne '') {
                   4168:                         &add_filetype($allfiles,$path.$value,$ext);
                   4169:                     }
                   4170:                 }
                   4171:             }
                   4172:         }
                   4173:     }
1.637     raeburn  4174:     return 'ok';
                   4175: }
                   4176: 
1.639     albertel 4177: sub add_filetype {
                   4178:     my ($allfiles,$file,$type)=@_;
                   4179:     if (exists($allfiles->{$file})) {
                   4180: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4181: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4182: 	}
                   4183:     } else {
                   4184: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4185:     }
                   4186: }
                   4187: 
1.1164    raeburn  4188: sub embedded_dependency {
                   4189:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4190:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4191:         if (($identifier ne '') &&
                   4192:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4193:             ($pathfrom ne '')) {
                   4194:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4195:             foreach my $dep (@{$related->{$identifier}}) {
                   4196:                 &add_filetype($allfiles,$path.$dep,'object');
                   4197:             }
                   4198:         }
                   4199:     }
                   4200:     return;
                   4201: }
                   4202: 
1.493     albertel 4203: sub removeuploadedurl {
1.984     neumanie 4204:     my ($url)=@_;	
                   4205:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4206:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4207: }
                   4208: 
                   4209: sub removeuserfile {
                   4210:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4211:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4212:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4213:     if ($result eq 'ok') {	
1.798     raeburn  4214:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4215:             my $metafile = $fname.'.meta';
                   4216:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4217: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4218:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4219:             my $sqlresult = 
1.823     albertel 4220:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4221:                                         'portfolio_metadata',$group,
                   4222:                                         'delete');
1.798     raeburn  4223:         }
                   4224:     }
                   4225:     return $result;
1.257     www      4226: }
1.15      www      4227: 
1.530     albertel 4228: sub mkdiruserfile {
                   4229:     my ($docuname,$docudom,$dir)=@_;
                   4230:     my $home=&homeserver($docuname,$docudom);
                   4231:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4232: }
                   4233: 
1.531     albertel 4234: sub renameuserfile {
                   4235:     my ($docuname,$docudom,$old,$new)=@_;
                   4236:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4237:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4238:                         &escape("$old").':'.&escape("$new"),$home);
                   4239:     if ($result eq 'ok') {
                   4240:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4241:             my $oldmeta = $old.'.meta';
                   4242:             my $newmeta = $new.'.meta';
                   4243:             my $metaresult = 
                   4244:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4245: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4246:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4247:             my $sqlresult = 
1.823     albertel 4248:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4249:                                         'portfolio_metadata',$group,
                   4250:                                         'delete');
1.798     raeburn  4251:         }
                   4252:     }
                   4253:     return $result;
1.531     albertel 4254: }
                   4255: 
1.14      www      4256: # ------------------------------------------------------------------------- Log
                   4257: 
                   4258: sub log {
                   4259:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4260:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4261: }
                   4262: 
                   4263: # ------------------------------------------------------------------ Course Log
1.352     www      4264: #
                   4265: # This routine flushes several buffers of non-mission-critical nature
                   4266: #
1.157     www      4267: 
                   4268: sub flushcourselogs {
1.352     www      4269:     &logthis('Flushing log buffers');
                   4270: #
                   4271: # course logs
                   4272: # This is a log of all transactions in a course, which can be used
                   4273: # for data mining purposes
                   4274: #
                   4275: # It also collects the courseid database, which lists last transaction
                   4276: # times and course titles for all courseids
                   4277: #
                   4278:     my %courseidbuffer=();
1.921     raeburn  4279:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4280:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4281: 		          &escape($courselogs{$crsid}),
                   4282: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4283: 	    delete $courselogs{$crsid};
                   4284:         } else {
                   4285:             &logthis('Failed to flush log buffer for '.$crsid);
                   4286:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4287:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4288:                         " exceeded maximum size, deleting.</font>");
                   4289:                delete $courselogs{$crsid};
                   4290:             }
1.352     www      4291:         }
1.920     raeburn  4292:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4293:             'description' => $coursedescrbuf{$crsid},
                   4294:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4295:             'type'        => $coursetypebuf{$crsid},
                   4296:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4297:         };
1.191     harris41 4298:     }
1.352     www      4299: #
                   4300: # Write course id database (reverse lookup) to homeserver of courses 
                   4301: # Is used in pickcourse
                   4302: #
1.840     albertel 4303:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4304:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4305:                                     $courseidbuffer{$crs_home},
                   4306:                                     $crs_home,'timeonly');
1.352     www      4307:     }
                   4308: #
                   4309: # File accesses
                   4310: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4311: #
1.449     matthew  4312:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4313:         if ($entry =~ /___count$/) {
                   4314:             my ($dom,$name);
1.807     albertel 4315:             ($dom,$name,undef)=
1.811     albertel 4316: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4317:             if (! defined($dom) || $dom eq '' || 
                   4318:                 ! defined($name) || $name eq '') {
1.620     albertel 4319:                 my $cid = $env{'request.course.id'};
                   4320:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4321:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4322:             }
1.450     matthew  4323:             my $value = $accesshash{$entry};
                   4324:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4325:             my %temphash=($url => $value);
1.449     matthew  4326:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4327:             if ($result eq 'ok') {
                   4328:                 delete $accesshash{$entry};
                   4329:             }
                   4330:         } else {
1.811     albertel 4331:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4332:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4333:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4334:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4335:                 delete $accesshash{$entry};
                   4336:             }
1.185     www      4337:         }
1.191     harris41 4338:     }
1.352     www      4339: #
                   4340: # Roles
                   4341: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4342: #
1.800     albertel 4343:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4344:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4345: 	    split(/\:/,$entry);
                   4346:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4347:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4348:                 $rudom,$runame) eq 'ok') {
                   4349: 	    delete $userrolehash{$entry};
                   4350:         }
                   4351:     }
1.662     raeburn  4352: #
1.1334    raeburn  4353: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4354: #
                   4355:     my %domrolebuffer = ();
1.1000    raeburn  4356:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4357:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4358:         if ($domrolebuffer{$rudom}) {
                   4359:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4360:                       '='.&escape($domainrolehash{$entry});
                   4361:         } else {
                   4362:             $domrolebuffer{$rudom}.=&escape($entry).
                   4363:                       '='.&escape($domainrolehash{$entry});
                   4364:         }
                   4365:         delete $domainrolehash{$entry};
                   4366:     }
                   4367:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4368: 	my %servers;
                   4369: 	if (defined(&domain($dom,'primary'))) {
                   4370: 	    my $primary=&domain($dom,'primary');
                   4371: 	    my $hostname=&hostname($primary);
                   4372: 	    $servers{$primary} = $hostname;
                   4373: 	} else { 
                   4374: 	    %servers = &get_servers($dom,'library');
                   4375: 	}
1.841     albertel 4376: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4377: 	    if (&reply('domroleput:'.$dom.':'.
                   4378: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4379: 		last;
                   4380: 	    } else {  
1.841     albertel 4381: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4382: 	    }
1.662     raeburn  4383:         }
                   4384:     }
1.186     www      4385:     $dumpcount++;
1.157     www      4386: }
                   4387: 
                   4388: sub courselog {
                   4389:     my $what=shift;
1.158     www      4390:     $what=time.':'.$what;
1.620     albertel 4391:     unless ($env{'request.course.id'}) { return ''; }
                   4392:     $coursedombuf{$env{'request.course.id'}}=
                   4393:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4394:     $coursenumbuf{$env{'request.course.id'}}=
                   4395:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4396:     $coursehombuf{$env{'request.course.id'}}=
                   4397:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4398:     $coursedescrbuf{$env{'request.course.id'}}=
                   4399:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4400:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4401:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4402:     $courseownerbuf{$env{'request.course.id'}}=
                   4403:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4404:     $coursetypebuf{$env{'request.course.id'}}=
                   4405:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4406:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4407: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4408:     } else {
1.620     albertel 4409: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4410:     }
1.620     albertel 4411:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4412: 	&flushcourselogs();
                   4413:     }
1.158     www      4414: }
                   4415: 
                   4416: sub courseacclog {
                   4417:     my $fnsymb=shift;
1.620     albertel 4418:     unless ($env{'request.course.id'}) { return ''; }
                   4419:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4420:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4421:         $what.=':POST';
1.583     matthew  4422:         # FIXME: Probably ought to escape things....
1.800     albertel 4423: 	foreach my $key (keys(%env)) {
                   4424:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4425:                 my $formitem = $1;
                   4426:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4427:                     $what.=':'.$formitem.'='.$env{$key};
                   4428:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4429:                     $what.=':'.$formitem.'='.$env{$key};
                   4430:                 }
1.158     www      4431:             }
1.191     harris41 4432:         }
1.583     matthew  4433:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4434:         # FIXME: We should not be depending on a form parameter that someone
                   4435:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4436:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4437:             $what.= ':POST';
                   4438:             # FIXME: Probably ought to escape things....
                   4439:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4440:                                  'crsdiscuss') {
1.620     albertel 4441:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4442:             }
                   4443:         }
1.158     www      4444:     }
                   4445:     &courselog($what);
1.149     www      4446: }
                   4447: 
1.185     www      4448: sub countacc {
                   4449:     my $url=&declutter(shift);
1.458     matthew  4450:     return if (! defined($url) || $url eq '');
1.620     albertel 4451:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4452: #
                   4453: # Mark that this url was used in this course
                   4454: #
1.620     albertel 4455:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4456: #
                   4457: # Increase the access count for this resource in this child process
                   4458: #
1.281     www      4459:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4460:     $accesshash{$key}++;
1.185     www      4461: }
1.349     www      4462: 
1.361     www      4463: sub linklog {
                   4464:     my ($from,$to)=@_;
                   4465:     $from=&declutter($from);
                   4466:     $to=&declutter($to);
                   4467:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4468:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4469: }
1.1160    www      4470: 
                   4471: sub statslog {
                   4472:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4473:     if ($users<2) { return; }
                   4474:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4475:             'course'       => $env{'request.course.id'},
                   4476:             'sections'     => '"all"',
                   4477:             'num_students' => $users,
                   4478:             'part'         => $part,
                   4479:             'symb'         => $symb,
                   4480:             'mean_tries'   => $av_attempts,
                   4481:             'deg_of_diff'  => $degdiff});
                   4482:     foreach my $key (keys(%dynstore)) {
                   4483:         $accesshash{$key}=$dynstore{$key};
                   4484:     }
                   4485: }
1.361     www      4486:   
1.349     www      4487: sub userrolelog {
                   4488:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4489:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4490:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4491:        $userrolehash
                   4492:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4493:                     =$tend.':'.$tstart;
1.662     raeburn  4494:     }
1.1169    droeschl 4495:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4496:        $userrolehash
                   4497:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4498:                     =$tend.':'.$tstart;
                   4499:     }
1.1334    raeburn  4500:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4501:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4502:        $domainrolehash
                   4503:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4504:                     = $tend.':'.$tstart;
                   4505:     }
1.351     www      4506: }
                   4507: 
1.957     raeburn  4508: sub courserolelog {
                   4509:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4510:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4511:         my $cdom = $1;
                   4512:         my $cnum = $2;
                   4513:         my $sec = $3;
                   4514:         my $namespace = 'rolelog';
                   4515:         my %storehash = (
                   4516:                            role    => $trole,
                   4517:                            start   => $tstart,
                   4518:                            end     => $tend,
                   4519:                            selfenroll => $selfenroll,
                   4520:                            context    => $context,
                   4521:                         );
                   4522:         if ($trole eq 'gr') {
                   4523:             $namespace = 'groupslog';
                   4524:             $storehash{'group'} = $sec;
                   4525:         } else {
                   4526:             $storehash{'section'} = $sec;
                   4527:         }
1.1188    raeburn  4528:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4529:                    $domain,$cnum,$cdom);
1.1184    raeburn  4530:         if (($trole ne 'st') || ($sec ne '')) {
                   4531:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4532:         }
                   4533:     }
                   4534:     return;
                   4535: }
                   4536: 
1.1184    raeburn  4537: sub domainrolelog {
                   4538:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4539:     if ($area =~ m{^/($match_domain)/$}) {
                   4540:         my $cdom = $1;
                   4541:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4542:         my $namespace = 'rolelog';
                   4543:         my %storehash = (
                   4544:                            role    => $trole,
                   4545:                            start   => $tstart,
                   4546:                            end     => $tend,
                   4547:                            context => $context,
                   4548:                         );
1.1188    raeburn  4549:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4550:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4551:     }
                   4552:     return;
                   4553: 
                   4554: }
                   4555: 
                   4556: sub coauthorrolelog {
                   4557:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4558:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4559:         my $audom = $1;
                   4560:         my $auname = $2;
                   4561:         my $namespace = 'rolelog';
                   4562:         my %storehash = (
                   4563:                            role    => $trole,
                   4564:                            start   => $tstart,
                   4565:                            end     => $tend,
                   4566:                            context => $context,
                   4567:                         );
1.1188    raeburn  4568:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4569:                    $domain,$auname,$audom);
1.1184    raeburn  4570:     }
                   4571:     return;
                   4572: }
                   4573: 
1.351     www      4574: sub get_course_adv_roles {
1.948     raeburn  4575:     my ($cid,$codes) = @_;
1.620     albertel 4576:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4577:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4578:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4579:     my %nothide=();
1.800     albertel 4580:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4581:         if ($user !~ /:/) {
                   4582: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4583:         } else {
                   4584:             $nothide{$user}=1;
                   4585:         }
1.470     www      4586:     }
1.1219    raeburn  4587:     my @possdoms = ($coursehash{'domain'});
                   4588:     if ($coursehash{'checkforpriv'}) {
                   4589:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4590:     }
1.351     www      4591:     my %returnhash=();
                   4592:     my %dumphash=
                   4593:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4594:     my $now=time;
1.997     raeburn  4595:     my %privileged;
1.1000    raeburn  4596:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4597: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4598:         if (($tstart) && ($tstart<0)) { next; }
                   4599:         if (($tend) && ($tend<$now)) { next; }
                   4600:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4601:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4602: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4603:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4604:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4605: 	if ($role eq 'cr') { next; }
1.948     raeburn  4606:         if ($codes) {
                   4607:             if ($section) { $role .= ':'.$section; }
                   4608:             if ($returnhash{$role}) {
                   4609:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4610:             } else {
                   4611:                 $returnhash{$role}=$username.':'.$domain;
                   4612:             }
1.351     www      4613:         } else {
1.988     raeburn  4614:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4615:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4616:             if ($returnhash{$key}) {
                   4617: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4618:             } else {
                   4619:                 $returnhash{$key}=$username.':'.$domain;
                   4620:             }
1.351     www      4621:         }
1.948     raeburn  4622:     }
1.400     www      4623:     return %returnhash;
                   4624: }
                   4625: 
                   4626: sub get_my_roles {
1.937     raeburn  4627:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4628:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4629:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4630:     my (%dumphash,%nothide);
1.1086    raeburn  4631:     if ($context eq 'userroles') {
1.1166    raeburn  4632:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4633:     } else {
1.1219    raeburn  4634:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4635:         if ($hidepriv) {
                   4636:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4637:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4638:                 if ($user !~ /:/) {
                   4639:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4640:                 } else {
                   4641:                     $nothide{$user} = 1;
                   4642:                 }
                   4643:             }
                   4644:         }
1.858     raeburn  4645:     }
1.400     www      4646:     my %returnhash=();
                   4647:     my $now=time;
1.999     raeburn  4648:     my %privileged;
1.800     albertel 4649:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4650:         my ($role,$tend,$tstart);
                   4651:         if ($context eq 'userroles') {
1.1149    raeburn  4652:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4653: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4654:         } else {
                   4655:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4656:         }
1.400     www      4657:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4658:         my $status = 'active';
1.939     raeburn  4659:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4660:             $status = 'previous';
                   4661:         } 
                   4662:         if (($tstart) && ($now<$tstart)) {
                   4663:             $status = 'future';
                   4664:         }
                   4665:         if (ref($types) eq 'ARRAY') {
                   4666:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4667:                 next;
                   4668:             } 
                   4669:         } else {
                   4670:             if ($status ne 'active') {
                   4671:                 next;
                   4672:             }
                   4673:         }
1.867     raeburn  4674:         my ($rolecode,$username,$domain,$section,$area);
                   4675:         if ($context eq 'userroles') {
1.1186    raeburn  4676:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4677:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4678:         } else {
                   4679:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4680:         }
1.832     raeburn  4681:         if (ref($roledoms) eq 'ARRAY') {
                   4682:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4683:                 next;
                   4684:             }
                   4685:         }
                   4686:         if (ref($roles) eq 'ARRAY') {
                   4687:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4688:                 if ($role =~ /^cr\//) {
                   4689:                     if (!grep(/^cr$/,@{$roles})) {
                   4690:                         next;
                   4691:                     }
1.1104    raeburn  4692:                 } elsif ($role =~ /^gr\//) {
                   4693:                     if (!grep(/^gr$/,@{$roles})) {
                   4694:                         next;
                   4695:                     }
1.922     raeburn  4696:                 } else {
                   4697:                     next;
                   4698:                 }
1.832     raeburn  4699:             }
1.867     raeburn  4700:         }
1.937     raeburn  4701:         if ($hidepriv) {
1.1219    raeburn  4702:             my @privroles = ('dc','su');
1.999     raeburn  4703:             if ($context eq 'userroles') {
1.1219    raeburn  4704:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4705:             } else {
1.1219    raeburn  4706:                 my $possdoms = [$domain];
                   4707:                 if (ref($roledoms) eq 'ARRAY') {
                   4708:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4709:                 }
1.1219    raeburn  4710:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4711:                     if (!$nothide{$username.':'.$domain}) {
                   4712:                         next;
                   4713:                     }
                   4714:                 }
1.937     raeburn  4715:             }
                   4716:         }
1.933     raeburn  4717:         if ($withsec) {
                   4718:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4719:                 $tstart.':'.$tend;
                   4720:         } else {
                   4721:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4722:         }
1.832     raeburn  4723:     }
1.373     www      4724:     return %returnhash;
1.399     www      4725: }
                   4726: 
1.1333    raeburn  4727: sub get_all_adhocroles {
                   4728:     my ($dom) = @_;
                   4729:     my @roles_by_num = ();
                   4730:     my %domdefaults = &get_domain_defaults($dom);
                   4731:     my (%description,%access_in_dom,%access_info);
                   4732:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4733:         my $count = 0;
                   4734:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4735:         my %ordered;
                   4736:         foreach my $role (sort(keys(%domcurrent))) {
                   4737:             my ($order,$desc,$access_in_dom);
                   4738:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4739:                 $order = $domcurrent{$role}{'order'};
                   4740:                 $desc = $domcurrent{$role}{'desc'};
                   4741:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4742:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4743:             }
                   4744:             if ($order eq '') {
                   4745:                 $order = $count;
                   4746:             }
                   4747:             $ordered{$order} = $role;
                   4748:             if ($desc ne '') {
                   4749:                 $description{$role} = $desc;
                   4750:             } else {
                   4751:                 $description{$role}= $role;
                   4752:             }
                   4753:             $count++;
                   4754:         }
                   4755:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4756:             push(@roles_by_num,$ordered{$item});
                   4757:         }
                   4758:     }
                   4759:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4760: }
                   4761: 
1.1332    raeburn  4762: sub get_my_adhocroles {
1.1333    raeburn  4763:     my ($cid,$checkreg) = @_;
                   4764:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4765:     if ($env{'request.course.id'} eq $cid) {
                   4766:         $cdom = $env{'course.'.$cid.'.domain'};
                   4767:         $cnum = $env{'course.'.$cid.'.num'};
                   4768:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4769:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4770:         $cdom = $1;
                   4771:         $cnum = $2;
                   4772:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4773:                                      $cdom,$cnum);
                   4774:     }
                   4775:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4776:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4777:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4778:         if ($rosterhash{$user} ne '') {
                   4779:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4780:             return ([],{}) if ($type eq 'auto');
                   4781:         }
                   4782:     }
                   4783:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4784:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4785:             my $then=$env{'user.login.time'};
                   4786:             my $update=$env{'user.update.time'};
1.1335    raeburn  4787:             if (!$update) {
                   4788:                 $update = $then;
                   4789:             }
                   4790:             my @liveroles;
1.1334    raeburn  4791:             foreach my $role ('dh','da') {
                   4792:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4793:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4794:                     my $limit = $update;
                   4795:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4796:                         $limit = $then;
                   4797:                     }
1.1335    raeburn  4798:                     my $activerole = 1;
                   4799:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4800:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4801:                     if ($activerole) {
                   4802:                         push(@liveroles,$role);
                   4803:                     }
1.1334    raeburn  4804:                 }
1.1332    raeburn  4805:             }
1.1335    raeburn  4806:             if (@liveroles) {
1.1332    raeburn  4807:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4808:                     my ($accessref,$accessinfo,%access_in_dom);
                   4809:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4810:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4811:                         if (@{$roles_by_num}) {
1.1332    raeburn  4812:                             my %settings;
                   4813:                             if ($env{'request.course.id'} eq $cid) {
                   4814:                                 foreach my $envkey (keys(%env)) {
                   4815:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4816:                                         $settings{$1} = $env{$envkey};
                   4817:                                     }
                   4818:                                 }
                   4819:                             } else {
                   4820:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4821:                             }
                   4822:                             my %setincrs;
                   4823:                             if ($settings{'internal.adhocaccess'}) {
                   4824:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4825:                             }
                   4826:                             my @statuses;
                   4827:                             if ($env{'environment.inststatus'}) {
                   4828:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4829:                             }
                   4830:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4831:                             if (ref($accessref) eq 'HASH') {
                   4832:                                 %access_in_dom = %{$accessref};
                   4833:                             }
                   4834:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4835:                                 my ($curraccess,@okstatus,@personnel);
                   4836:                                 if ($setincrs{$role}) {
                   4837:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4838:                                     if ($curraccess eq 'status') {
                   4839:                                         @okstatus = split(/\&/,$rest);
                   4840:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4841:                                         @personnel = split(/\&/,$rest);
                   4842:                                     }
                   4843:                                 } else {
                   4844:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4845:                                     if (ref($accessinfo) eq 'HASH') {
                   4846:                                         if ($curraccess eq 'status') {
                   4847:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4848:                                                 @okstatus = @{$accessinfo->{$role}};
                   4849:                                             }
                   4850:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4851:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4852:                                                 @personnel = @{$accessinfo->{$role}};
                   4853:                                             }
1.1332    raeburn  4854:                                         }
                   4855:                                     }
                   4856:                                 }
                   4857:                                 if ($curraccess eq 'none') {
                   4858:                                     next;
                   4859:                                 } elsif ($curraccess eq 'all') {
                   4860:                                     push(@possroles,$role);
1.1336    raeburn  4861:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4862:                                     if (grep(/^dh$/,@liveroles)) {
                   4863:                                         push(@possroles,$role);
                   4864:                                     } else {
                   4865:                                         next;
                   4866:                                     }
1.1336    raeburn  4867:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4868:                                     if (grep(/^da$/,@liveroles)) {
                   4869:                                         push(@possroles,$role);
                   4870:                                     } else {
                   4871:                                         next;
                   4872:                                     }
1.1332    raeburn  4873:                                 } elsif ($curraccess eq 'status') {
                   4874:                                     if (@okstatus) {
                   4875:                                         if (!@statuses) {
                   4876:                                             if (grep(/^default$/,@okstatus)) {
                   4877:                                                 push(@possroles,$role);
                   4878:                                             }
                   4879:                                         } else {
                   4880:                                             foreach my $status (@okstatus) {
                   4881:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4882:                                                     push(@possroles,$role);
                   4883:                                                     last;
                   4884:                                                 }
                   4885:                                             }
                   4886:                                         }
                   4887:                                     }
                   4888:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4889:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4890:                                         if ($curraccess eq 'exc') {
                   4891:                                             push(@possroles,$role);
                   4892:                                         }
                   4893:                                     } elsif ($curraccess eq 'inc') {
                   4894:                                         push(@possroles,$role);
                   4895:                                     }
                   4896:                                 }
                   4897:                             }
                   4898:                         }
                   4899:                     }
                   4900:                 }
                   4901:             }
                   4902:         }
                   4903:     }
1.1333    raeburn  4904:     unless (ref($description) eq 'HASH') {
                   4905:         if (ref($roles_by_num) eq 'ARRAY') {
                   4906:             my %desc;
                   4907:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4908:             $description = \%desc;
                   4909:         } else {
                   4910:             $description = {};
                   4911:         }
                   4912:     }
                   4913:     return (\@possroles,$description);
1.1332    raeburn  4914: }
                   4915: 
1.399     www      4916: # ----------------------------------------------------- Frontpage Announcements
                   4917: #
                   4918: #
                   4919: 
                   4920: sub postannounce {
                   4921:     my ($server,$text)=@_;
1.844     albertel 4922:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4923:     unless ($text=~/\w/) { $text=''; }
                   4924:     return &reply('setannounce:'.&escape($text),$server);
                   4925: }
                   4926: 
                   4927: sub getannounce {
1.448     albertel 4928: 
1.1359    raeburn  4929:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4930: 	my $announcement='';
1.800     albertel 4931: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4932: 	close($fh);
1.399     www      4933: 	if ($announcement=~/\w/) { 
                   4934: 	    return 
                   4935:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4936:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4937: 	} else {
                   4938: 	    return '';
                   4939: 	}
                   4940:     } else {
                   4941: 	return '';
                   4942:     }
1.351     www      4943: }
1.353     www      4944: 
                   4945: # ---------------------------------------------------------- Course ID routines
                   4946: # Deal with domain's nohist_courseid.db files
                   4947: #
                   4948: 
                   4949: sub courseidput {
1.921     raeburn  4950:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4951:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4952:     my $outcome;
                   4953:     if ($caller eq 'timeonly') {
                   4954:         my $cids = '';
                   4955:         foreach my $item (keys(%$storehash)) {
                   4956:             $cids.=&escape($item).'&';
                   4957:         }
                   4958:         $cids=~s/\&$//;
                   4959:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4960:                           $coursehome);       
                   4961:     } else {
                   4962:         my $items = '';
                   4963:         foreach my $item (keys(%$storehash)) {
                   4964:             $items.= &escape($item).'='.
                   4965:                      &freeze_escape($$storehash{$item}).'&';
                   4966:         }
                   4967:         $items=~s/\&$//;
                   4968:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4969:                           $coursehome);
1.918     raeburn  4970:     }
                   4971:     if ($outcome eq 'unknown_cmd') {
                   4972:         my $what;
                   4973:         foreach my $cid (keys(%$storehash)) {
                   4974:             $what .= &escape($cid).'=';
1.921     raeburn  4975:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4976:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4977:             }
                   4978:             $what =~ s/\:$/&/;
                   4979:         }
                   4980:         $what =~ s/\&$//;  
                   4981:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4982:     } else {
                   4983:         return $outcome;
                   4984:     }
1.353     www      4985: }
                   4986: 
                   4987: sub courseiddump {
1.921     raeburn  4988:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4989:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4990:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4991:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4992:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4993:     my $as_hash = 1;
                   4994:     my %returnhash;
                   4995:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4996:     my %libserv = &all_library();
                   4997:     foreach my $tryserver (keys(%libserv)) {
                   4998:         if ( (  $hostidflag == 1 
                   4999: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   5000: 	     || (!defined($hostidflag)) ) {
                   5001: 
1.918     raeburn  5002: 	    if (($domfilter eq '') ||
                   5003: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5004:                 my $rep;
                   5005:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5006:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5007:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5008:                                 &escape($descfilter), &escape($instcodefilter), 
                   5009:                                 &escape($ownerfilter), &escape($coursefilter),
                   5010:                                 &escape($typefilter), &escape($regexp_ok), 
                   5011:                                 $as_hash, &escape($selfenrollonly), 
                   5012:                                 &escape($catfilter), $showhidden, $caller, 
                   5013:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5014:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5015:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5016:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5017:                 } else {
                   5018:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5019:                              $sincefilter.':'.&escape($descfilter).':'.
                   5020:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5021:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5022:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5023:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5024:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5025:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5026:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5027:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5028:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5029:                 }
                   5030:                      
1.918     raeburn  5031:                 my @pairs=split(/\&/,$rep);
                   5032:                 foreach my $item (@pairs) {
                   5033:                     my ($key,$value)=split(/\=/,$item,2);
                   5034:                     $key = &unescape($key);
                   5035:                     next if ($key =~ /^error: 2 /);
                   5036:                     my $result = &thaw_unescape($value);
                   5037:                     if (ref($result) eq 'HASH') {
                   5038:                         $returnhash{$key}=$result;
                   5039:                     } else {
1.921     raeburn  5040:                         my @responses = split(/:/,$value);
                   5041:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5042:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5043:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5044:                         }
1.1008    raeburn  5045:                     }
1.353     www      5046:                 }
                   5047:             }
                   5048:         }
                   5049:     }
                   5050:     return %returnhash;
                   5051: }
                   5052: 
1.1055    raeburn  5053: sub courselastaccess {
                   5054:     my ($cdom,$cnum,$hostidref) = @_;
                   5055:     my %returnhash;
                   5056:     if ($cdom && $cnum) {
                   5057:         my $chome = &homeserver($cnum,$cdom);
                   5058:         if ($chome ne 'no_host') {
                   5059:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5060:             &extract_lastaccess(\%returnhash,$rep);
                   5061:         }
                   5062:     } else {
                   5063:         if (!$cdom) { $cdom=''; }
                   5064:         my %libserv = &all_library();
                   5065:         foreach my $tryserver (keys(%libserv)) {
                   5066:             if (ref($hostidref) eq 'ARRAY') {
                   5067:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5068:             } 
                   5069:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5070:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5071:                 &extract_lastaccess(\%returnhash,$rep);
                   5072:             }
                   5073:         }
                   5074:     }
                   5075:     return %returnhash;
                   5076: }
                   5077: 
                   5078: sub extract_lastaccess {
                   5079:     my ($returnhash,$rep) = @_;
                   5080:     if (ref($returnhash) eq 'HASH') {
                   5081:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5082:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5083:                  $rep eq '') {
                   5084:             my @pairs=split(/\&/,$rep);
                   5085:             foreach my $item (@pairs) {
                   5086:                 my ($key,$value)=split(/\=/,$item,2);
                   5087:                 $key = &unescape($key);
                   5088:                 next if ($key =~ /^error: 2 /);
                   5089:                 $returnhash->{$key} = &thaw_unescape($value);
                   5090:             }
                   5091:         }
                   5092:     }
                   5093:     return;
                   5094: }
                   5095: 
1.658     raeburn  5096: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5097: 
                   5098: sub dcmailput {
1.685     raeburn  5099:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5100:     my $status = &Apache::lonnet::critical(
1.740     www      5101:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5102:        &escape($message),$server);
1.662     raeburn  5103:     return $status;
                   5104: }
                   5105: 
1.658     raeburn  5106: sub dcmaildump {
                   5107:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5108:     my %returnhash=();
1.846     albertel 5109: 
                   5110:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5111:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5112:                                                          &escape($enddate).':';
                   5113: 	my @esc_senders=map { &escape($_)} @$senders;
                   5114: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5115: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5116:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5117:             if (($key) && ($value)) {
                   5118:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5119:             }
                   5120:         }
                   5121:     }
                   5122:     return %returnhash;
                   5123: }
1.662     raeburn  5124: # ---------------------------------------------------------- Domain roles
                   5125: 
                   5126: sub get_domain_roles {
                   5127:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5128:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5129:         $startdate = '.';
                   5130:     }
1.1018    raeburn  5131:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5132:         $enddate = '.';
                   5133:     }
1.922     raeburn  5134:     my $rolelist;
                   5135:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5136:         $rolelist = join('&',@{$roles});
1.922     raeburn  5137:     }
1.662     raeburn  5138:     my %personnel = ();
1.841     albertel 5139: 
                   5140:     my %servers = &get_servers($dom,'library');
                   5141:     foreach my $tryserver (keys(%servers)) {
                   5142: 	%{$personnel{$tryserver}}=();
                   5143: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5144: 					    &escape($startdate).':'.
                   5145: 					    &escape($enddate).':'.
                   5146: 					    &escape($rolelist), $tryserver))) {
                   5147: 	    my ($key,$value) = split(/\=/,$line,2);
                   5148: 	    if (($key) && ($value)) {
                   5149: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5150: 	    }
                   5151: 	}
1.662     raeburn  5152:     }
                   5153:     return %personnel;
                   5154: }
1.658     raeburn  5155: 
1.1332    raeburn  5156: sub get_active_domroles {
                   5157:     my ($dom,$roles) = @_;
                   5158:     return () unless (ref($roles) eq 'ARRAY');
                   5159:     my $now = time;
                   5160:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5161:     my %domroles;
                   5162:     foreach my $server (keys(%dompersonnel)) {
                   5163:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5164:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5165:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5166:         }
                   5167:     }
                   5168:     return %domroles;
                   5169: }
                   5170: 
1.1057    www      5171: # ----------------------------------------------------------- Interval timing 
1.149     www      5172: 
1.1153    www      5173: {
                   5174: # Caches needed for speedup of navmaps
                   5175: # We don't want to cache this for very long at all (5 seconds at most)
                   5176: # 
                   5177: # The user for whom we cache
                   5178: my $cachedkey='';
                   5179: # The cached times for this user
                   5180: my %cachedtimes=();
                   5181: # When this was last done
1.1282    raeburn  5182: my $cachedtime='';
1.1153    www      5183: 
                   5184: sub load_all_first_access {
1.1308    raeburn  5185:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5186:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5187:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5188:         (!$ignorecache)) {
1.1154    raeburn  5189:         return;
                   5190:     }
                   5191:     $cachedtime=time;
                   5192:     $cachedkey=$uname.':'.$udom;
                   5193:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5194: }
                   5195: 
1.504     albertel 5196: sub get_first_access {
1.1308    raeburn  5197:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5198:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5199:     if ($argsymb) { $symb=$argsymb; }
                   5200:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5201:     if ($argmap) { $map = $argmap; }
1.926     albertel 5202:     if ($type eq 'course') {
                   5203: 	$res='course';
                   5204:     } elsif ($type eq 'map') {
1.588     albertel 5205: 	$res=&symbread($map);
                   5206:     } else {
                   5207: 	$res=$symb;
                   5208:     }
1.1308    raeburn  5209:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5210:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5211: }
                   5212: 
                   5213: sub set_first_access {
1.1162    raeburn  5214:     my ($type,$interval)=@_;
1.790     albertel 5215:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5216:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5217:     if ($type eq 'course') {
                   5218: 	$res='course';
                   5219:     } elsif ($type eq 'map') {
1.588     albertel 5220: 	$res=&symbread($map);
                   5221:     } else {
                   5222: 	$res=$symb;
                   5223:     }
1.1153    www      5224:     $cachedkey='';
1.1162    raeburn  5225:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 5226:     if (!$firstaccess) {
1.1162    raeburn  5227:         my $start = time;
                   5228: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5229:                           $udom,$uname);
                   5230:         if ($putres eq 'ok') {
                   5231:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5232:                  $udom,$uname); 
                   5233:             &appenv(
                   5234:                      {
                   5235:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5236:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5237:                      }
                   5238:                   );
1.1365    raeburn  5239:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5240:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5241:             }
1.1162    raeburn  5242:         }
                   5243:         return $putres;
1.505     albertel 5244:     }
                   5245:     return 'already_set';
1.504     albertel 5246: }
1.1153    www      5247: }
1.1282    raeburn  5248: 
1.110     www      5249: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5250: 
                   5251: sub expirespread {
                   5252:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5253:     my $cid=$env{'request.course.id'}; 
1.110     www      5254:     if ($cid) {
                   5255:        my $now=time;
                   5256:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5257:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5258:                             $env{'course.'.$cid.'.num'}.
1.110     www      5259: 	        	    ':nohist_expirationdates:'.
                   5260:                             &escape($key).'='.$now,
1.620     albertel 5261:                             $env{'course.'.$cid.'.home'})
1.110     www      5262:     }
                   5263:     return 'ok';
1.14      www      5264: }
                   5265: 
1.109     www      5266: # ----------------------------------------------------- Devalidate Spreadsheets
                   5267: 
                   5268: sub devalidate {
1.325     www      5269:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5270:     my $cid=$env{'request.course.id'}; 
1.109     www      5271:     if ($cid) {
1.391     matthew  5272:         # delete the stored spreadsheets for
                   5273:         # - the student level sheet of this user in course's homespace
                   5274:         # - the assessment level sheet for this resource 
                   5275:         #   for this user in user's homespace
1.553     albertel 5276: 	# - current conditional state info
1.325     www      5277: 	my $key=$uname.':'.$udom.':';
1.109     www      5278:         my $status=
1.299     matthew  5279: 	    &del('nohist_calculatedsheets',
1.391     matthew  5280: 		 [$key.'studentcalc:'],
1.620     albertel 5281: 		 $env{'course.'.$cid.'.domain'},
                   5282: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5283: 		.' '.
                   5284: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5285: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5286:         unless ($status eq 'ok ok') {
                   5287:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5288:                     $uname.' at '.$udom.' for '.
1.109     www      5289: 		    $symb.': '.$status);
1.133     albertel 5290:         }
1.553     albertel 5291: 	&delenv('user.state.'.$cid);
1.109     www      5292:     }
                   5293: }
                   5294: 
1.265     albertel 5295: sub get_scalar {
                   5296:     my ($string,$end) = @_;
                   5297:     my $value;
                   5298:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5299: 	$value = $1;
                   5300:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5301: 	$value = $1;
                   5302:     }
                   5303:     return &unescape($value);
                   5304: }
                   5305: 
                   5306: sub array2str {
                   5307:   my (@array) = @_;
                   5308:   my $result=&arrayref2str(\@array);
                   5309:   $result=~s/^__ARRAY_REF__//;
                   5310:   $result=~s/__END_ARRAY_REF__$//;
                   5311:   return $result;
                   5312: }
                   5313: 
1.204     albertel 5314: sub arrayref2str {
                   5315:   my ($arrayref) = @_;
1.265     albertel 5316:   my $result='__ARRAY_REF__';
1.204     albertel 5317:   foreach my $elem (@$arrayref) {
1.265     albertel 5318:     if(ref($elem) eq 'ARRAY') {
                   5319:       $result.=&arrayref2str($elem).'&';
                   5320:     } elsif(ref($elem) eq 'HASH') {
                   5321:       $result.=&hashref2str($elem).'&';
                   5322:     } elsif(ref($elem)) {
                   5323:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5324:     } else {
                   5325:       $result.=&escape($elem).'&';
                   5326:     }
                   5327:   }
                   5328:   $result=~s/\&$//;
1.265     albertel 5329:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5330:   return $result;
                   5331: }
                   5332: 
1.168     albertel 5333: sub hash2str {
1.204     albertel 5334:   my (%hash) = @_;
                   5335:   my $result=&hashref2str(\%hash);
1.265     albertel 5336:   $result=~s/^__HASH_REF__//;
                   5337:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5338:   return $result;
                   5339: }
                   5340: 
                   5341: sub hashref2str {
                   5342:   my ($hashref)=@_;
1.265     albertel 5343:   my $result='__HASH_REF__';
1.800     albertel 5344:   foreach my $key (sort(keys(%$hashref))) {
                   5345:     if (ref($key) eq 'ARRAY') {
                   5346:       $result.=&arrayref2str($key).'=';
                   5347:     } elsif (ref($key) eq 'HASH') {
                   5348:       $result.=&hashref2str($key).'=';
                   5349:     } elsif (ref($key)) {
1.265     albertel 5350:       $result.='=';
1.800     albertel 5351:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5352:     } else {
1.1132    raeburn  5353: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5354:     }
                   5355: 
1.800     albertel 5356:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5357:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5358:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5359:       $result.=&hashref2str($hashref->{$key}).'&';
                   5360:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5361:        $result.='&';
1.800     albertel 5362:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5363:     } else {
1.800     albertel 5364:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5365:     }
                   5366:   }
1.168     albertel 5367:   $result=~s/\&$//;
1.265     albertel 5368:   $result .= '__END_HASH_REF__';
1.168     albertel 5369:   return $result;
                   5370: }
                   5371: 
                   5372: sub str2hash {
1.265     albertel 5373:     my ($string)=@_;
                   5374:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5375:     return %$hash;
                   5376: }
                   5377: 
                   5378: sub str2hashref {
1.168     albertel 5379:   my ($string) = @_;
1.265     albertel 5380: 
                   5381:   my %hash;
                   5382: 
                   5383:   if($string !~ /^__HASH_REF__/) {
                   5384:       if (! ($string eq '' || !defined($string))) {
                   5385: 	  $hash{'error'}='Not hash reference';
                   5386:       }
                   5387:       return (\%hash, $string);
                   5388:   }
                   5389: 
                   5390:   $string =~ s/^__HASH_REF__//;
                   5391: 
                   5392:   while($string !~ /^__END_HASH_REF__/) {
                   5393:       #key
                   5394:       my $key='';
                   5395:       if($string =~ /^__HASH_REF__/) {
                   5396:           ($key, $string)=&str2hashref($string);
                   5397:           if(defined($key->{'error'})) {
                   5398:               $hash{'error'}='Bad data';
                   5399:               return (\%hash, $string);
                   5400:           }
                   5401:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5402:           ($key, $string)=&str2arrayref($string);
                   5403:           if($key->[0] eq 'Array reference error') {
                   5404:               $hash{'error'}='Bad data';
                   5405:               return (\%hash, $string);
                   5406:           }
                   5407:       } else {
                   5408:           $string =~ s/^(.*?)=//;
1.267     albertel 5409: 	  $key=&unescape($1);
1.265     albertel 5410:       }
                   5411:       $string =~ s/^=//;
                   5412: 
                   5413:       #value
                   5414:       my $value='';
                   5415:       if($string =~ /^__HASH_REF__/) {
                   5416:           ($value, $string)=&str2hashref($string);
                   5417:           if(defined($value->{'error'})) {
                   5418:               $hash{'error'}='Bad data';
                   5419:               return (\%hash, $string);
                   5420:           }
                   5421:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5422:           ($value, $string)=&str2arrayref($string);
                   5423:           if($value->[0] eq 'Array reference error') {
                   5424:               $hash{'error'}='Bad data';
                   5425:               return (\%hash, $string);
                   5426:           }
                   5427:       } else {
                   5428: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5429:       }
                   5430:       $string =~ s/^&//;
                   5431: 
                   5432:       $hash{$key}=$value;
1.204     albertel 5433:   }
1.265     albertel 5434: 
                   5435:   $string =~ s/^__END_HASH_REF__//;
                   5436: 
                   5437:   return (\%hash, $string);
1.204     albertel 5438: }
                   5439: 
                   5440: sub str2array {
1.265     albertel 5441:     my ($string)=@_;
                   5442:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5443:     return @$array;
                   5444: }
                   5445: 
                   5446: sub str2arrayref {
1.204     albertel 5447:   my ($string) = @_;
1.265     albertel 5448:   my @array;
                   5449: 
                   5450:   if($string !~ /^__ARRAY_REF__/) {
                   5451:       if (! ($string eq '' || !defined($string))) {
                   5452: 	  $array[0]='Array reference error';
                   5453:       }
                   5454:       return (\@array, $string);
                   5455:   }
                   5456: 
                   5457:   $string =~ s/^__ARRAY_REF__//;
                   5458: 
                   5459:   while($string !~ /^__END_ARRAY_REF__/) {
                   5460:       my $value='';
                   5461:       if($string =~ /^__HASH_REF__/) {
                   5462:           ($value, $string)=&str2hashref($string);
                   5463:           if(defined($value->{'error'})) {
                   5464:               $array[0] ='Array reference error';
                   5465:               return (\@array, $string);
                   5466:           }
                   5467:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5468:           ($value, $string)=&str2arrayref($string);
                   5469:           if($value->[0] eq 'Array reference error') {
                   5470:               $array[0] ='Array reference error';
                   5471:               return (\@array, $string);
                   5472:           }
                   5473:       } else {
                   5474: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5475:       }
                   5476:       $string =~ s/^&//;
                   5477: 
                   5478:       push(@array, $value);
1.191     harris41 5479:   }
1.265     albertel 5480: 
                   5481:   $string =~ s/^__END_ARRAY_REF__//;
                   5482: 
                   5483:   return (\@array, $string);
1.168     albertel 5484: }
                   5485: 
1.167     albertel 5486: # -------------------------------------------------------------------Temp Store
                   5487: 
1.168     albertel 5488: sub tmpreset {
                   5489:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5490:   if (!$symb) {
                   5491:     $symb=&symbread();
1.620     albertel 5492:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5493:   }
                   5494:   $symb=escape($symb);
                   5495: 
1.620     albertel 5496:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5497:   $namespace=~s/\//\_/g;
                   5498:   $namespace=~s/\W//g;
                   5499: 
1.620     albertel 5500:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5501:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5502:   if ($domain eq 'public' && $stuname eq 'public') {
                   5503:       $stuname=$ENV{'REMOTE_ADDR'};
                   5504:   }
1.1117    foxr     5505:   my $path=LONCAPA::tempdir();
1.168     albertel 5506:   my %hash;
                   5507:   if (tie(%hash,'GDBM_File',
                   5508: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5509: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5510:     foreach my $key (keys(%hash)) {
1.180     albertel 5511:       if ($key=~ /:$symb/) {
1.168     albertel 5512: 	delete($hash{$key});
                   5513:       }
                   5514:     }
                   5515:   }
                   5516: }
                   5517: 
1.167     albertel 5518: sub tmpstore {
1.168     albertel 5519:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5520: 
                   5521:   if (!$symb) {
                   5522:     $symb=&symbread();
1.620     albertel 5523:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5524:   }
                   5525:   $symb=escape($symb);
                   5526: 
                   5527:   if (!$namespace) {
                   5528:     # I don't think we would ever want to store this for a course.
                   5529:     # it seems this will only be used if we don't have a course.
1.620     albertel 5530:     #$namespace=$env{'request.course.id'};
1.168     albertel 5531:     #if (!$namespace) {
1.620     albertel 5532:       $namespace=$env{'request.state'};
1.168     albertel 5533:     #}
                   5534:   }
                   5535:   $namespace=~s/\//\_/g;
                   5536:   $namespace=~s/\W//g;
1.620     albertel 5537:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5538:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5539:   if ($domain eq 'public' && $stuname eq 'public') {
                   5540:       $stuname=$ENV{'REMOTE_ADDR'};
                   5541:   }
1.168     albertel 5542:   my $now=time;
                   5543:   my %hash;
1.1117    foxr     5544:   my $path=LONCAPA::tempdir();
1.168     albertel 5545:   if (tie(%hash,'GDBM_File',
                   5546: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5547: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5548:     $hash{"version:$symb"}++;
                   5549:     my $version=$hash{"version:$symb"};
                   5550:     my $allkeys=''; 
                   5551:     foreach my $key (keys(%$storehash)) {
                   5552:       $allkeys.=$key.':';
1.591     albertel 5553:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5554:     }
                   5555:     $hash{"$version:$symb:timestamp"}=$now;
                   5556:     $allkeys.='timestamp';
                   5557:     $hash{"$version:keys:$symb"}=$allkeys;
                   5558:     if (untie(%hash)) {
                   5559:       return 'ok';
                   5560:     } else {
                   5561:       return "error:$!";
                   5562:     }
                   5563:   } else {
                   5564:     return "error:$!";
                   5565:   }
                   5566: }
1.167     albertel 5567: 
1.168     albertel 5568: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5569: 
1.168     albertel 5570: sub tmprestore {
                   5571:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5572: 
1.168     albertel 5573:   if (!$symb) {
                   5574:     $symb=&symbread();
1.620     albertel 5575:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5576:   }
                   5577:   $symb=escape($symb);
                   5578: 
1.620     albertel 5579:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5580: 
1.620     albertel 5581:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5582:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5583:   if ($domain eq 'public' && $stuname eq 'public') {
                   5584:       $stuname=$ENV{'REMOTE_ADDR'};
                   5585:   }
1.168     albertel 5586:   my %returnhash;
                   5587:   $namespace=~s/\//\_/g;
                   5588:   $namespace=~s/\W//g;
                   5589:   my %hash;
1.1117    foxr     5590:   my $path=LONCAPA::tempdir();
1.168     albertel 5591:   if (tie(%hash,'GDBM_File',
                   5592: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5593: 	  &GDBM_READER(),0640)) {
1.168     albertel 5594:     my $version=$hash{"version:$symb"};
                   5595:     $returnhash{'version'}=$version;
                   5596:     my $scope;
                   5597:     for ($scope=1;$scope<=$version;$scope++) {
                   5598:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5599:       my @keys=split(/:/,$vkeys);
                   5600:       my $key;
                   5601:       $returnhash{"$scope:keys"}=$vkeys;
                   5602:       foreach $key (@keys) {
1.591     albertel 5603: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5604: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5605:       }
                   5606:     }
1.168     albertel 5607:     if (!(untie(%hash))) {
                   5608:       return "error:$!";
                   5609:     }
                   5610:   } else {
                   5611:     return "error:$!";
                   5612:   }
                   5613:   return %returnhash;
1.167     albertel 5614: }
                   5615: 
1.9       www      5616: # ----------------------------------------------------------------------- Store
                   5617: 
                   5618: sub store {
1.1269    raeburn  5619:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5620:     my $home='';
                   5621: 
1.168     albertel 5622:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5623: 
1.213     www      5624:     $symb=&symbclean($symb);
1.122     albertel 5625:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5626: 
1.620     albertel 5627:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5628:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5629: 
                   5630:     &devalidate($symb,$stuname,$domain);
1.109     www      5631: 
                   5632:     $symb=escape($symb);
1.187     www      5633:     if (!$namespace) { 
1.620     albertel 5634:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5635:           return ''; 
                   5636:        } 
                   5637:     }
1.620     albertel 5638:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5639: 
                   5640:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5641:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5642: 
1.12      www      5643:     my $namevalue='';
1.800     albertel 5644:     foreach my $key (keys(%$storehash)) {
                   5645:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5646:     }
1.12      www      5647:     $namevalue=~s/\&$//;
1.187     www      5648:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5649:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5650: }
                   5651: 
1.47      www      5652: # -------------------------------------------------------------- Critical Store
                   5653: 
                   5654: sub cstore {
1.1269    raeburn  5655:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5656:     my $home='';
                   5657: 
1.168     albertel 5658:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5659: 
1.213     www      5660:     $symb=&symbclean($symb);
1.122     albertel 5661:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5662: 
1.620     albertel 5663:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5664:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5665: 
                   5666:     &devalidate($symb,$stuname,$domain);
1.109     www      5667: 
                   5668:     $symb=escape($symb);
1.187     www      5669:     if (!$namespace) { 
1.620     albertel 5670:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5671:           return ''; 
                   5672:        } 
                   5673:     }
1.620     albertel 5674:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5675: 
                   5676:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5677:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5678: 
1.47      www      5679:     my $namevalue='';
1.800     albertel 5680:     foreach my $key (keys(%$storehash)) {
                   5681:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5682:     }
1.47      www      5683:     $namevalue=~s/\&$//;
1.187     www      5684:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5685:     return critical
1.1269    raeburn  5686:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5687: }
                   5688: 
1.9       www      5689: # --------------------------------------------------------------------- Restore
                   5690: 
                   5691: sub restore {
1.124     www      5692:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5693:     my $home='';
                   5694: 
1.168     albertel 5695:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5696: 
1.122     albertel 5697:     if (!$symb) {
1.1224    raeburn  5698:         return if ($namespace eq 'courserequests');
                   5699:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5700:     } else {
1.1224    raeburn  5701:         unless ($namespace eq 'courserequests') {
                   5702:             $symb=&escape(&symbclean($symb));
                   5703:         }
1.122     albertel 5704:     }
1.188     www      5705:     if (!$namespace) { 
1.620     albertel 5706:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5707:           return ''; 
                   5708:        } 
                   5709:     }
1.620     albertel 5710:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5711:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5712:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5713:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5714: 
1.12      www      5715:     my %returnhash=();
1.800     albertel 5716:     foreach my $line (split(/\&/,$answer)) {
                   5717: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5718:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5719:     }
1.75      www      5720:     my $version;
                   5721:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5722:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5723:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5724:        }
1.75      www      5725:     }
1.13      www      5726:     return %returnhash;
1.34      www      5727: }
                   5728: 
                   5729: # ---------------------------------------------------------- Course Description
1.1118    foxr     5730: #
                   5731: #  
1.34      www      5732: 
                   5733: sub coursedescription {
1.731     albertel 5734:     my ($courseid,$args)=@_;
1.34      www      5735:     $courseid=~s/^\///;
1.49      www      5736:     $courseid=~s/\_/\//g;
1.34      www      5737:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5738:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5739:     my $normalid=$cdomain.'_'.$cnum;
                   5740:     # need to always cache even if we get errors otherwise we keep 
                   5741:     # trying and trying and trying to get the course description.
                   5742:     my %envhash=();
                   5743:     my %returnhash=();
1.731     albertel 5744:     
                   5745:     my $expiretime=600;
                   5746:     if ($env{'request.course.id'} eq $normalid) {
                   5747: 	$expiretime=120;
                   5748:     }
                   5749: 
                   5750:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5751:     if (!$args->{'freshen_cache'}
                   5752: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5753: 	foreach my $key (keys(%env)) {
                   5754: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5755: 	    my ($setting) = $1;
                   5756: 	    $returnhash{$setting} = $env{$key};
                   5757: 	}
                   5758: 	return %returnhash;
                   5759:     }
                   5760: 
1.1118    foxr     5761:     # get the data again
                   5762: 
1.731     albertel 5763:     if (!$args->{'one_time'}) {
                   5764: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5765:     }
1.811     albertel 5766: 
1.34      www      5767:     if ($chome ne 'no_host') {
1.302     albertel 5768:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5769:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5770: 	   my $username = $env{'user.name'}; # Defult username
                   5771: 	   if(defined $args->{'user'}) {
                   5772: 	       $username = $args->{'user'};
                   5773: 	   }
1.129     albertel 5774:            $returnhash{'home'}= $chome;
                   5775: 	   $returnhash{'domain'} = $cdomain;
                   5776: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5777:            if (!defined($returnhash{'type'})) {
                   5778:                $returnhash{'type'} = 'Course';
                   5779:            }
1.130     albertel 5780:            while (my ($name,$value) = each %returnhash) {
1.53      www      5781:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5782:            }
1.270     www      5783:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5784:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5785: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5786:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5787:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5788:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5789:        }
                   5790:     }
1.731     albertel 5791:     if (!$args->{'one_time'}) {
1.949     raeburn  5792: 	&appenv(\%envhash);
1.731     albertel 5793:     }
1.302     albertel 5794:     return %returnhash;
1.461     www      5795: }
                   5796: 
1.1080    raeburn  5797: sub update_released_required {
                   5798:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5799:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5800:         $cid = $env{'request.course.id'};
                   5801:         $cdom = $env{'course.'.$cid.'.domain'};
                   5802:         $cnum = $env{'course.'.$cid.'.num'};
                   5803:         $chome = $env{'course.'.$cid.'.home'};
                   5804:     }
                   5805:     if ($needsrelease) {
                   5806:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5807:         my $needsupdate;
                   5808:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5809:             $needsupdate = 1;
                   5810:         } else {
                   5811:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5812:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5813:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5814:                 $needsupdate = 1;
                   5815:             }
                   5816:         }
                   5817:         if ($needsupdate) {
                   5818:             my %needshash = (
                   5819:                              'internal.releaserequired' => $needsrelease,
                   5820:                             );
                   5821:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5822:             if ($putresult eq 'ok') {
                   5823:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5824:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5825:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5826:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5827:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5828:                 }
                   5829:             }
                   5830:         }
                   5831:     }
                   5832:     return;
                   5833: }
                   5834: 
1.461     www      5835: # -------------------------------------------------See if a user is privileged
                   5836: 
                   5837: sub privileged {
1.1219    raeburn  5838:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5839:     my $now = time;
1.1219    raeburn  5840:     my $roles;
                   5841:     if (ref($possroles) eq 'ARRAY') {
                   5842:         $roles = $possroles; 
                   5843:     } else {
                   5844:         $roles = ['dc','su'];
                   5845:     }
                   5846:     if (ref($possdomains) eq 'ARRAY') {
                   5847:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5848:         foreach my $dom (@{$possdomains}) {
                   5849:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5850:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5851:                 foreach my $role (@{$roles}) {
                   5852:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5853:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5854:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5855:                             return 1 unless (($end && $end < $now) ||
                   5856:                                              ($start && $start > $now));
                   5857:                         }
                   5858:                     }
                   5859:                 }
                   5860:             }
                   5861:         }
                   5862:     } else {
                   5863:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5864:         my $now = time;
1.1170    droeschl 5865: 
1.1275    musolffc 5866:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5867:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5868:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5869:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5870:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5871:             }
1.1219    raeburn  5872:         }
                   5873:     }
                   5874:     return 0;
                   5875: }
1.1170    droeschl 5876: 
1.1219    raeburn  5877: sub privileged_by_domain {
                   5878:     my ($domains,$roles) = @_;
                   5879:     my %privileged = ();
                   5880:     my $cachetime = 60*60*24;
                   5881:     my $now = time;
                   5882:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5883:         return %privileged;
                   5884:     }
                   5885:     foreach my $dom (@{$domains}) {
                   5886:         next if (ref($privileged{$dom}) eq 'HASH');
                   5887:         my $needroles;
                   5888:         foreach my $role (@{$roles}) {
                   5889:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5890:             if (defined($cached)) {
                   5891:                 if (ref($result) eq 'HASH') {
                   5892:                     $privileged{$dom}{$role} = $result;
                   5893:                 }
                   5894:             } else {
                   5895:                 $needroles = 1;
                   5896:             }
                   5897:         }
                   5898:         if ($needroles) {
                   5899:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5900:             $privileged{$dom} = {};
                   5901:             foreach my $server (keys(%dompersonnel)) {
                   5902:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5903:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5904:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5905:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5906:                         next if ($end && $end < $now);
                   5907:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5908:                             $dompersonnel{$server}{$item};
                   5909:                     }
                   5910:                 }
                   5911:             }
                   5912:             if (ref($privileged{$dom}) eq 'HASH') {
                   5913:                 foreach my $role (@{$roles}) {
                   5914:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5915:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5916:                     } else {
                   5917:                         my %hash = ();
                   5918:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5919:                     }
                   5920:                 }
                   5921:             }
                   5922:         }
                   5923:     }
                   5924:     return %privileged;
1.9       www      5925: }
1.1       albertel 5926: 
1.103     harris41 5927: # -------------------------------------------------------- Get user privileges
1.11      www      5928: 
                   5929: sub rolesinit {
1.1169    droeschl 5930:     my ($domain, $username) = @_;
                   5931:     my %userroles = ('user.login.time' => time);
                   5932:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5933: 
                   5934:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5935:     # also, blocking can be triggered by an activating timer
                   5936:     # it's saved in the user's %env.
                   5937:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5938:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5939:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5940:         %timerintchk, %timerintenv);
                   5941: 
1.1162    raeburn  5942:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5943:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5944:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5945:     }
1.1169    droeschl 5946: 
1.1162    raeburn  5947:     foreach my $key (keys(%timerinterval)) {
                   5948:         my ($cid,$rest) = split(/\0/,$key);
                   5949:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5950:     }
1.1169    droeschl 5951: 
1.11      www      5952:     my %allroles=();
1.1162    raeburn  5953:     my %allgroups=();
1.11      www      5954: 
1.1274    raeburn  5955:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5956:         my $role = $rolesdump{$area};
                   5957:         $area =~ s/\_\w\w$//;
                   5958: 
                   5959:         my ($trole, $tend, $tstart, $group_privs);
                   5960: 
                   5961:         if ($role =~ /^cr/) {
                   5962:         # Custom role, defined by a user 
                   5963:         # e.g., user.role.cr/msu/smith/mynewrole
                   5964:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5965:                 $trole = $1;
                   5966:                 ($tend, $tstart) = split('_', $2);
                   5967:             } else {
                   5968:                 $trole = $role;
                   5969:             }
                   5970:         } elsif ($role =~ m|^gr/|) {
                   5971:         # Role of member in a group, defined within a course/community
                   5972:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5973:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5974:             next if $tstart eq '-1';
                   5975:             ($trole, $group_privs) = split(/\//, $trole);
                   5976:             $group_privs = &unescape($group_privs);
                   5977:         } else {
                   5978:         # Just a normal role, defined in roles.tab
                   5979:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5980:         }
                   5981: 
                   5982:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5983:                  $username);
                   5984:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5985: 
                   5986:         # role expired or not available yet?
                   5987:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5988:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5989: 
                   5990:         next if $area eq '' or $trole eq '';
                   5991: 
                   5992:         my $spec = "$trole.$area";
                   5993:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5994: 
                   5995:         if ($trole =~ /^cr\//) {
                   5996:         # Custom role, defined by a user
                   5997:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5998:         } elsif ($trole eq 'gr') {
                   5999:         # Role of a member in a group, defined within a course/community
                   6000:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   6001:             next;
                   6002:         } else {
                   6003:         # Normal role, defined in roles.tab
                   6004:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6005:         }
                   6006: 
                   6007:         my $cid = $tdomain.'_'.$trest;
                   6008:         unless ($firstaccchk{$cid}) {
                   6009:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6010:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6011:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6012:                         $coursetimerstarts{$cid}{$item}; 
                   6013:                 }
                   6014:             }
                   6015:             $firstaccchk{$cid} = 1;
                   6016:         }
                   6017:         unless ($timerintchk{$cid}) {
                   6018:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6019:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6020:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6021:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6022:                 }
1.12      www      6023:             }
1.1169    droeschl 6024:             $timerintchk{$cid} = 1;
1.191     harris41 6025:         }
1.11      www      6026:     }
1.1169    droeschl 6027: 
1.1341    raeburn  6028:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6029:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6030:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6031:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6032: 
1.1162    raeburn  6033:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6034: }
                   6035: 
1.567     raeburn  6036: sub set_arearole {
1.1215    raeburn  6037:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6038:     unless ($nolog) {
1.567     raeburn  6039: # log the associated role with the area
1.1215    raeburn  6040:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6041:     }
1.743     albertel 6042:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6043: }
                   6044: 
                   6045: sub custom_roleprivs {
                   6046:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6047:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6048:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6049:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6050:         my ($rdummy,$roledef)=
                   6051:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6052:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6053:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6054:             if (defined($syspriv)) {
1.1043    raeburn  6055:                 if ($trest =~ /^$match_community$/) {
                   6056:                     $syspriv =~ s/bre\&S//; 
                   6057:                 }
1.567     raeburn  6058:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6059:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6060:             }
                   6061:             if ($tdomain ne '') {
                   6062:                 if (defined($dompriv)) {
                   6063:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6064:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6065:                 }
                   6066:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6067:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6068:                         my $rolename = $1;
                   6069:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6070:                     }
1.567     raeburn  6071:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6072:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6073:                 }
                   6074:             }
                   6075:         }
                   6076:     }
                   6077: }
                   6078: 
1.1332    raeburn  6079: sub course_adhocrole_privs {
                   6080:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6081:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6082:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6083:         my (%currprivs,%storeprivs);
                   6084:         foreach my $item (split(/:/,$coursepriv)) {
                   6085:             my ($priv,$restrict) = split(/\&/,$item);
                   6086:             $currprivs{$priv} = $restrict;
                   6087:         }
                   6088:         my (%possadd,%possremove,%full);
                   6089:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6090:             my ($priv,$restrict)=split(/\&/,$item);
                   6091:             $full{$priv} = $restrict;
                   6092:         }
                   6093:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6094:              next if ($item eq '');
                   6095:              my ($rule,$rest) = split(/=/,$item);
                   6096:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6097:              foreach my $priv (split(/:/,$rest)) {
                   6098:                  if ($priv ne '') {
                   6099:                      if ($rule eq 'off') {
                   6100:                          $possremove{$priv} = 1;
                   6101:                      } else {
                   6102:                          $possadd{$priv} = 1;
                   6103:                      }
                   6104:                  }
                   6105:              }
                   6106:          }
                   6107:          foreach my $priv (sort(keys(%full))) {
                   6108:              if (exists($currprivs{$priv})) {
                   6109:                  unless (exists($possremove{$priv})) {
                   6110:                      $storeprivs{$priv} = $currprivs{$priv};
                   6111:                  }
                   6112:              } elsif (exists($possadd{$priv})) {
                   6113:                  $storeprivs{$priv} = $full{$priv};
                   6114:              }
                   6115:          }
                   6116:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6117:      }
                   6118:      return $coursepriv;
                   6119: }
                   6120: 
1.678     raeburn  6121: sub group_roleprivs {
                   6122:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6123:     my $access = 1;
                   6124:     my $now = time;
                   6125:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6126:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6127:     if ($access) {
1.811     albertel 6128:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6129:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6130:     }
                   6131: }
1.567     raeburn  6132: 
                   6133: sub standard_roleprivs {
                   6134:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6135:     if (defined($pr{$trole.':s'})) {
                   6136:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6137:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6138:     }
                   6139:     if ($tdomain ne '') {
                   6140:         if (defined($pr{$trole.':d'})) {
                   6141:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6142:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6143:         }
                   6144:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6145:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6146:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6147:         }
                   6148:     }
                   6149: }
                   6150: 
                   6151: sub set_userprivs {
1.1064    raeburn  6152:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6153:     my $author=0;
                   6154:     my $adv=0;
1.1341    raeburn  6155:     my $rar=0;
1.678     raeburn  6156:     my %grouproles = ();
                   6157:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6158:         my @groupkeys; 
1.1000    raeburn  6159:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6160:             push(@groupkeys,$role);
                   6161:         }
                   6162:         if (ref($groups_roles) eq 'HASH') {
                   6163:             foreach my $key (keys(%{$groups_roles})) {
                   6164:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6165:                     push(@groupkeys,$key);
                   6166:                 }
                   6167:             }
                   6168:         }
                   6169:         if (@groupkeys > 0) {
                   6170:             foreach my $role (@groupkeys) {
                   6171:                 my ($trole,$area,$sec,$extendedarea);
                   6172:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6173:                     $trole = $1;
                   6174:                     $area = $2;
                   6175:                     $sec = $3;
                   6176:                     $extendedarea = $area.$sec;
                   6177:                     if (exists($$allgroups{$area})) {
                   6178:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6179:                             my $spec = $trole.'.'.$extendedarea;
                   6180:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6181:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6182:                         }
1.678     raeburn  6183:                     }
                   6184:                 }
                   6185:             }
                   6186:         }
                   6187:     }
1.800     albertel 6188:     foreach my $group (keys(%grouproles)) {
                   6189:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6190:     }
1.800     albertel 6191:     foreach my $role (keys(%{$allroles})) {
                   6192:         my %thesepriv;
1.941     raeburn  6193:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6194:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6195:             if ($item ne '') {
                   6196:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6197:                 if ($restrictions eq '') {
                   6198:                     $thesepriv{$privilege}='F';
                   6199:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6200:                     $thesepriv{$privilege}.=$restrictions;
                   6201:                 }
                   6202:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6203:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6204:             }
                   6205:         }
                   6206:         my $thesestr='';
1.1104    raeburn  6207:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6208: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6209: 	}
                   6210:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6211:     }
1.1341    raeburn  6212:     return ($author,$adv,$rar);
1.567     raeburn  6213: }
                   6214: 
1.994     raeburn  6215: sub role_status {
1.1104    raeburn  6216:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6217:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6218:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6219:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6220:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6221:             $$where = '/'.$two;
1.994     raeburn  6222:             $$trolecode=$$role.'.'.$$where;
                   6223:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6224:             $$tstatus='is';
1.1104    raeburn  6225:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6226:                 $$tstatus='future';
1.1034    raeburn  6227:                 if ($$tstart<$now) {
                   6228:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6229:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6230:                             my (%allroles,%allgroups,$group_privs,
                   6231:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6232:                             my %userroles = (
                   6233:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6234:                             );
1.1064    raeburn  6235:                             @rolecodes = ('cm'); 
1.1002    raeburn  6236:                             my $spec=$$role.'.'.$$where;
                   6237:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6238:                             if ($$role =~ /^cr\//) {
                   6239:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6240:                                 push(@rolecodes,'cr');
1.1002    raeburn  6241:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6242:                                 push(@rolecodes,$$role);
1.1002    raeburn  6243:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6244:                                                     $env{'user.name'});
1.1064    raeburn  6245:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6246:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6247:                                 $group_privs = &unescape($group_privs);
                   6248:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6249:                                 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  6250:                                 &get_groups_roles($tdomain,$trest,
                   6251:                                                   \%course_roles,\@rolecodes,
                   6252:                                                   \%groups_roles);
1.1002    raeburn  6253:                             } else {
1.1064    raeburn  6254:                                 push(@rolecodes,$$role);
1.1002    raeburn  6255:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6256:                             }
1.1341    raeburn  6257:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6258:                                                                    \%groups_roles);
1.1064    raeburn  6259:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6260:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6261:                         }
                   6262:                     }
1.1034    raeburn  6263:                     $$tstatus = 'is';
1.1002    raeburn  6264:                 }
1.994     raeburn  6265:             }
                   6266:             if ($$tend) {
1.1104    raeburn  6267:                 if ($$tend<$update) {
1.994     raeburn  6268:                     $$tstatus='expired';
                   6269:                 } elsif ($$tend<$now) {
                   6270:                     $$tstatus='will_not';
                   6271:                 }
                   6272:             }
                   6273:         }
                   6274:     }
                   6275: }
                   6276: 
1.1104    raeburn  6277: sub get_groups_roles {
                   6278:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6279:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6280:                   (ref($rolecodes) eq 'ARRAY') && 
                   6281:                   (ref($groups_roles) eq 'HASH')); 
                   6282:     if (keys(%{$cdom_courseroles}) > 0) {
                   6283:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6284:         if ($cdom ne '' && $cnum ne '') {
                   6285:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6286:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6287:                     my $crsrole = $1;
                   6288:                     my $crssec = $2;
                   6289:                     if ($crsrole =~ /^cr/) {
                   6290:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6291:                             push(@{$rolecodes},'cr');
                   6292:                         }
                   6293:                     } else {
                   6294:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6295:                             push(@{$rolecodes},$crsrole);
                   6296:                         }
                   6297:                     }
                   6298:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6299:                     if ($crssec ne '') {
                   6300:                         $rolekey .= "/$crssec";
                   6301:                     }
                   6302:                     $rolekey .= './';
                   6303:                     $groups_roles->{$rolekey} = $rolecodes;
                   6304:                 }
                   6305:             }
                   6306:         }
                   6307:     }
                   6308:     return;
                   6309: }
                   6310: 
                   6311: sub delete_env_groupprivs {
                   6312:     my ($where,$courseroles,$possroles) = @_;
                   6313:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6314:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6315:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6316:         %{$courseroles->{$udom}} =
                   6317:             &get_my_roles('','','userroles',['active'],
                   6318:                           $possroles,[$udom],1);
                   6319:     }
                   6320:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6321:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6322:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6323:             my $area = '/'.$cdom.'/'.$cnum;
                   6324:             my $privkey = "user.priv.$crsrole.$area";
                   6325:             if ($crssec ne '') {
                   6326:                 $privkey .= '/'.$crssec;
                   6327:             }
                   6328:             $privkey .= ".$area/$group";
                   6329:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6330:         }
                   6331:     }
                   6332:     return;
                   6333: }
                   6334: 
1.994     raeburn  6335: sub check_adhoc_privs {
1.1329    raeburn  6336:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6337:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6338:     if ($sec) {
                   6339:         $cckey .= '/'.$sec;
                   6340:     } 
1.1185    raeburn  6341:     my $setprivs;
1.994     raeburn  6342:     if ($env{$cckey}) {
                   6343:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6344:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6345:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6346:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6347:             $setprivs = 1;
1.994     raeburn  6348:         }
                   6349:     } else {
1.1330    raeburn  6350:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6351:         $setprivs = 1;
1.994     raeburn  6352:     }
1.1185    raeburn  6353:     return $setprivs;
1.994     raeburn  6354: }
                   6355: 
                   6356: sub set_adhoc_privileges {
1.1326    raeburn  6357: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6358:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6359:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6360:     if ($sec ne '') {
                   6361:         $area .= '/'.$sec;
                   6362:     }
1.994     raeburn  6363:     my $spec = $role.'.'.$area;
                   6364:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6365:                                   $env{'user.name'},1);
1.1326    raeburn  6366:     my %rolehash = ();
1.1332    raeburn  6367:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6368:         my $rolename = $1;
1.1326    raeburn  6369:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6370:         my %domdef = &get_domain_defaults($dcdom);
                   6371:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6372:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6373:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6374:             }
                   6375:         }
1.1326    raeburn  6376:     } else {
                   6377:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6378:     }
1.1341    raeburn  6379:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6380:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6381:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6382:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6383:         &appenv( {'request.role'        => $spec,
                   6384:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6385:                   'request.course.sec'  => $sec,
1.1088    raeburn  6386:                  }
                   6387:                );
                   6388:         my $tadv=0;
                   6389:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6390:         &appenv({'request.role.adv'    => $tadv});
                   6391:     }
1.994     raeburn  6392: }
                   6393: 
1.12      www      6394: # --------------------------------------------------------------- get interface
                   6395: 
                   6396: sub get {
1.131     albertel 6397:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6398:    my $items='';
1.800     albertel 6399:    foreach my $item (@$storearr) {
                   6400:        $items.=&escape($item).'&';
1.191     harris41 6401:    }
1.12      www      6402:    $items=~s/\&$//;
1.620     albertel 6403:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6404:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6405:    my $uhome=&homeserver($uname,$udomain);
                   6406: 
1.133     albertel 6407:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6408:    my @pairs=split(/\&/,$rep);
1.273     albertel 6409:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6410:      return @pairs;
                   6411:    }
1.15      www      6412:    my %returnhash=();
1.42      www      6413:    my $i=0;
1.800     albertel 6414:    foreach my $item (@$storearr) {
                   6415:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6416:       $i++;
1.191     harris41 6417:    }
1.15      www      6418:    return %returnhash;
1.27      www      6419: }
                   6420: 
                   6421: # --------------------------------------------------------------- del interface
                   6422: 
                   6423: sub del {
1.133     albertel 6424:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6425:    my $items='';
1.800     albertel 6426:    foreach my $item (@$storearr) {
                   6427:        $items.=&escape($item).'&';
1.191     harris41 6428:    }
1.984     neumanie 6429: 
1.27      www      6430:    $items=~s/\&$//;
1.620     albertel 6431:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6432:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6433:    my $uhome=&homeserver($uname,$udomain);
                   6434:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6435: }
                   6436: 
                   6437: # -------------------------------------------------------------- dump interface
                   6438: 
1.1180    droeschl 6439: sub unserialize {
                   6440:     my ($rep, $escapedkeys) = @_;
                   6441: 
                   6442:     return {} if $rep =~ /^error/;
                   6443: 
                   6444:     my %returnhash=();
1.1252    raeburn  6445: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6446: 	    my ($key, $value) = split(/=/, $item, 2);
                   6447: 	    $key = unescape($key) unless $escapedkeys;
                   6448: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6449: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6450: 	}
                   6451:     #return %returnhash;
                   6452:     return \%returnhash;
                   6453: }        
                   6454: 
                   6455: # see Lond::dump_with_regexp
                   6456: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6457: sub dump {
1.1180    droeschl 6458:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6459:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6460:     if (!$uname) { $uname=$env{'user.name'}; }
                   6461:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6462: 
1.1266    raeburn  6463:     if ($regexp) {
                   6464:         $regexp=&escape($regexp);
                   6465:     } else {
                   6466:         $regexp='.';
                   6467:     }
1.1180    droeschl 6468:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6469:         # user is hosted on this machine
1.1266    raeburn  6470:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6471:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6472:         return %{unserialize($reply, $escapedkeys)};
                   6473:     }
1.1166    raeburn  6474:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6475:     my @pairs=split(/\&/,$rep);
                   6476:     my %returnhash=();
1.1098    foxr     6477:     if (!($rep =~ /^error/ )) {
                   6478: 	foreach my $item (@pairs) {
                   6479: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6480:         $key = unescape($key) unless $escapedkeys;
                   6481:         #$key = &unescape($key);
1.1098    foxr     6482: 	    next if ($key =~ /^error: 2 /);
                   6483: 	    $returnhash{$key}=&thaw_unescape($value);
                   6484: 	}
1.755     albertel 6485:     }
                   6486:     return %returnhash;
1.407     www      6487: }
                   6488: 
1.1098    foxr     6489: 
1.717     albertel 6490: # --------------------------------------------------------- dumpstore interface
                   6491: 
                   6492: sub dumpstore {
                   6493:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6494:    # same as dump but keys must be escaped. They may contain colon separated
                   6495:    # lists of values that may themself contain colons (e.g. symbs).
                   6496:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6497: }
                   6498: 
1.407     www      6499: # -------------------------------------------------------------- keys interface
                   6500: 
                   6501: sub getkeys {
                   6502:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6503:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6504:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6505:    my $uhome=&homeserver($uname,$udomain);
                   6506:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6507:    my @keyarray=();
1.800     albertel 6508:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6509:       next if ($key =~ /^error: 2 /);
1.800     albertel 6510:       push(@keyarray,&unescape($key));
1.407     www      6511:    }
                   6512:    return @keyarray;
1.318     matthew  6513: }
                   6514: 
1.319     matthew  6515: # --------------------------------------------------------------- currentdump
                   6516: sub currentdump {
1.328     matthew  6517:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6518:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6519:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6520:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6521:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6522:    my $rep;
                   6523: 
                   6524:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6525:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6526:                    $courseid)));
                   6527:    } else {
                   6528:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6529:    }
                   6530: 
1.318     matthew  6531:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6532:    #
1.318     matthew  6533:    my %returnhash=();
1.319     matthew  6534:    #
1.1343    raeburn  6535:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6536:        # an old lond will not know currentdump
                   6537:        # Do a dump and make it look like a currentdump
1.822     albertel 6538:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6539:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6540:        my %hash = @tmp;
                   6541:        @tmp=();
1.424     matthew  6542:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6543:    } else {
                   6544:        my @pairs=split(/\&/,$rep);
1.800     albertel 6545:        foreach my $pair (@pairs) {
                   6546:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6547:            my ($symb,$param) = split(/:/,$key);
                   6548:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6549:                                                         &thaw_unescape($value);
1.319     matthew  6550:        }
1.191     harris41 6551:    }
1.12      www      6552:    return %returnhash;
1.424     matthew  6553: }
                   6554: 
                   6555: sub convert_dump_to_currentdump{
                   6556:     my %hash = %{shift()};
                   6557:     my %returnhash;
                   6558:     # Code ripped from lond, essentially.  The only difference
                   6559:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6560:     # we might run in to problems with parameter names =~ /^v\./
                   6561:     while (my ($key,$value) = each(%hash)) {
                   6562:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6563: 	$symb  = &unescape($symb);
                   6564: 	$param = &unescape($param);
1.424     matthew  6565:         next if ($v eq 'version' || $symb eq 'keys');
                   6566:         next if (exists($returnhash{$symb}) &&
                   6567:                  exists($returnhash{$symb}->{$param}) &&
                   6568:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6569:         $returnhash{$symb}->{$param}=$value;
                   6570:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6571:     }
                   6572:     #
                   6573:     # Remove all of the keys in the hashes which keep track of
                   6574:     # the version of the parameter.
                   6575:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6576:         # use a foreach because we are going to delete from the hash.
                   6577:         foreach my $key (keys(%$param_hash)) {
                   6578:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6579:         }
                   6580:     }
                   6581:     return \%returnhash;
1.12      www      6582: }
                   6583: 
1.627     albertel 6584: # ------------------------------------------------------ critical inc interface
                   6585: 
                   6586: sub cinc {
                   6587:     return &inc(@_,'critical');
                   6588: }
                   6589: 
1.449     matthew  6590: # --------------------------------------------------------------- inc interface
                   6591: 
                   6592: sub inc {
1.627     albertel 6593:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6594:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6595:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6596:     my $uhome=&homeserver($uname,$udomain);
                   6597:     my $items='';
                   6598:     if (! ref($store)) {
                   6599:         # got a single value, so use that instead
                   6600:         $items = &escape($store).'=&';
                   6601:     } elsif (ref($store) eq 'SCALAR') {
                   6602:         $items = &escape($$store).'=&';        
                   6603:     } elsif (ref($store) eq 'ARRAY') {
                   6604:         $items = join('=&',map {&escape($_);} @{$store});
                   6605:     } elsif (ref($store) eq 'HASH') {
                   6606:         while (my($key,$value) = each(%{$store})) {
                   6607:             $items.= &escape($key).'='.&escape($value).'&';
                   6608:         }
                   6609:     }
                   6610:     $items=~s/\&$//;
1.627     albertel 6611:     if ($critical) {
                   6612: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6613:     } else {
                   6614: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6615:     }
1.449     matthew  6616: }
                   6617: 
1.12      www      6618: # --------------------------------------------------------------- put interface
                   6619: 
                   6620: sub put {
1.134     albertel 6621:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6622:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6623:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6624:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6625:    my $items='';
1.800     albertel 6626:    foreach my $item (keys(%$storehash)) {
                   6627:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6628:    }
1.12      www      6629:    $items=~s/\&$//;
1.134     albertel 6630:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6631: }
                   6632: 
1.631     albertel 6633: # ------------------------------------------------------------ newput interface
                   6634: 
                   6635: sub newput {
                   6636:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6637:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6638:    if (!$uname) { $uname=$env{'user.name'}; }
                   6639:    my $uhome=&homeserver($uname,$udomain);
                   6640:    my $items='';
                   6641:    foreach my $key (keys(%$storehash)) {
                   6642:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6643:    }
                   6644:    $items=~s/\&$//;
                   6645:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6646: }
                   6647: 
                   6648: # ---------------------------------------------------------  putstore interface
                   6649: 
1.524     raeburn  6650: sub putstore {
1.1269    raeburn  6651:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6652:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6653:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6654:    my $uhome=&homeserver($uname,$udomain);
                   6655:    my $items='';
1.715     albertel 6656:    foreach my $key (keys(%$storehash)) {
                   6657:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6658:    }
1.715     albertel 6659:    $items=~s/\&$//;
1.716     albertel 6660:    my $esc_symb=&escape($symb);
                   6661:    my $esc_v=&escape($version);
1.715     albertel 6662:    my $reply =
1.716     albertel 6663:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6664: 	      $uhome);
1.1269    raeburn  6665:    if (($tolog) && ($reply eq 'ok')) {
                   6666:        my $namevalue='';
                   6667:        foreach my $key (keys(%{$storehash})) {
                   6668:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6669:        }
                   6670:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6671:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6672:                      '&version='.$esc_v.
                   6673:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6674:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6675:    }
1.715     albertel 6676:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6677:        # gfall back to way things use to be done
1.715     albertel 6678:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6679: 			    $uname);
1.524     raeburn  6680:    }
1.715     albertel 6681:    return $reply;
                   6682: }
                   6683: 
                   6684: sub old_putstore {
1.716     albertel 6685:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6686:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6687:     if (!$uname) { $uname=$env{'user.name'}; }
                   6688:     my $uhome=&homeserver($uname,$udomain);
                   6689:     my %newstorehash;
1.800     albertel 6690:     foreach my $item (keys(%$storehash)) {
                   6691: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6692: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6693:     }
                   6694:     my $items='';
                   6695:     my %allitems = ();
1.800     albertel 6696:     foreach my $item (keys(%newstorehash)) {
                   6697: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6698: 	    my $key = $1.':keys:'.$2;
                   6699: 	    $allitems{$key} .= $3.':';
                   6700: 	}
1.800     albertel 6701: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6702:     }
1.800     albertel 6703:     foreach my $item (keys(%allitems)) {
                   6704: 	$allitems{$item} =~ s/\:$//;
                   6705: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6706:     }
                   6707:     $items=~s/\&$//;
                   6708:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6709: }
                   6710: 
1.47      www      6711: # ------------------------------------------------------ critical put interface
                   6712: 
                   6713: sub cput {
1.134     albertel 6714:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6715:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6716:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6717:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6718:    my $items='';
1.800     albertel 6719:    foreach my $item (keys(%$storehash)) {
                   6720:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6721:    }
1.47      www      6722:    $items=~s/\&$//;
1.134     albertel 6723:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6724: }
                   6725: 
                   6726: # -------------------------------------------------------------- eget interface
                   6727: 
                   6728: sub eget {
1.133     albertel 6729:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6730:    my $items='';
1.800     albertel 6731:    foreach my $item (@$storearr) {
                   6732:        $items.=&escape($item).'&';
1.191     harris41 6733:    }
1.12      www      6734:    $items=~s/\&$//;
1.620     albertel 6735:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6736:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6737:    my $uhome=&homeserver($uname,$udomain);
                   6738:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6739:    my @pairs=split(/\&/,$rep);
                   6740:    my %returnhash=();
1.42      www      6741:    my $i=0;
1.800     albertel 6742:    foreach my $item (@$storearr) {
                   6743:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6744:       $i++;
1.191     harris41 6745:    }
1.12      www      6746:    return %returnhash;
                   6747: }
                   6748: 
1.667     albertel 6749: # ------------------------------------------------------------ tmpput interface
                   6750: sub tmpput {
1.802     raeburn  6751:     my ($storehash,$server,$context)=@_;
1.667     albertel 6752:     my $items='';
1.800     albertel 6753:     foreach my $item (keys(%$storehash)) {
                   6754: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6755:     }
                   6756:     $items=~s/\&$//;
1.802     raeburn  6757:     if (defined($context)) {
                   6758:         $items .= ':'.&escape($context);
                   6759:     }
1.667     albertel 6760:     return &reply("tmpput:$items",$server);
                   6761: }
                   6762: 
                   6763: # ------------------------------------------------------------ tmpget interface
                   6764: sub tmpget {
1.688     albertel 6765:     my ($token,$server)=@_;
                   6766:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6767:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6768:     my %returnhash;
1.1328    raeburn  6769:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6770:         return %returnhash;
                   6771:     }
1.667     albertel 6772:     foreach my $item (split(/\&/,$rep)) {
                   6773: 	my ($key,$value)=split(/=/,$item);
                   6774: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6775:     }
                   6776:     return %returnhash;
                   6777: }
                   6778: 
1.1113    raeburn  6779: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6780: sub tmpdel {
                   6781:     my ($token,$server)=@_;
                   6782:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6783:     return &reply("tmpdel:$token",$server);
                   6784: }
                   6785: 
1.1198    raeburn  6786: # ------------------------------------------------------------ get_timebased_id 
                   6787: 
                   6788: sub get_timebased_id {
                   6789:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6790:         $maxtries) = @_;
                   6791:     my ($newid,$error,$dellock);
                   6792:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6793:         return ('','ok','invalid call to get suffix');
                   6794:     }
                   6795: 
                   6796: # set defaults for any optional args for which values were not supplied
                   6797:     if ($who eq '') {
                   6798:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6799:     }
                   6800:     if (!$locktries) {
                   6801:         $locktries = 3;
                   6802:     }
                   6803:     if (!$maxtries) {
                   6804:         $maxtries = 10;
                   6805:     }
                   6806:     
                   6807:     if (($cdom eq '') || ($cnum eq '')) {
                   6808:         if ($env{'request.course.id'}) {
                   6809:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6810:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6811:         }
                   6812:         if (($cdom eq '') || ($cnum eq '')) {
                   6813:             return ('','ok','call to get suffix not in course context');
                   6814:         }
                   6815:     }
                   6816: 
                   6817: # construct locking item
                   6818:     my $lockhash = {
                   6819:                       $prefix."\0".'locked_'.$keyid => $who,
                   6820:                    };
                   6821:     my $tries = 0;
                   6822: 
                   6823: # attempt to get lock on nohist_$namespace file
                   6824:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6825:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6826:         $tries ++;
                   6827:         sleep 1;
                   6828:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6829:     }
                   6830: 
                   6831: # attempt to get unique identifier, based on current timestamp
                   6832:     if ($gotlock eq 'ok') {
                   6833:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6834:         my $id = time;
                   6835:         $newid = $id;
1.1268    raeburn  6836:         if ($idtype eq 'addcode') {
                   6837:             $newid .= &sixnum_code();
                   6838:         }
1.1198    raeburn  6839:         my $idtries = 0;
                   6840:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6841:             if ($idtype eq 'concat') {
                   6842:                 $newid = $id.$idtries;
1.1268    raeburn  6843:             } elsif ($idtype eq 'addcode') {
                   6844:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6845:             } else {
                   6846:                 $newid ++;
                   6847:             }
                   6848:             $idtries ++;
                   6849:         }
                   6850:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6851:             my %new_item =  (
                   6852:                               $prefix."\0".$newid => $who,
                   6853:                             );
                   6854:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6855:                                                  $cdom,$cnum);
                   6856:             if ($putresult ne 'ok') {
                   6857:                 undef($newid);
                   6858:                 $error = 'error saving new item: '.$putresult;
                   6859:             }
                   6860:         } else {
1.1268    raeburn  6861:              undef($newid);
1.1198    raeburn  6862:              $error = ('error: no unique suffix available for the new item ');
                   6863:         }
                   6864: #  remove lock
                   6865:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6866:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6867:     } else {
                   6868:         $error = "error: could not obtain lockfile\n";
                   6869:         $dellock = 'ok';
1.1276    raeburn  6870:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6871:             $dellock = 'nolock';
                   6872:         }
1.1198    raeburn  6873:     }
                   6874:     return ($newid,$dellock,$error);
                   6875: }
                   6876: 
1.1268    raeburn  6877: sub sixnum_code {
                   6878:     my $code;
                   6879:     for (0..6) {
                   6880:         $code .= int( rand(9) );
                   6881:     }
                   6882:     return $code;
                   6883: }
                   6884: 
1.765     albertel 6885: # -------------------------------------------------- portfolio access checking
                   6886: 
                   6887: sub portfolio_access {
1.1270    raeburn  6888:     my ($requrl,$clientip) = @_;
1.765     albertel 6889:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6890:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6891:     if ($result) {
                   6892:         my %setters;
                   6893:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6894:             my ($startblock,$endblock) =
                   6895:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6896:             if ($startblock && $endblock) {
                   6897:                 return 'B';
                   6898:             }
                   6899:         } else {
                   6900:             my ($startblock,$endblock) =
                   6901:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6902:             if ($startblock && $endblock) {
                   6903:                 return 'B';
                   6904:             }
                   6905:         }
                   6906:     }
1.765     albertel 6907:     if ($result eq 'ok') {
1.766     albertel 6908:        return 'F';
1.765     albertel 6909:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6910:        return 'A';
1.765     albertel 6911:     }
1.766     albertel 6912:     return '';
1.765     albertel 6913: }
                   6914: 
                   6915: sub get_portfolio_access {
1.1270    raeburn  6916:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6917: 
                   6918:     if (!ref($access_hash)) {
                   6919: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6920: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6921: 						   $file_name);
                   6922: 	$access_hash = $access_controls{$file_name};
                   6923:     }
                   6924: 
1.1270    raeburn  6925:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6926:     my $now = time;
                   6927:     if (ref($access_hash) eq 'HASH') {
                   6928:         foreach my $key (keys(%{$access_hash})) {
                   6929:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6930:             if ($start > $now) {
                   6931:                 next;
                   6932:             }
                   6933:             if ($end && $end<$now) {
                   6934:                 next;
                   6935:             }
                   6936:             if ($scope eq 'public') {
                   6937:                 $public = $key;
                   6938:                 last;
                   6939:             } elsif ($scope eq 'guest') {
                   6940:                 $guest = $key;
                   6941:             } elsif ($scope eq 'domains') {
                   6942:                 push(@domains,$key);
                   6943:             } elsif ($scope eq 'users') {
                   6944:                 push(@users,$key);
                   6945:             } elsif ($scope eq 'course') {
                   6946:                 push(@courses,$key);
                   6947:             } elsif ($scope eq 'group') {
                   6948:                 push(@groups,$key);
1.1270    raeburn  6949:             } elsif ($scope eq 'ip') {
                   6950:                 push(@ips,$key);
1.765     albertel 6951:             }
                   6952:         }
                   6953:         if ($public) {
                   6954:             return 'ok';
1.1270    raeburn  6955:         } elsif (@ips > 0) {
                   6956:             my $allowed;
                   6957:             foreach my $ipkey (@ips) {
                   6958:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6959:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6960:                         $allowed = 1;
                   6961:                         last; 
                   6962:                     }
                   6963:                 }
                   6964:             }
                   6965:             if ($allowed) {
                   6966:                 return 'ok';
                   6967:             }
1.765     albertel 6968:         }
                   6969:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6970:             if ($guest) {
                   6971:                 return $guest;
                   6972:             }
                   6973:         } else {
                   6974:             if (@domains > 0) {
                   6975:                 foreach my $domkey (@domains) {
                   6976:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6977:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6978:                             return 'ok';
                   6979:                         }
                   6980:                     }
                   6981:                 }
                   6982:             }
                   6983:             if (@users > 0) {
                   6984:                 foreach my $userkey (@users) {
1.865     raeburn  6985:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6986:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6987:                             if (ref($item) eq 'HASH') {
                   6988:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6989:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6990:                                     return 'ok';
                   6991:                                 }
                   6992:                             }
                   6993:                         }
                   6994:                     } 
1.765     albertel 6995:                 }
                   6996:             }
                   6997:             my %roleshash;
                   6998:             my @courses_and_groups = @courses;
                   6999:             push(@courses_and_groups,@groups); 
                   7000:             if (@courses_and_groups > 0) {
                   7001:                 my (%allgroups,%allroles); 
                   7002:                 my ($start,$end,$role,$sec,$group);
                   7003:                 foreach my $envkey (%env) {
1.1060    raeburn  7004:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7005:                         my $cid = $2.'_'.$3; 
                   7006:                         if ($1 eq 'gr') {
                   7007:                             $group = $4;
                   7008:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7009:                         } else {
                   7010:                             if ($4 eq '') {
                   7011:                                 $sec = 'none';
                   7012:                             } else {
                   7013:                                 $sec = $4;
                   7014:                             }
                   7015:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7016:                         }
1.811     albertel 7017:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7018:                         my $cid = $2.'_'.$3;
                   7019:                         if ($4 eq '') {
                   7020:                             $sec = 'none';
                   7021:                         } else {
                   7022:                             $sec = $4;
                   7023:                         }
                   7024:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7025:                     }
                   7026:                 }
                   7027:                 if (keys(%allroles) == 0) {
                   7028:                     return;
                   7029:                 }
                   7030:                 foreach my $key (@courses_and_groups) {
                   7031:                     my %content = %{$$access_hash{$key}};
                   7032:                     my $cnum = $content{'number'};
                   7033:                     my $cdom = $content{'domain'};
                   7034:                     my $cid = $cdom.'_'.$cnum;
                   7035:                     if (!exists($allroles{$cid})) {
                   7036:                         next;
                   7037:                     }    
                   7038:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7039:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7040:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7041:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7042:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7043:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7044:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7045:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7046:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7047:                                         if (grep/^all$/,@sections) {
                   7048:                                             return 'ok';
                   7049:                                         } else {
                   7050:                                             if (grep/^$sec$/,@sections) {
                   7051:                                                 return 'ok';
                   7052:                                             }
                   7053:                                         }
                   7054:                                     }
                   7055:                                 }
                   7056:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7057:                                     if (grep/^none$/,@groups) {
                   7058:                                         return 'ok';
                   7059:                                     }
                   7060:                                 } else {
                   7061:                                     if (grep/^all$/,@groups) {
                   7062:                                         return 'ok';
                   7063:                                     } 
                   7064:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7065:                                         if (grep/^$group$/,@groups) {
                   7066:                                             return 'ok';
                   7067:                                         }
                   7068:                                     }
                   7069:                                 } 
                   7070:                             }
                   7071:                         }
                   7072:                     }
                   7073:                 }
                   7074:             }
                   7075:             if ($guest) {
                   7076:                 return $guest;
                   7077:             }
                   7078:         }
                   7079:     }
                   7080:     return;
                   7081: }
                   7082: 
                   7083: sub course_group_datechecker {
                   7084:     my ($dates,$now,$status) = @_;
                   7085:     my ($start,$end) = split(/\./,$dates);
                   7086:     if (!$start && !$end) {
                   7087:         return 'ok';
                   7088:     }
                   7089:     if (grep/^active$/,@{$status}) {
                   7090:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7091:             return 'ok';
                   7092:         }
                   7093:     }
                   7094:     if (grep/^previous$/,@{$status}) {
                   7095:         if ($end > $now ) {
                   7096:             return 'ok';
                   7097:         }
                   7098:     }
                   7099:     if (grep/^future$/,@{$status}) {
                   7100:         if ($start > $now) {
                   7101:             return 'ok';
                   7102:         }
                   7103:     }
                   7104:     return; 
                   7105: }
                   7106: 
                   7107: sub parse_portfolio_url {
                   7108:     my ($url) = @_;
                   7109: 
                   7110:     my ($type,$udom,$unum,$group,$file_name);
                   7111:     
1.823     albertel 7112:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7113: 	$type = 1;
                   7114:         $udom = $1;
                   7115:         $unum = $2;
                   7116:         $file_name = $3;
1.823     albertel 7117:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7118: 	$type = 2;
                   7119:         $udom = $1;
                   7120:         $unum = $2;
                   7121:         $group = $3;
                   7122:         $file_name = $3.'/'.$4;
                   7123:     }
                   7124:     if (wantarray) {
                   7125: 	return ($type,$udom,$unum,$file_name,$group);
                   7126:     }
                   7127:     return $type;
                   7128: }
                   7129: 
                   7130: sub is_portfolio_url {
                   7131:     my ($url) = @_;
                   7132:     return scalar(&parse_portfolio_url($url));
                   7133: }
                   7134: 
1.798     raeburn  7135: sub is_portfolio_file {
                   7136:     my ($file) = @_;
1.820     raeburn  7137:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7138:         return 1;
                   7139:     }
                   7140:     return;
                   7141: }
                   7142: 
1.976     raeburn  7143: sub usertools_access {
1.1084    raeburn  7144:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7145:     my ($access,%tools);
                   7146:     if ($context eq '') {
                   7147:         $context = 'tools';
                   7148:     }
                   7149:     if ($context eq 'requestcourses') {
                   7150:         %tools = (
                   7151:                       official   => 1,
                   7152:                       unofficial => 1,
1.1006    raeburn  7153:                       community  => 1,
1.1246    raeburn  7154:                       textbook   => 1,
1.1305    raeburn  7155:                       placement  => 1,
1.1368    raeburn  7156:                       lti        => 1,
1.985     raeburn  7157:                  );
1.1183    raeburn  7158:     } elsif ($context eq 'requestauthor') {
                   7159:         %tools = (
                   7160:                       requestauthor => 1,
                   7161:                  );
1.985     raeburn  7162:     } else {
                   7163:         %tools = (
                   7164:                       aboutme   => 1,
                   7165:                       blog      => 1,
1.1177    raeburn  7166:                       webdav    => 1,
1.985     raeburn  7167:                       portfolio => 1,
                   7168:                  );
                   7169:     }
1.976     raeburn  7170:     return if (!defined($tools{$tool}));
                   7171: 
1.1242    raeburn  7172:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7173:         $udom = $env{'user.domain'};
                   7174:         $uname = $env{'user.name'};
                   7175:     }
                   7176: 
1.978     raeburn  7177:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7178:         if ($action ne 'reload') {
1.985     raeburn  7179:             if ($context eq 'requestcourses') {
                   7180:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7181:             } elsif ($context eq 'requestauthor') {
                   7182:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7183:             } else {
                   7184:                 return $env{'environment.availabletools.'.$tool};
                   7185:             }
                   7186:         }
1.976     raeburn  7187:     }
                   7188: 
1.1183    raeburn  7189:     my ($toolstatus,$inststatus,$envkey);
                   7190:     if ($context eq 'requestauthor') {
                   7191:         $envkey = $context; 
                   7192:     } else {
                   7193:         $envkey = $context.'.'.$tool;
                   7194:     }
1.976     raeburn  7195: 
1.985     raeburn  7196:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7197:          ($action ne 'reload')) {
1.1183    raeburn  7198:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7199:         $inststatus = $env{'environment.inststatus'};
                   7200:     } else {
1.1084    raeburn  7201:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7202:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7203:             $inststatus = $userenvref->{'inststatus'};
                   7204:         } else {
1.1183    raeburn  7205:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7206:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7207:             $inststatus = $userenv{'inststatus'};
                   7208:         }
1.976     raeburn  7209:     }
                   7210: 
                   7211:     if ($toolstatus ne '') {
                   7212:         if ($toolstatus) {
                   7213:             $access = 1;
                   7214:         } else {
                   7215:             $access = 0;
                   7216:         }
                   7217:         return $access;
                   7218:     }
                   7219: 
1.1084    raeburn  7220:     my ($is_adv,%domdef);
                   7221:     if (ref($is_advref) eq 'HASH') {
                   7222:         $is_adv = $is_advref->{'is_adv'};
                   7223:     } else {
                   7224:         $is_adv = &is_advanced_user($udom,$uname);
                   7225:     }
                   7226:     if (ref($domdefref) eq 'HASH') {
                   7227:         %domdef = %{$domdefref};
                   7228:     } else {
                   7229:         %domdef = &get_domain_defaults($udom);
                   7230:     }
1.976     raeburn  7231:     if (ref($domdef{$tool}) eq 'HASH') {
                   7232:         if ($is_adv) {
                   7233:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7234:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7235:                     $access = 1;
                   7236:                 } else {
                   7237:                     $access = 0;
                   7238:                 }
                   7239:                 return $access;
                   7240:             }
                   7241:         }
                   7242:         if ($inststatus ne '') {
                   7243:             my ($hasaccess,$hasnoaccess);
                   7244:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7245:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7246:                     if ($domdef{$tool}{$affiliation}) {
                   7247:                         $hasaccess = 1;
                   7248:                     } else {
                   7249:                         $hasnoaccess = 1;
                   7250:                     }
                   7251:                 }
                   7252:             }
                   7253:             if ($hasaccess || $hasnoaccess) {
                   7254:                 if ($hasaccess) {
                   7255:                     $access = 1;
                   7256:                 } elsif ($hasnoaccess) {
                   7257:                     $access = 0; 
                   7258:                 }
                   7259:                 return $access;
                   7260:             }
                   7261:         } else {
                   7262:             if ($domdef{$tool}{'default'} ne '') {
                   7263:                 if ($domdef{$tool}{'default'}) {
                   7264:                     $access = 1;
                   7265:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7266:                     $access = 0;
                   7267:                 }
                   7268:                 return $access;
                   7269:             }
                   7270:         }
                   7271:     } else {
1.1177    raeburn  7272:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7273:             $access = 1;
                   7274:         } else {
                   7275:             $access = 0;
                   7276:         }
1.976     raeburn  7277:         return $access;
                   7278:     }
                   7279: }
                   7280: 
1.1050    raeburn  7281: sub is_course_owner {
                   7282:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7283:     if (($udom eq '') || ($uname eq '')) {
                   7284:         $udom = $env{'user.domain'};
                   7285:         $uname = $env{'user.name'};
                   7286:     }
                   7287:     unless (($udom eq '') || ($uname eq '')) {
                   7288:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7289:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7290:                 return 1;
                   7291:             } else {
                   7292:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7293:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7294:                     return 1;
                   7295:                 }
                   7296:             }
                   7297:         }
                   7298:     }
                   7299:     return;
                   7300: }
                   7301: 
1.976     raeburn  7302: sub is_advanced_user {
                   7303:     my ($udom,$uname) = @_;
1.1085    raeburn  7304:     if ($udom ne '' && $uname ne '') {
                   7305:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7306:             if (wantarray) {
                   7307:                 return ($env{'user.adv'},$env{'user.author'});
                   7308:             } else {
                   7309:                 return $env{'user.adv'};
                   7310:             }
1.1085    raeburn  7311:         }
                   7312:     }
1.976     raeburn  7313:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7314:     my %allroles;
1.1128    raeburn  7315:     my ($is_adv,$is_author);
1.976     raeburn  7316:     foreach my $role (keys(%roleshash)) {
                   7317:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7318:         my $area = '/'.$tdomain.'/'.$trest;
                   7319:         if ($sec ne '') {
                   7320:             $area .= '/'.$sec;
                   7321:         }
                   7322:         if (($area ne '') && ($trole ne '')) {
                   7323:             my $spec=$trole.'.'.$area;
                   7324:             if ($trole =~ /^cr\//) {
                   7325:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7326:             } elsif ($trole ne 'gr') {
                   7327:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7328:             }
1.1128    raeburn  7329:             if ($trole eq 'au') {
                   7330:                 $is_author = 1;
                   7331:             }
1.976     raeburn  7332:         }
                   7333:     }
                   7334:     foreach my $role (keys(%allroles)) {
                   7335:         last if ($is_adv);
                   7336:         foreach my $item (split(/:/,$allroles{$role})) {
                   7337:             if ($item ne '') {
                   7338:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7339:                 if ($privilege eq 'adv') {
                   7340:                     $is_adv = 1;
                   7341:                     last;
                   7342:                 }
                   7343:             }
                   7344:         }
                   7345:     }
1.1128    raeburn  7346:     if (wantarray) {
                   7347:         return ($is_adv,$is_author);
                   7348:     }
1.976     raeburn  7349:     return $is_adv;
                   7350: }
1.798     raeburn  7351: 
1.1035    raeburn  7352: sub check_can_request {
1.1368    raeburn  7353:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7354:     my $canreq = 0;
1.1368    raeburn  7355:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7356:         $uname = $env{'user.name'};
                   7357:         $udom = $env{'user.domain'};
                   7358:     }
1.1035    raeburn  7359:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7360:     my @options = ('approval','validate','autolimit');
                   7361:     my $optregex = join('|',@options);
                   7362:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7363:         foreach my $type (@{$types}) {
1.1368    raeburn  7364:             if (&usertools_access($uname,$udom,$type,undef,
                   7365:                                   'requestcourses')) {
1.1035    raeburn  7366:                 $canreq ++;
1.1036    raeburn  7367:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7368:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7369:                 }
1.1368    raeburn  7370:                 if ($dom eq $udom) {
1.1035    raeburn  7371:                     $can_request->{$type} = 1;
                   7372:                 }
                   7373:             }
1.1368    raeburn  7374:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7375:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7376:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7377:                 if (@curr > 0) {
1.1036    raeburn  7378:                     foreach my $item (@curr) {
                   7379:                         if (ref($request_domains) eq 'HASH') {
                   7380:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7381:                             if ($otherdom ne '') {
                   7382:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7383:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7384:                                         push(@{$request_domains->{$type}},$otherdom);
                   7385:                                     }
                   7386:                                 } else {
                   7387:                                     push(@{$request_domains->{$type}},$otherdom);
                   7388:                                 }
                   7389:                             }
                   7390:                         }
                   7391:                     }
1.1368    raeburn  7392:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7393:                         $canreq ++;
1.1035    raeburn  7394:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7395:                             $can_request->{$type} = 1;
                   7396:                         }
                   7397:                     }
                   7398:                 }
                   7399:             }
                   7400:         }
                   7401:     }
                   7402:     return $canreq;
                   7403: }
                   7404: 
1.341     www      7405: # ---------------------------------------------- Custom access rule evaluation
                   7406: 
                   7407: sub customaccess {
                   7408:     my ($priv,$uri)=@_;
1.807     albertel 7409:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7410:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7411:     $udom = &LONCAPA::clean_domain($udom);
                   7412:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7413:     my $access=0;
1.800     albertel 7414:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7415: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7416: 	if ($type eq 'user') {
                   7417: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7418: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7419: 		if ($tdom) {
                   7420: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7421: 		}
1.896     albertel 7422: 		if ($tuname) {
                   7423: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7424: 		}
                   7425: 		$access=($effect eq 'allow');
                   7426: 		last;
                   7427: 	    }
                   7428: 	} else {
                   7429: 	    if ($role) {
                   7430: 		if ($role ne $urole) { next; }
                   7431: 	    }
                   7432: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7433: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7434: 		if ($tdom) {
                   7435: 		    if ($tdom ne $udom) { next; }
                   7436: 		}
                   7437: 		if ($tcrs) {
                   7438: 		    if ($tcrs ne $ucrs) { next; }
                   7439: 		}
                   7440: 		if ($tsec) {
                   7441: 		    if ($tsec ne $usec) { next; }
                   7442: 		}
                   7443: 		$access=($effect eq 'allow');
                   7444: 		last;
                   7445: 	    }
                   7446: 	    if ($realm eq '' && $role eq '') {
                   7447: 		$access=($effect eq 'allow');
                   7448: 	    }
1.402     bowersj2 7449: 	}
1.341     www      7450:     }
                   7451:     return $access;
                   7452: }
                   7453: 
1.103     harris41 7454: # ------------------------------------------------- Check for a user privilege
1.12      www      7455: 
                   7456: sub allowed {
1.1281    raeburn  7457:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7458:     my $ver_orguri=$uri;
1.439     www      7459:     $uri=&deversion($uri);
1.152     www      7460:     my $orguri=$uri;
1.52      www      7461:     $uri=&declutter($uri);
1.809     raeburn  7462: 
1.810     raeburn  7463:     if ($priv eq 'evb') {
                   7464: # Evade communication block restrictions for specified role in a course
                   7465:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7466:             return $1;
                   7467:         } else {
                   7468:             return;
                   7469:         }
                   7470:     }
                   7471: 
1.620     albertel 7472:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7473: # Free bre access to adm and meta resources
1.1343    raeburn  7474:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7475: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7476: 	&& ($priv eq 'bre')) {
1.14      www      7477: 	return 'F';
1.159     www      7478:     }
                   7479: 
1.545     banghart 7480: # Free bre access to user's own portfolio contents
1.714     raeburn  7481:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7482:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7483: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7484:         my %setters;
                   7485:         my ($startblock,$endblock) = 
                   7486:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7487:         if ($startblock && $endblock) {
                   7488:             return 'B';
                   7489:         } else {
                   7490:             return 'F';
                   7491:         }
1.545     banghart 7492:     }
                   7493: 
1.762     raeburn  7494: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7495:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7496:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7497:         if (exists($env{'request.course.id'})) {
                   7498:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7499:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7500:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7501:                 my $courseprivid=$env{'request.course.id'};
                   7502:                 $courseprivid=~s/\_/\//;
                   7503:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7504:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7505:                     return $1; 
1.762     raeburn  7506:                 } else {
                   7507:                     if ($env{'request.course.sec'}) {
                   7508:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7509:                     }
                   7510:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7511:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7512:                         return $2;
                   7513:                     }
1.714     raeburn  7514:                 }
                   7515:             }
                   7516:         }
                   7517:     }
                   7518: 
1.159     www      7519: # Free bre to public access
                   7520: 
                   7521:     if ($priv eq 'bre') {
1.1362    raeburn  7522:         my $copyright;
                   7523:         unless ($uri =~ /ext\.tool/) {
                   7524:             $copyright=&metadata($uri,'copyright');
                   7525:         }
1.620     albertel 7526: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7527:            return 'F'; 
                   7528:         }
1.238     www      7529:         if ($copyright eq 'priv') {
                   7530:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7531: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7532: 		return '';
                   7533:             }
                   7534:         }
                   7535:         if ($copyright eq 'domain') {
                   7536:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7537: 	    unless (($env{'user.domain'} eq $1) ||
                   7538:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7539: 		return '';
                   7540:             }
1.262     matthew  7541:         }
1.620     albertel 7542:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7543:             # Library role, so allow browsing of resources in this domain.
                   7544:             return 'F';
1.238     www      7545:         }
1.341     www      7546:         if ($copyright eq 'custom') {
                   7547: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7548:         }
1.14      www      7549:     }
1.264     matthew  7550:     # Domain coordinator is trying to create a course
1.620     albertel 7551:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7552:         # uri is the requested domain in this case.
                   7553:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7554:         # a role of dc for the domain in question.
1.620     albertel 7555:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7556:     }
1.29      www      7557: 
1.52      www      7558:     my $thisallowed='';
                   7559:     my $statecond=0;
                   7560:     my $courseprivid='';
                   7561: 
1.1039    raeburn  7562:     my $ownaccess;
1.1043    raeburn  7563:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7564:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7565:         if ($uri eq '') {
                   7566:             $ownaccess = 1;
                   7567:         } else {
                   7568:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7569:                 my $udom = $env{'user.domain'};
                   7570:                 my $uname = $env{'user.name'};
                   7571:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7572:                     $ownaccess = 1;
1.1040    raeburn  7573:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7574:                     unless ($uri =~ m{\.\./}) {
                   7575:                         $ownaccess = 1;
                   7576:                     }
                   7577:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7578:                     my $now = time;
                   7579:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7580:                         my $adom = $1;
                   7581:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7582:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7583:                                 my ($start,$end) = split('.',$env{$key});
                   7584:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7585:                                     $ownaccess = 1;
                   7586:                                     last;
                   7587:                                 }
                   7588:                             }
                   7589:                         }
                   7590:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7591:                         my $adom = $1;
                   7592:                         my $aname = $2;
1.1042    raeburn  7593:                         foreach my $role ('ca','aa') { 
                   7594:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7595:                                 my ($start,$end) =
                   7596:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7597:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7598:                                     $ownaccess = 1;
                   7599:                                     last;
                   7600:                                 }
1.1039    raeburn  7601:                             }
                   7602:                         }
                   7603:                     }
                   7604:                 }
                   7605:             }
                   7606:         }
                   7607:     }
                   7608: 
1.52      www      7609: # Course
                   7610: 
1.620     albertel 7611:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7612:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7613:             $thisallowed.=$1;
                   7614:         }
1.52      www      7615:     }
1.29      www      7616: 
1.52      www      7617: # Domain
                   7618: 
1.620     albertel 7619:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7620:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7621:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7622:             $thisallowed.=$1;
                   7623:         }
1.12      www      7624:     }
1.52      www      7625: 
1.1141    raeburn  7626: # User who is not author or co-author might still be able to edit
                   7627: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7628:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7629:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7630:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7631:             $thisallowed.=$1;
                   7632:         }
                   7633:     }
                   7634: 
1.52      www      7635: # Course: uri itself is a course
1.66      www      7636:     my $courseuri=$uri;
                   7637:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7638:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7639: 
1.620     albertel 7640:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7641:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7642:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7643:             $thisallowed.=$1;
                   7644:         }
1.12      www      7645:     }
1.29      www      7646: 
1.665     albertel 7647: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7648: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7649:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7650: 	$thisallowed='';
1.671     raeburn  7651:         my ($match)=&is_on_map($uri);
                   7652:         if ($match) {
                   7653:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7654:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7655:                 my $value = $1;
                   7656:                 if ($noblockcheck) {
                   7657:                     $thisallowed.=$value;
1.1162    raeburn  7658:                 } else {
1.1281    raeburn  7659:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7660:                     if (@blockers > 0) {
                   7661:                         $thisallowed = 'B';
                   7662:                     } else {
                   7663:                         $thisallowed.=$value;
                   7664:                     }
1.1162    raeburn  7665:                 }
1.671     raeburn  7666:             }
                   7667:         } else {
1.705     albertel 7668:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7669:             if ($refuri) {
                   7670:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7671:                     $thisallowed='F';
1.671     raeburn  7672:                 } else {
                   7673:                     $refuri=&declutter($refuri);
                   7674:                     my ($match) = &is_on_map($refuri);
                   7675:                     if ($match) {
1.1281    raeburn  7676:                         if ($noblockcheck) {
                   7677:                             $thisallowed='F';
1.1162    raeburn  7678:                         } else {
1.1281    raeburn  7679:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7680:                             if (@blockers > 0) {
                   7681:                                 $thisallowed = 'B';
                   7682:                             } else {
                   7683:                                 $thisallowed='F';
                   7684:                             }
1.1162    raeburn  7685:                         }
1.671     raeburn  7686:                     }
1.669     raeburn  7687:                 }
1.671     raeburn  7688:             }
                   7689:         }
1.314     www      7690:     }
1.492     albertel 7691: 
1.766     albertel 7692:     if ($priv eq 'bre'
                   7693: 	&& $thisallowed ne 'F' 
                   7694: 	&& $thisallowed ne '2'
                   7695: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7696: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7697:     }
1.1250    raeburn  7698: 
1.52      www      7699: # Full access at system, domain or course-wide level? Exit.
1.29      www      7700:     if ($thisallowed=~/F/) {
                   7701: 	return 'F';
                   7702:     }
                   7703: 
1.52      www      7704: # If this is generating or modifying users, exit with special codes
1.29      www      7705: 
1.643     www      7706:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7707: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7708: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7709: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7710: 	    unless ($auname) { return $thisallowed; }
                   7711: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7712: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7713: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7714: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7715: 	}
1.52      www      7716: 	return $thisallowed;
                   7717:     }
                   7718: #
1.103     harris41 7719: # Gathered so far: system, domain and course wide privileges
1.52      www      7720: #
                   7721: # Course: See if uri or referer is an individual resource that is part of 
                   7722: # the course
                   7723: 
1.620     albertel 7724:     if ($env{'request.course.id'}) {
1.232     www      7725: 
1.620     albertel 7726:        $courseprivid=$env{'request.course.id'};
                   7727:        if ($env{'request.course.sec'}) {
                   7728:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7729:        }
                   7730:        $courseprivid=~s/\_/\//;
                   7731:        my $checkreferer=1;
1.232     www      7732:        my ($match,$cond)=&is_on_map($uri);
                   7733:        if ($match) {
                   7734:            $statecond=$cond;
1.620     albertel 7735:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7736:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7737:                my $value = $1;
                   7738:                if ($priv eq 'bre') {
1.1281    raeburn  7739:                    if ($noblockcheck) {
                   7740:                        $thisallowed.=$value;
1.1162    raeburn  7741:                    } else {
1.1281    raeburn  7742:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7743:                        if (@blockers > 0) {
                   7744:                            $thisallowed = 'B';
                   7745:                        } else {
                   7746:                            $thisallowed.=$value;
                   7747:                        }
1.1162    raeburn  7748:                    }
                   7749:                } else {
                   7750:                    $thisallowed.=$value;
                   7751:                }
1.52      www      7752:                $checkreferer=0;
                   7753:            }
1.29      www      7754:        }
1.83      www      7755:        
1.148     www      7756:        if ($checkreferer) {
1.620     albertel 7757: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7758:             unless ($refuri) {
1.800     albertel 7759:                 foreach my $key (keys(%env)) {
                   7760: 		    if ($key=~/^httpref\..*\*/) {
                   7761: 			my $pattern=$key;
1.156     www      7762:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7763:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7764:                         $pattern=~s/\//\\\//g;
1.152     www      7765:                         if ($orguri=~/$pattern/) {
1.800     albertel 7766: 			    $refuri=$env{$key};
1.148     www      7767:                         }
                   7768:                     }
1.191     harris41 7769:                 }
1.148     www      7770:             }
1.232     www      7771: 
1.148     www      7772:          if ($refuri) { 
1.152     www      7773: 	  $refuri=&declutter($refuri);
1.232     www      7774:           my ($match,$cond)=&is_on_map($refuri);
                   7775:             if ($match) {
                   7776:               my $refstatecond=$cond;
1.620     albertel 7777:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7778:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7779:                   my $value = $1;
                   7780:                   if ($priv eq 'bre') {
1.1281    raeburn  7781:                       if ($noblockcheck) {
                   7782:                           $thisallowed.=$value;
1.1162    raeburn  7783:                       } else {
1.1281    raeburn  7784:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7785:                           if (@blockers > 0) {
                   7786:                               $thisallowed = 'B';
                   7787:                           } else {
                   7788:                               $thisallowed.=$value;
                   7789:                           }
1.1162    raeburn  7790:                       }
                   7791:                   } else {
                   7792:                       $thisallowed.=$value;
                   7793:                   }
1.53      www      7794:                   $uri=$refuri;
                   7795:                   $statecond=$refstatecond;
1.52      www      7796:               }
                   7797:           }
1.148     www      7798:         }
1.29      www      7799:        }
1.52      www      7800:    }
1.29      www      7801: 
1.52      www      7802: #
1.103     harris41 7803: # Gathered now: all privileges that could apply, and condition number
1.52      www      7804: # 
                   7805: #
                   7806: # Full or no access?
                   7807: #
1.29      www      7808: 
1.52      www      7809:     if ($thisallowed=~/F/) {
                   7810: 	return 'F';
                   7811:     }
1.29      www      7812: 
1.52      www      7813:     unless ($thisallowed) {
                   7814:         return '';
                   7815:     }
1.29      www      7816: 
1.52      www      7817: # Restrictions exist, deal with them
                   7818: #
                   7819: #   C:according to course preferences
                   7820: #   R:according to resource settings
                   7821: #   L:unless locked
                   7822: #   X:according to user session state
                   7823: #
                   7824: 
                   7825: # Possibly locked functionality, check all courses
1.54      www      7826: # Locks might take effect only after 10 minutes cache expiration for other
                   7827: # courses, and 2 minutes for current course
1.52      www      7828: 
                   7829:     my $envkey;
                   7830:     if ($thisallowed=~/L/) {
1.1000    raeburn  7831:         foreach $envkey (keys(%env)) {
1.54      www      7832:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7833:                my $courseid=$2;
                   7834:                my $roleid=$1.'.'.$2;
1.92      www      7835:                $courseid=~s/^\///;
1.54      www      7836:                my $expiretime=600;
1.620     albertel 7837:                if ($env{'request.role'} eq $roleid) {
1.54      www      7838: 		  $expiretime=120;
                   7839:                }
                   7840: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7841:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7842:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7843: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7844:                }
1.620     albertel 7845:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7846:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7847: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7848:                        &log($env{'user.domain'},$env{'user.name'},
                   7849:                             $env{'user.home'},
1.57      www      7850:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7851:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7852:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7853: 		       return '';
                   7854:                    }
                   7855:                }
1.620     albertel 7856:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7857:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7858: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7859:                        &log($env{'user.domain'},$env{'user.name'},
                   7860:                             $env{'user.home'},
1.57      www      7861:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7862:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7863:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7864: 		       return '';
                   7865:                    }
                   7866:                }
                   7867: 	   }
1.29      www      7868:        }
1.52      www      7869:     }
                   7870:    
                   7871: #
                   7872: # Rest of the restrictions depend on selected course
                   7873: #
                   7874: 
1.620     albertel 7875:     unless ($env{'request.course.id'}) {
1.766     albertel 7876: 	if ($thisallowed eq 'A') {
                   7877: 	    return 'A';
1.814     raeburn  7878:         } elsif ($thisallowed eq 'B') {
                   7879:             return 'B';
1.766     albertel 7880: 	} else {
                   7881: 	    return '1';
                   7882: 	}
1.52      www      7883:     }
1.29      www      7884: 
1.52      www      7885: #
                   7886: # Now user is definitely in a course
                   7887: #
1.53      www      7888: 
                   7889: 
                   7890: # Course preferences
                   7891: 
                   7892:    if ($thisallowed=~/C/) {
1.620     albertel 7893:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7894:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7895:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7896: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7897: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7898: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7899: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7900: 			$env{'request.course.id'});
                   7901: 	   }
1.237     www      7902:            return '';
                   7903:        }
                   7904: 
1.620     albertel 7905:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7906: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7907: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7908: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7909: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7910: 			$env{'request.course.id'});
                   7911: 	   }
1.54      www      7912:            return '';
                   7913:        }
1.53      www      7914:    }
                   7915: 
                   7916: # Resource preferences
                   7917: 
                   7918:    if ($thisallowed=~/R/) {
1.620     albertel 7919:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7920:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7921: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7922: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7923: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7924: 	   }
                   7925: 	   return '';
1.54      www      7926:        }
1.53      www      7927:    }
1.30      www      7928: 
1.246     www      7929: # Restricted by state or randomout?
1.30      www      7930: 
1.52      www      7931:    if ($thisallowed=~/X/) {
1.620     albertel 7932:       if ($env{'acc.randomout'}) {
1.579     albertel 7933: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7934:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7935:             return ''; 
                   7936:          }
1.247     www      7937:       }
                   7938:       if (&condval($statecond)) {
1.52      www      7939: 	 return '2';
                   7940:       } else {
                   7941:          return '';
                   7942:       }
                   7943:    }
1.30      www      7944: 
1.766     albertel 7945:     if ($thisallowed eq 'A') {
                   7946: 	return 'A';
1.814     raeburn  7947:     } elsif ($thisallowed eq 'B') {
                   7948:         return 'B';
1.766     albertel 7949:     }
1.52      www      7950:    return 'F';
1.232     www      7951: }
1.1162    raeburn  7952: 
1.1192    raeburn  7953: # ------------------------------------------- Check construction space access
                   7954: 
                   7955: sub constructaccess {
                   7956:     my ($url,$setpriv)=@_;
                   7957: 
                   7958: # We do not allow editing of previous versions of files
                   7959:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7960: 
                   7961: # Get username and domain from URL
                   7962:     my ($ownername,$ownerdomain,$ownerhome);
                   7963: 
                   7964:     ($ownerdomain,$ownername) =
1.1325    raeburn  7965:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7966: 
                   7967: # The URL does not really point to any authorspace, forget it
                   7968:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7969: 
                   7970: # Now we need to see if the user has access to the authorspace of
                   7971: # $ownername at $ownerdomain
                   7972: 
                   7973:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7974: # Real author for this?
                   7975:        $ownerhome = $env{'user.home'};
                   7976:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7977:           return ($ownername,$ownerdomain,$ownerhome);
                   7978:        }
                   7979:     } else {
                   7980: # Co-author for this?
                   7981:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7982:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7983:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7984:             return ($ownername,$ownerdomain,$ownerhome);
                   7985:         }
1.1312    raeburn  7986:         if ($env{'request.course.id'}) {
                   7987:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7988:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7989:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7990:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7991:                     return ($ownername,$ownerdomain,$ownerhome);
                   7992:                 }
                   7993:             }
                   7994:         }
1.1192    raeburn  7995:     }
                   7996: 
                   7997: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7998: # we might as well leave
                   7999:    unless ($setpriv) { return ''; }
                   8000: 
                   8001: # Backdoor access?
                   8002:     my $allowed=&allowed('eco',$ownerdomain);
                   8003: # Nope
                   8004:     unless ($allowed) { return ''; }
                   8005: # Looks like we may have access, but could be locked by the owner of the construction space
                   8006:     if ($allowed eq 'U') {
                   8007:         my %blocked=&get('environment',['domcoord.author'],
                   8008:                          $ownerdomain,$ownername);
                   8009: # Is blocked by owner
                   8010:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8011:     }
                   8012:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8013: # Grant temporary access
                   8014:         my $then=$env{'user.login.time'};
1.1209    raeburn  8015:         my $update=$env{'user.update.time'};
1.1192    raeburn  8016:         if (!$update) { $update = $then; }
                   8017:         my $refresh=$env{'user.refresh.time'};
                   8018:         if (!$refresh) { $refresh = $update; }
                   8019:         my $now = time;
                   8020:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8021:                            $now,'ca','constructaccess');
                   8022:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8023:         return($ownername,$ownerdomain,$ownerhome);
                   8024:     }
                   8025: # No business here
                   8026:     return '';
                   8027: }
                   8028: 
1.1282    raeburn  8029: # ----------------------------------------------------------- Content Blocking
                   8030: 
                   8031: {
                   8032: # Caches for faster Course Contents display where content blocking
                   8033: # is in operation (i.e., interval param set) for timed quiz.
                   8034: #
                   8035: # User for whom data are being temporarily cached.
                   8036: my $cacheduser='';
                   8037: # Cached blockers for this user (a hash of blocking items). 
                   8038: my %cachedblockers=();
                   8039: # When the data were last cached.
                   8040: my $cachedlast='';
                   8041: 
                   8042: sub load_all_blockers {
                   8043:     my ($uname,$udom,$blocks)=@_;
                   8044:     if (($uname ne '') && ($udom ne '')) { 
                   8045:         if (($cacheduser eq $uname.':'.$udom) &&
                   8046:             (abs($cachedlast-time)<5)) {
                   8047:             return;
                   8048:         }
                   8049:     }
                   8050:     $cachedlast=time;
                   8051:     $cacheduser=$uname.':'.$udom;
                   8052:     %cachedblockers = &get_commblock_resources($blocks);
                   8053: }
                   8054: 
1.1162    raeburn  8055: sub get_comm_blocks {
                   8056:     my ($cdom,$cnum) = @_;
                   8057:     if ($cdom eq '' || $cnum eq '') {
                   8058:         return unless ($env{'request.course.id'});
                   8059:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8060:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8061:     }
                   8062:     my %commblocks;
                   8063:     my $hashid=$cdom.'_'.$cnum;
                   8064:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8065:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8066:         %commblocks = %{$blocksref};
                   8067:     } else {
                   8068:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8069:         my $cachetime = 600;
                   8070:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8071:     }
                   8072:     return %commblocks;
                   8073: }
                   8074: 
1.1282    raeburn  8075: sub get_commblock_resources {
                   8076:     my ($blocks) = @_;
                   8077:     my %blockers = ();
                   8078:     return %blockers unless ($env{'request.course.id'});
                   8079:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8080:     my %commblocks;
                   8081:     if (ref($blocks) eq 'HASH') {
                   8082:         %commblocks = %{$blocks};
                   8083:     } else {
                   8084:         %commblocks = &get_comm_blocks();
                   8085:     }
1.1282    raeburn  8086:     return %blockers unless (keys(%commblocks) > 0); 
                   8087:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8088:     return %blockers unless (ref($navmap));
1.1162    raeburn  8089:     my $now = time;
                   8090:     foreach my $block (keys(%commblocks)) {
                   8091:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8092:             my ($start,$end) = ($1,$2);
                   8093:             if ($start <= $now && $end >= $now) {
                   8094:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8095:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8096:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8097:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8098:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8099:                             }
                   8100:                         }
                   8101:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8102:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8103:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8104:                             }
                   8105:                         }
                   8106:                     }
                   8107:                 }
                   8108:             }
                   8109:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8110:             my $item = $1;
1.1163    raeburn  8111:             my @to_test;
1.1162    raeburn  8112:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8113:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8114:                     my @interval;
                   8115:                     my $type = 'map';
                   8116:                     if ($item eq 'course') {
                   8117:                         $type = 'course';
                   8118:                         @interval=&EXT("resource.0.interval");
                   8119:                     } else {
                   8120:                         if ($item =~ /___\d+___/) {
                   8121:                             $type = 'resource';
                   8122:                             @interval=&EXT("resource.0.interval",$item);
                   8123:                             if (ref($navmap)) {                        
                   8124:                                 my $res = $navmap->getBySymb($item); 
                   8125:                                 push(@to_test,$res);
                   8126:                             }
1.1162    raeburn  8127:                         } else {
1.1282    raeburn  8128:                             my $mapsymb = &symbread($item,1);
                   8129:                             if ($mapsymb) {
                   8130:                                 if (ref($navmap)) {
                   8131:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8132:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8133:                                     foreach my $res (@to_test) {
                   8134:                                         my $symb = $res->symb();
                   8135:                                         next if ($symb eq $mapsymb);
                   8136:                                         if ($symb ne '') {
                   8137:                                             @interval=&EXT("resource.0.interval",$symb);
                   8138:                                             if ($interval[1] eq 'map') {
                   8139:                                                 last;
1.1162    raeburn  8140:                                             }
                   8141:                                         }
                   8142:                                     }
                   8143:                                 }
                   8144:                             }
                   8145:                         }
1.1282    raeburn  8146:                     }
1.1310    raeburn  8147:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8148:                         my $timelimit = $1; 
1.1282    raeburn  8149:                         my $first_access;
                   8150:                         if ($type eq 'resource') {
                   8151:                             $first_access=&get_first_access($interval[1],$item);
                   8152:                         } elsif ($type eq 'map') {
                   8153:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8154:                         } else {
                   8155:                             $first_access=&get_first_access($interval[1]);
                   8156:                         }
                   8157:                         if ($first_access) {
1.1292    raeburn  8158:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8159:                             if ($timesup > $now) {
                   8160:                                 my $activeblock;
                   8161:                                 foreach my $res (@to_test) {
1.1283    raeburn  8162:                                     if ($res->answerable()) {
1.1282    raeburn  8163:                                         $activeblock = 1;
                   8164:                                         last;
                   8165:                                     }
                   8166:                                 }
                   8167:                                 if ($activeblock) {
                   8168:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8169:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8170:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8171:                                          }
                   8172:                                     }
                   8173:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8174:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8175:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8176:                                         }
1.1162    raeburn  8177:                                     }
                   8178:                                 }
                   8179:                             }
                   8180:                         }
                   8181:                     }
                   8182:                 }
                   8183:             }
                   8184:         }
                   8185:     }
1.1282    raeburn  8186:     return %blockers;
1.1162    raeburn  8187: }
                   8188: 
1.1282    raeburn  8189: sub has_comm_blocking {
                   8190:     my ($priv,$symb,$uri,$blocks) = @_;
                   8191:     my @blockers;
                   8192:     return unless ($env{'request.course.id'});
                   8193:     return unless ($priv eq 'bre');
                   8194:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8195:     return if ($env{'request.state'} eq 'construct');
                   8196:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8197:     return unless (keys(%cachedblockers) > 0);
                   8198:     my (%possibles,@symbs);
                   8199:     if (!$symb) {
                   8200:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8201:     }
1.1282    raeburn  8202:     if ($symb) {
                   8203:         @symbs = ($symb);
                   8204:     } elsif (keys(%possibles)) { 
                   8205:         @symbs = keys(%possibles);
                   8206:     }
                   8207:     my $noblock;
                   8208:     foreach my $symb (@symbs) {
                   8209:         last if ($noblock);
                   8210:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8211:         foreach my $block (keys(%cachedblockers)) {
                   8212:             if ($block =~ /^firstaccess____(.+)$/) {
                   8213:                 my $item = $1;
                   8214:                 if (($item eq $map) || ($item eq $symb)) {
                   8215:                     $noblock = 1;
                   8216:                     last;
                   8217:                 }
                   8218:             }
                   8219:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8220:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8221:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8222:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8223:                             push(@blockers,$block);
                   8224:                         }
                   8225:                     }
                   8226:                 }
1.1162    raeburn  8227:             }
1.1282    raeburn  8228:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8229:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8230:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8231:                         push(@blockers,$block);
                   8232:                     }
                   8233:                 }
1.1162    raeburn  8234:             }
                   8235:         }
                   8236:     }
1.1282    raeburn  8237:     return if ($noblock);
                   8238:     return @blockers;
                   8239: }
1.1162    raeburn  8240: }
                   8241: 
1.1282    raeburn  8242: # -------------------------------- Deversion and split uri into path an filename   
                   8243: 
1.1133    foxr     8244: #
1.1282    raeburn  8245: #   Removes the version from a URI and
1.1133    foxr     8246: #   splits it in to its filename and path to the filename.
                   8247: #   Seems like File::Basename could have done this more clearly.
                   8248: #   Parameters:
                   8249: #      $uri   - input URI
                   8250: #   Returns:
                   8251: #     Two element list consisting of 
                   8252: #     $pathname  - the URI up to and excluding the trailing /
                   8253: #     $filename  - The part of the URI following the last /
                   8254: #  NOTE:
                   8255: #    Another realization of this is simply:
                   8256: #    use File::Basename;
                   8257: #    ...
                   8258: #    $uri = shift;
                   8259: #    $filename = basename($uri);
                   8260: #    $path     = dirname($uri);
                   8261: #    return ($filename, $path);
                   8262: #
                   8263: #     The implementation below is probably faster however.
                   8264: #
1.710     albertel 8265: sub split_uri_for_cond {
                   8266:     my $uri=&deversion(&declutter(shift));
                   8267:     my @uriparts=split(/\//,$uri);
                   8268:     my $filename=pop(@uriparts);
                   8269:     my $pathname=join('/',@uriparts);
                   8270:     return ($pathname,$filename);
                   8271: }
1.232     www      8272: # --------------------------------------------------- Is a resource on the map?
                   8273: 
                   8274: sub is_on_map {
1.710     albertel 8275:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8276:     #Trying to find the conditional for the file
1.620     albertel 8277:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8278: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8279:     if ($match) {
1.289     bowersj2 8280: 	return (1,$1);
                   8281:     } else {
1.434     www      8282: 	return (0,0);
1.289     bowersj2 8283:     }
1.12      www      8284: }
                   8285: 
1.427     www      8286: # --------------------------------------------------------- Get symb from alias
                   8287: 
                   8288: sub get_symb_from_alias {
                   8289:     my $symb=shift;
                   8290:     my ($map,$resid,$url)=&decode_symb($symb);
                   8291: # Already is a symb
                   8292:     if ($url) { return $symb; }
                   8293: # Must be an alias
                   8294:     my $aliassymb='';
                   8295:     my %bighash;
1.620     albertel 8296:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8297:                             &GDBM_READER(),0640)) {
                   8298:         my $rid=$bighash{'mapalias_'.$symb};
                   8299: 	if ($rid) {
                   8300: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8301: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8302: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8303: 	}
                   8304:         untie %bighash;
                   8305:     }
                   8306:     return $aliassymb;
                   8307: }
                   8308: 
1.12      www      8309: # ----------------------------------------------------------------- Define Role
                   8310: 
                   8311: sub definerole {
                   8312:   if (allowed('mcr','/')) {
1.1326    raeburn  8313:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8314:     foreach my $role (split(':',$sysrole)) {
                   8315: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8316:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8317:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8318: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8319:                return "refused:s:$crole&$cqual"; 
                   8320:             }
                   8321:         }
1.191     harris41 8322:     }
1.800     albertel 8323:     foreach my $role (split(':',$domrole)) {
                   8324: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8325:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8326:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8327: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8328:                return "refused:d:$crole&$cqual"; 
                   8329:             }
                   8330:         }
1.191     harris41 8331:     }
1.800     albertel 8332:     foreach my $role (split(':',$courole)) {
                   8333: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8334:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8335:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8336: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8337:                return "refused:c:$crole&$cqual"; 
                   8338:             }
                   8339:         }
1.191     harris41 8340:     }
1.1326    raeburn  8341:     my $uhome;
                   8342:     if (($uname ne '') && ($udom ne '')) {
                   8343:         $uhome = &homeserver($uname,$udom);
                   8344:         return $uhome if ($uhome eq 'no_host');
                   8345:     } else {
                   8346:         $uname = $env{'user.name'};
                   8347:         $udom = $env{'user.domain'};
                   8348:         $uhome = $env{'user.home'};
                   8349:     }
1.620     albertel 8350:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8351:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8352:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8353:     return reply($command,$uhome);
1.12      www      8354:   } else {
                   8355:     return 'refused';
                   8356:   }
1.105     harris41 8357: }
                   8358: 
                   8359: # ---------------- Make a metadata query against the network of library servers
                   8360: 
                   8361: sub metadata_query {
1.1237    raeburn  8362:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8363:     my %rhash;
1.845     albertel 8364:     my %libserv = &all_library();
1.244     matthew  8365:     my @server_list = (defined($server_array) ? @$server_array
                   8366:                                               : keys(%libserv) );
                   8367:     for my $server (@server_list) {
1.1237    raeburn  8368:         my $domains = ''; 
                   8369:         if (ref($domains_hash) eq 'HASH') {
                   8370:             $domains = $domains_hash->{$server}; 
                   8371:         }
1.118     harris41 8372: 	unless ($custom or $customshow) {
1.1237    raeburn  8373: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8374: 	    $rhash{$server}=$reply;
                   8375: 	}
                   8376: 	else {
                   8377: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8378: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8379: 			     $server);
                   8380: 	    $rhash{$server}=$reply;
                   8381: 	}
1.112     harris41 8382:     }
1.118     harris41 8383:     return \%rhash;
1.240     www      8384: }
                   8385: 
                   8386: # ----------------------------------------- Send log queries and wait for reply
                   8387: 
                   8388: sub log_query {
                   8389:     my ($uname,$udom,$query,%filters)=@_;
                   8390:     my $uhome=&homeserver($uname,$udom);
                   8391:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8392:     my $uhost=&hostname($uhome);
1.800     albertel 8393:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8394:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8395:                        $uhome);
1.479     albertel 8396:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8397:     return get_query_reply($queryid);
                   8398: }
                   8399: 
1.818     raeburn  8400: # -------------------------- Update MySQL table for portfolio file
                   8401: 
                   8402: sub update_portfolio_table {
1.821     raeburn  8403:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8404:     if ($group ne '') {
                   8405:         $file_name =~s /^\Q$group\E//;
                   8406:     }
1.818     raeburn  8407:     my $homeserver = &homeserver($uname,$udom);
                   8408:     my $queryid=
1.821     raeburn  8409:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8410:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8411:     my $reply = &get_query_reply($queryid);
                   8412:     return $reply;
                   8413: }
                   8414: 
1.899     raeburn  8415: # -------------------------- Update MySQL allusers table
                   8416: 
                   8417: sub update_allusers_table {
                   8418:     my ($uname,$udom,$names) = @_;
                   8419:     my $homeserver = &homeserver($uname,$udom);
                   8420:     my $queryid=
                   8421:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8422:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8423:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8424:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8425:                'generation='.&escape($names->{'generation'}).'%%'.
                   8426:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8427:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8428:     return;
1.899     raeburn  8429: }
                   8430: 
1.508     raeburn  8431: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8432: 
                   8433: sub fetch_enrollment_query {
1.511     raeburn  8434:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8435:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8436:     my $maxtries = 1;
1.508     raeburn  8437:     if ($context eq 'automated') {
                   8438:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8439:         $sleep = 2;
                   8440:         $loopmax = 100;
1.547     raeburn  8441:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8442:     } else {
                   8443:         $homeserver = &homeserver($cnum,$dom);
                   8444:     }
1.838     albertel 8445:     my $host=&hostname($homeserver);
1.506     raeburn  8446:     my $cmd = '';
1.1000    raeburn  8447:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8448:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8449:     }
                   8450:     $cmd =~ s/%%$//;
                   8451:     $cmd = &escape($cmd);
                   8452:     my $query = 'fetchenrollment';
1.620     albertel 8453:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8454:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8455:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8456:         return 'error: '.$queryid;
                   8457:     }
1.1317    raeburn  8458:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8459:     my $tries = 1;
                   8460:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8461:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8462:         $tries ++;
                   8463:     }
1.526     raeburn  8464:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8465:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8466:     } else {
1.901     albertel 8467:         my @responses = split(/:/,$reply);
1.1322    raeburn  8468:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8469:             foreach my $line (@responses) {
                   8470:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8471:                 $$replyref{$key} = $value;
                   8472:             }
                   8473:         } else {
1.1117    foxr     8474:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8475:             foreach my $line (@responses) {
                   8476:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8477:                 $$replyref{$key} = $value;
                   8478:                 if ($value > 0) {
1.800     albertel 8479:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8480:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8481:                         my $destname = $pathname.'/'.$filename;
                   8482:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8483:                         if ($xml_classlist =~ /^error/) {
                   8484:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8485:                         } else {
1.1359    raeburn  8486:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8487:                                 print FILE &unescape($xml_classlist);
                   8488:                                 close(FILE);
1.526     raeburn  8489:                             } else {
                   8490:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8491:                             }
                   8492:                         }
                   8493:                     }
                   8494:                 }
                   8495:             }
                   8496:         }
                   8497:         return 'ok';
                   8498:     }
                   8499:     return 'error';
                   8500: }
                   8501: 
1.242     www      8502: sub get_query_reply {
1.1317    raeburn  8503:     my ($queryid,$sleep,$loopmax) = @_;;
                   8504:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8505:         $sleep = 0.2;
                   8506:     }
                   8507:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8508:         $loopmax = 100;
                   8509:     }
1.1117    foxr     8510:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8511:     my $reply='';
1.1317    raeburn  8512:     for (1..$loopmax) {
                   8513: 	sleep($sleep);
1.240     www      8514:         if (-e $replyfile.'.end') {
1.1359    raeburn  8515: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8516: 		$reply = join('',<$fh>);
                   8517: 		close($fh);
1.240     www      8518: 	   } else { return 'error: reply_file_error'; }
1.242     www      8519:            return &unescape($reply);
                   8520: 	}
1.240     www      8521:     }
1.242     www      8522:     return 'timeout:'.$queryid;
1.240     www      8523: }
                   8524: 
                   8525: sub courselog_query {
1.241     www      8526: #
                   8527: # possible filters:
                   8528: # url: url or symb
                   8529: # username
                   8530: # domain
                   8531: # action: view, submit, grade
                   8532: # start: timestamp
                   8533: # end: timestamp
                   8534: #
1.240     www      8535:     my (%filters)=@_;
1.620     albertel 8536:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8537:     if ($filters{'url'}) {
                   8538: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8539:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8540:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8541:     }
1.620     albertel 8542:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8543:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8544:     return &log_query($cname,$cdom,'courselog',%filters);
                   8545: }
                   8546: 
                   8547: sub userlog_query {
1.858     raeburn  8548: #
                   8549: # possible filters:
                   8550: # action: log check role
                   8551: # start: timestamp
                   8552: # end: timestamp
                   8553: #
1.240     www      8554:     my ($uname,$udom,%filters)=@_;
                   8555:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8556: }
                   8557: 
1.506     raeburn  8558: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8559: 
                   8560: sub auto_run {
1.508     raeburn  8561:     my ($cnum,$cdom) = @_;
1.876     raeburn  8562:     my $response = 0;
                   8563:     my $settings;
                   8564:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8565:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8566:         $settings = $domconfig{'autoenroll'};
                   8567:         if ($settings->{'run'} eq '1') {
                   8568:             $response = 1;
                   8569:         }
                   8570:     } else {
1.934     raeburn  8571:         my $homeserver;
                   8572:         if (&is_course($cdom,$cnum)) {
                   8573:             $homeserver = &homeserver($cnum,$cdom);
                   8574:         } else {
                   8575:             $homeserver = &domain($cdom,'primary');
                   8576:         }
                   8577:         if ($homeserver ne 'no_host') {
                   8578:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8579:         }
1.876     raeburn  8580:     }
1.506     raeburn  8581:     return $response;
                   8582: }
1.776     albertel 8583: 
1.506     raeburn  8584: sub auto_get_sections {
1.508     raeburn  8585:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8586:     my $homeserver;
                   8587:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8588:         $homeserver = &homeserver($cnum,$cdom);
                   8589:     }
                   8590:     if (!defined($homeserver)) { 
                   8591:         if ($cdom =~ /^$match_domain$/) {
                   8592:             $homeserver = &domain($cdom,'primary');
                   8593:         }
                   8594:     }
                   8595:     my @secs;
                   8596:     if (defined($homeserver)) {
                   8597:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8598:         unless ($response eq 'refused') {
                   8599:             @secs = split(/:/,$response);
                   8600:         }
1.506     raeburn  8601:     }
                   8602:     return @secs;
                   8603: }
1.776     albertel 8604: 
1.506     raeburn  8605: sub auto_new_course {
1.1099    raeburn  8606:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8607:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8608:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8609:     return $response;
                   8610: }
1.776     albertel 8611: 
1.506     raeburn  8612: sub auto_validate_courseID {
1.508     raeburn  8613:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8614:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8615:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8616:     return $response;
                   8617: }
1.776     albertel 8618: 
1.1007    raeburn  8619: sub auto_validate_instcode {
1.1020    raeburn  8620:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8621:     my ($homeserver,$response);
                   8622:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8623:         $homeserver = &homeserver($cnum,$cdom);
                   8624:     }
                   8625:     if (!defined($homeserver)) {
                   8626:         if ($cdom =~ /^$match_domain$/) {
                   8627:             $homeserver = &domain($cdom,'primary');
                   8628:         }
                   8629:     }
1.1065    raeburn  8630:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8631:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8632:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8633:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8634: }
                   8635: 
1.506     raeburn  8636: sub auto_create_password {
1.873     raeburn  8637:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8638:     my ($homeserver,$response);
1.506     raeburn  8639:     my $create_passwd = 0;
                   8640:     my $authchk = '';
1.873     raeburn  8641:     if ($udom =~ /^$match_domain$/) {
                   8642:         $homeserver = &domain($udom,'primary');
                   8643:     }
                   8644:     if ($homeserver eq '') {
                   8645:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8646:             $homeserver = &homeserver($cnum,$cdom);
                   8647:         }
                   8648:     }
                   8649:     if ($homeserver eq '') {
                   8650:         $authchk = 'nodomain';
1.506     raeburn  8651:     } else {
1.873     raeburn  8652:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8653:         if ($response eq 'refused') {
                   8654:             $authchk = 'refused';
                   8655:         } else {
1.901     albertel 8656:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8657:         }
1.506     raeburn  8658:     }
                   8659:     return ($authparam,$create_passwd,$authchk);
                   8660: }
                   8661: 
1.706     raeburn  8662: sub auto_photo_permission {
                   8663:     my ($cnum,$cdom,$students) = @_;
                   8664:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8665:     my ($outcome,$perm_reqd,$conditions) = 
                   8666: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8667:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8668: 	return (undef,undef);
                   8669:     }
1.706     raeburn  8670:     return ($outcome,$perm_reqd,$conditions);
                   8671: }
                   8672: 
                   8673: sub auto_checkphotos {
                   8674:     my ($uname,$udom,$pid) = @_;
                   8675:     my $homeserver = &homeserver($uname,$udom);
                   8676:     my ($result,$resulttype);
                   8677:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8678: 				   &escape($uname).':'.&escape($pid),
                   8679: 				   $homeserver));
1.709     albertel 8680:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8681: 	return (undef,undef);
                   8682:     }
1.706     raeburn  8683:     if ($outcome) {
                   8684:         ($result,$resulttype) = split(/:/,$outcome);
                   8685:     } 
                   8686:     return ($result,$resulttype);
                   8687: }
                   8688: 
                   8689: sub auto_photochoice {
                   8690:     my ($cnum,$cdom) = @_;
                   8691:     my $homeserver = &homeserver($cnum,$cdom);
                   8692:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8693: 						       &escape($cdom),
                   8694: 						       $homeserver)));
1.709     albertel 8695:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8696: 	return (undef,undef);
                   8697:     }
1.706     raeburn  8698:     return ($update,$comment);
                   8699: }
                   8700: 
                   8701: sub auto_photoupdate {
                   8702:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8703:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8704:     my $host=&hostname($homeserver);
1.706     raeburn  8705:     my $cmd = '';
                   8706:     my $maxtries = 1;
1.800     albertel 8707:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8708:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8709:     }
                   8710:     $cmd =~ s/%%$//;
                   8711:     $cmd = &escape($cmd);
                   8712:     my $query = 'institutionalphotos';
                   8713:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8714:     unless ($queryid=~/^\Q$host\E\_/) {
                   8715:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8716:         return 'error: '.$queryid;
                   8717:     }
                   8718:     my $reply = &get_query_reply($queryid);
                   8719:     my $tries = 1;
                   8720:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8721:         $reply = &get_query_reply($queryid);
                   8722:         $tries ++;
                   8723:     }
                   8724:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8725:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8726:     } else {
                   8727:         my @responses = split(/:/,$reply);
                   8728:         my $outcome = shift(@responses); 
                   8729:         foreach my $item (@responses) {
                   8730:             my ($key,$value) = split(/=/,$item);
                   8731:             $$photo{$key} = $value;
                   8732:         }
                   8733:         return $outcome;
                   8734:     }
                   8735:     return 'error';
                   8736: }
                   8737: 
1.521     raeburn  8738: sub auto_instcode_format {
1.793     albertel 8739:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8740: 	$cat_order) = @_;
1.521     raeburn  8741:     my $courses = '';
1.772     raeburn  8742:     my @homeservers;
1.521     raeburn  8743:     if ($caller eq 'global') {
1.841     albertel 8744: 	my %servers = &get_servers($codedom,'library');
                   8745: 	foreach my $tryserver (keys(%servers)) {
                   8746: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8747: 		push(@homeservers,$tryserver);
                   8748: 	    }
1.584     raeburn  8749:         }
1.1022    raeburn  8750:     } elsif ($caller eq 'requests') {
                   8751:         if ($codedom =~ /^$match_domain$/) {
                   8752:             my $chome = &domain($codedom,'primary');
                   8753:             unless ($chome eq 'no_host') {
                   8754:                 push(@homeservers,$chome);
                   8755:             }
                   8756:         }
1.521     raeburn  8757:     } else {
1.772     raeburn  8758:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8759:     }
1.793     albertel 8760:     foreach my $code (keys(%{$instcodes})) {
                   8761:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8762:     }
                   8763:     chop($courses);
1.772     raeburn  8764:     my $ok_response = 0;
                   8765:     my $response;
                   8766:     while (@homeservers > 0 && $ok_response == 0) {
                   8767:         my $server = shift(@homeservers); 
                   8768:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8769:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8770:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8771: 		split(/:/,$response);
1.772     raeburn  8772:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8773:             push(@{$codetitles},&str2array($codetitles_str));
                   8774:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8775:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8776:             $ok_response = 1;
                   8777:         }
                   8778:     }
                   8779:     if ($ok_response) {
1.521     raeburn  8780:         return 'ok';
1.772     raeburn  8781:     } else {
                   8782:         return $response;
1.521     raeburn  8783:     }
                   8784: }
                   8785: 
1.792     raeburn  8786: sub auto_instcode_defaults {
                   8787:     my ($domain,$returnhash,$code_order) = @_;
                   8788:     my @homeservers;
1.841     albertel 8789: 
                   8790:     my %servers = &get_servers($domain,'library');
                   8791:     foreach my $tryserver (keys(%servers)) {
                   8792: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8793: 	    push(@homeservers,$tryserver);
                   8794: 	}
1.792     raeburn  8795:     }
1.841     albertel 8796: 
1.792     raeburn  8797:     my $response;
1.841     albertel 8798:     foreach my $server (@homeservers) {
1.792     raeburn  8799:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8800:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8801: 	
                   8802: 	foreach my $pair (split(/\&/,$response)) {
                   8803: 	    my ($name,$value)=split(/\=/,$pair);
                   8804: 	    if ($name eq 'code_order') {
                   8805: 		@{$code_order} = split(/\&/,&unescape($value));
                   8806: 	    } else {
                   8807: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8808: 	    }
                   8809: 	}
                   8810: 	return 'ok';
1.792     raeburn  8811:     }
1.841     albertel 8812: 
                   8813:     return $response;
1.1003    raeburn  8814: }
                   8815: 
                   8816: sub auto_possible_instcodes {
1.1007    raeburn  8817:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8818:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8819:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8820:         return;
                   8821:     }
1.1003    raeburn  8822:     my (@homeservers,$uhome);
                   8823:     if (defined(&domain($domain,'primary'))) {
                   8824:         $uhome=&domain($domain,'primary');
                   8825:         push(@homeservers,&domain($domain,'primary'));
                   8826:     } else {
                   8827:         my %servers = &get_servers($domain,'library');
                   8828:         foreach my $tryserver (keys(%servers)) {
                   8829:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8830:                 push(@homeservers,$tryserver);
                   8831:             }
                   8832:         }
                   8833:     }
                   8834:     my $response;
                   8835:     foreach my $server (@homeservers) {
                   8836:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8837:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8838:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8839:             split(':',$response);
                   8840:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8841:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8842:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8843:             my ($name,$value)=split('=',$item);
                   8844:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8845:         }
                   8846:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8847:             my ($name,$value)=split('=',$item);
                   8848:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8849:         }
                   8850:         return 'ok';
                   8851:     }
                   8852:     return $response;
                   8853: }
1.792     raeburn  8854: 
1.1010    raeburn  8855: sub auto_courserequest_checks {
                   8856:     my ($dom) = @_;
1.1020    raeburn  8857:     my ($homeserver,%validations);
                   8858:     if ($dom =~ /^$match_domain$/) {
                   8859:         $homeserver = &domain($dom,'primary');
                   8860:     }
                   8861:     unless ($homeserver eq 'no_host') {
                   8862:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8863:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8864:             my @items = split(/&/,$response);
                   8865:             foreach my $item (@items) {
                   8866:                 my ($key,$value) = split('=',$item);
                   8867:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8868:             }
                   8869:         }
                   8870:     }
1.1010    raeburn  8871:     return %validations; 
                   8872: }
                   8873: 
1.1020    raeburn  8874: sub auto_courserequest_validation {
1.1255    raeburn  8875:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8876:     my ($homeserver,$response);
                   8877:     if ($dom =~ /^$match_domain$/) {
                   8878:         $homeserver = &domain($dom,'primary');
                   8879:     }
1.1255    raeburn  8880:     unless ($homeserver eq 'no_host') {
                   8881:         my $customdata;
                   8882:         if (ref($custominfo) eq 'HASH') {
                   8883:             $customdata = &freeze_escape($custominfo);
                   8884:         }
1.1020    raeburn  8885:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8886:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8887:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8888:                                     $customdata,$homeserver));
1.1020    raeburn  8889:     }
                   8890:     return $response;
                   8891: }
                   8892: 
1.777     albertel 8893: sub auto_validate_class_sec {
1.918     raeburn  8894:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8895:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8896:     my $ownerlist;
                   8897:     if (ref($owners) eq 'ARRAY') {
                   8898:         $ownerlist = join(',',@{$owners});
                   8899:     } else {
                   8900:         $ownerlist = $owners;
                   8901:     }
1.773     raeburn  8902:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8903:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8904:     return $response;
                   8905: }
                   8906: 
1.1367    raeburn  8907: sub auto_validate_instclasses {
                   8908:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8909:     my ($homeserver,%validations);
                   8910:     $homeserver = &homeserver($cnum,$cdom);
                   8911:     unless ($homeserver eq 'no_host') {
                   8912:         my $ownerlist;
                   8913:         if (ref($owners) eq 'ARRAY') {
                   8914:             $ownerlist = join(',',@{$owners});
                   8915:         } else {
                   8916:             $ownerlist = $owners;
                   8917:         }
                   8918:         if (ref($classesref) eq 'HASH') {
                   8919:             my $classes = &freeze_escape($classesref);
                   8920:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8921:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8922:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8923:                 my @items = split(/&/,$response);
                   8924:                 foreach my $item (@items) {
                   8925:                     my ($key,$value) = split('=',$item);
                   8926:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8927:                 }
                   8928:             }
                   8929:         }
                   8930:     }
                   8931:     return %validations;
                   8932: }
                   8933: 
1.1248    raeburn  8934: sub auto_crsreq_update {
                   8935:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8936:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8937:     my ($homeserver,%crsreqresponse);
                   8938:     if ($cdom =~ /^$match_domain$/) {
                   8939:         $homeserver = &domain($cdom,'primary');
                   8940:     }
                   8941:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8942:         my $info;
                   8943:         if (ref($inbound) eq 'HASH') {
                   8944:             $info = &freeze_escape($inbound);
                   8945:         }
                   8946:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8947:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8948:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8949:                             &escape($title).':'.&escape($code).':'.
                   8950:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8951:                             $homeserver);
1.1248    raeburn  8952:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8953:             my @items = split(/&/,$response);
                   8954:             foreach my $item (@items) {
                   8955:                 my ($key,$value) = split('=',$item);
                   8956:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8957:             }
                   8958:         }
                   8959:     }
                   8960:     return \%crsreqresponse;
                   8961: }
                   8962: 
1.1305    raeburn  8963: sub auto_export_grades {
1.1309    raeburn  8964:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8965:     my ($homeserver,%exportresponse);
                   8966:     if ($cdom =~ /^$match_domain$/) {
                   8967:         $homeserver = &domain($cdom,'primary');
                   8968:     }
                   8969:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8970:         my $info;
                   8971:         if (ref($inforef) eq 'HASH') {
                   8972:             $info = &freeze_escape($inforef);
                   8973:         }
                   8974:         if (ref($gradesref) eq 'HASH') {
                   8975:             my $grades = &freeze_escape($gradesref);
                   8976:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8977:                                 $info.':'.$grades,$homeserver);
                   8978:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8979:                 my @items = split(/&/,$response);
                   8980:                 foreach my $item (@items) {
                   8981:                     my ($key,$value) = split('=',$item);
                   8982:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8983:                 }
                   8984:             }
                   8985:         }
                   8986:     }
                   8987:     return \%exportresponse;
1.1305    raeburn  8988: }
                   8989: 
1.1287    raeburn  8990: sub check_instcode_cloning {
                   8991:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8992:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8993:         return;
                   8994:     }
                   8995:     my $canclone;
                   8996:     if (@{$code_order} > 0) {
                   8997:         my $instcoderegexp ='^';
                   8998:         my @clonecodes = split(/\&/,$cloner);
                   8999:         foreach my $item (@{$code_order}) {
                   9000:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   9001:                 foreach my $pair (@clonecodes) {
                   9002:                     my ($key,$val) = split(/\=/,$pair,2);
                   9003:                     $val = &unescape($val);
                   9004:                     if ($key eq $item) {
                   9005:                         $instcoderegexp .= '('.$val.')';
                   9006:                         last;
                   9007:                     }
                   9008:                 }
                   9009:             } else {
                   9010:                 $instcoderegexp .= $codedefaults->{$item};
                   9011:             }
                   9012:         }
                   9013:         $instcoderegexp .= '$';
                   9014:         my (@from,@to);
                   9015:         eval {
                   9016:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9017:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9018:         };
                   9019:         if ((@from > 0) && (@to > 0)) {
                   9020:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9021:             if (!@diffs) {
                   9022:                 $canclone = 1;
                   9023:             }
                   9024:         }
                   9025:     }
                   9026:     return $canclone;
                   9027: }
                   9028: 
                   9029: sub default_instcode_cloning {
                   9030:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9031:     my (%codedefaults,@code_order,$canclone);
                   9032:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9033:         %codedefaults = %{$codedefaultsref};
                   9034:         @code_order = @{$codeorderref};
                   9035:     } elsif ($clonedom) {
                   9036:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9037:     }
                   9038:     if (($domdefclone) && (@code_order)) {
                   9039:         my @clonecodes = split(/\+/,$domdefclone);
                   9040:         my $instcoderegexp ='^';
                   9041:         foreach my $item (@code_order) {
                   9042:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9043:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9044:             } else {
                   9045:                 $instcoderegexp .= $codedefaults{$item};
                   9046:             }
                   9047:         }
                   9048:         $instcoderegexp .= '$';
                   9049:         my (@from,@to);
                   9050:         eval {
                   9051:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9052:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9053:         };
                   9054:         if ((@from > 0) && (@to > 0)) {
                   9055:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9056:             if (!@diffs) {
                   9057:                 $canclone = 1;
                   9058:             }
                   9059:         }
                   9060:     }
                   9061:     return $canclone;
                   9062: }
                   9063: 
1.679     raeburn  9064: # ------------------------------------------------------- Course Group routines
                   9065: 
                   9066: sub get_coursegroups {
1.809     raeburn  9067:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9068:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9069: }
                   9070: 
1.679     raeburn  9071: sub modify_coursegroup {
                   9072:     my ($cdom,$cnum,$groupsettings) = @_;
                   9073:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9074: }
                   9075: 
1.809     raeburn  9076: sub toggle_coursegroup_status {
                   9077:     my ($cdom,$cnum,$group,$action) = @_;
                   9078:     my ($from_namespace,$to_namespace);
                   9079:     if ($action eq 'delete') {
                   9080:         $from_namespace = 'coursegroups';
                   9081:         $to_namespace = 'deleted_groups';
                   9082:     } else {
                   9083:         $from_namespace = 'deleted_groups';
                   9084:         $to_namespace = 'coursegroups';
                   9085:     }
                   9086:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9087:     if (my $tmp = &error(%curr_group)) {
                   9088:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9089:         return ('read error',$tmp);
                   9090:     } else {
                   9091:         my %savedsettings = %curr_group; 
1.809     raeburn  9092:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9093:         my $deloutcome;
                   9094:         if ($result eq 'ok') {
1.809     raeburn  9095:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9096:         } else {
                   9097:             return ('write error',$result);
                   9098:         }
                   9099:         if ($deloutcome eq 'ok') {
                   9100:             return 'ok';
                   9101:         } else {
                   9102:             return ('delete error',$deloutcome);
                   9103:         }
                   9104:     }
                   9105: }
                   9106: 
1.679     raeburn  9107: sub modify_group_roles {
1.957     raeburn  9108:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9109:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9110:     my $role = 'gr/'.&escape($userprivs);
                   9111:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9112:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9113:     if ($result eq 'ok') {
                   9114:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9115:     }
1.679     raeburn  9116:     return $result;
                   9117: }
                   9118: 
                   9119: sub modify_coursegroup_membership {
                   9120:     my ($cdom,$cnum,$membership) = @_;
                   9121:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9122:     return $result;
                   9123: }
                   9124: 
1.682     raeburn  9125: sub get_active_groups {
                   9126:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9127:     my $now = time;
                   9128:     my %groups = ();
                   9129:     foreach my $key (keys(%env)) {
1.811     albertel 9130:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9131:             my ($start,$end) = split(/\./,$env{$key});
                   9132:             if (($end!=0) && ($end<$now)) { next; }
                   9133:             if (($start!=0) && ($start>$now)) { next; }
                   9134:             if ($1 eq $cdom && $2 eq $cnum) {
                   9135:                 $groups{$3} = $env{$key} ;
                   9136:             }
                   9137:         }
                   9138:     }
                   9139:     return %groups;
                   9140: }
                   9141: 
1.683     raeburn  9142: sub get_group_membership {
                   9143:     my ($cdom,$cnum,$group) = @_;
                   9144:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9145: }
                   9146: 
                   9147: sub get_users_groups {
                   9148:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9149:     my @usersgroups;
1.683     raeburn  9150:     my $cachetime=1800;
                   9151: 
                   9152:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9153:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9154:     if (defined($cached)) {
1.734     albertel 9155:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9156:     } else {  
                   9157:         $grouplist = '';
1.816     raeburn  9158:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9159:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9160:         my $access_end = $env{'course.'.$courseid.
                   9161:                               '.default_enrollment_end_date'};
                   9162:         my $now = time;
                   9163:         foreach my $key (keys(%roleshash)) {
                   9164:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9165:                 my $group = $1;
                   9166:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9167:                     my $start = $2;
                   9168:                     my $end = $1;
                   9169:                     if ($start == -1) { next; } # deleted from group
                   9170:                     if (($start!=0) && ($start>$now)) { next; }
                   9171:                     if (($end!=0) && ($end<$now)) {
                   9172:                         if ($access_end && $access_end < $now) {
                   9173:                             if ($access_end - $end < 86400) {
                   9174:                                 push(@usersgroups,$group);
1.733     raeburn  9175:                             }
                   9176:                         }
1.817     raeburn  9177:                         next;
1.733     raeburn  9178:                     }
1.817     raeburn  9179:                     push(@usersgroups,$group);
1.683     raeburn  9180:                 }
                   9181:             }
                   9182:         }
1.817     raeburn  9183:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9184:         $grouplist = join(':',@usersgroups);
                   9185:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9186:     }
1.733     raeburn  9187:     return @usersgroups;
1.683     raeburn  9188: }
                   9189: 
                   9190: sub devalidate_getgroups_cache {
                   9191:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9192:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9193: 
1.683     raeburn  9194:     my $hashid="$udom:$uname:$courseid";
                   9195:     &devalidate_cache_new('getgroups',$hashid);
                   9196: }
                   9197: 
1.12      www      9198: # ------------------------------------------------------------------ Plain Text
                   9199: 
                   9200: sub plaintext {
1.988     raeburn  9201:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9202:     if ($short =~ m{^cr/}) {
1.758     albertel 9203: 	return (split('/',$short))[-1];
                   9204:     }
1.742     raeburn  9205:     if (!defined($cid)) {
                   9206:         $cid = $env{'request.course.id'};
                   9207:     }
                   9208:     my %rolenames = (
1.1008    raeburn  9209:                       Course    => 'std',
                   9210:                       Community => 'alt1',
1.1305    raeburn  9211:                       Placement => 'std',
1.742     raeburn  9212:                     );
1.1037    raeburn  9213:     if ($cid ne '') {
                   9214:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9215:             unless ($forcedefault) {
                   9216:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9217:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9218:                 return &Apache::lonlocal::mt($roletext);
                   9219:             }
                   9220:         }
                   9221:     }
                   9222:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9223:         (defined($rolenames{$type})) && 
                   9224:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9225:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9226:     } elsif ($cid ne '') {
                   9227:         my $crstype = $env{'course.'.$cid.'.type'};
                   9228:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9229:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9230:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9231:         }
1.742     raeburn  9232:     }
1.1037    raeburn  9233:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9234: }
                   9235: 
                   9236: # ----------------------------------------------------------------- Assign Role
                   9237: 
                   9238: sub assignrole {
1.957     raeburn  9239:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9240:         $context)=@_;
1.21      www      9241:     my $mrole;
                   9242:     if ($role =~ /^cr\//) {
1.393     www      9243:         my $cwosec=$url;
1.811     albertel 9244:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9245: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9246:            my $refused = 1;
                   9247:            if ($context eq 'requestcourses') {
                   9248:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9249:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9250:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9251:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9252:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9253:                            if ($crsenv{'internal.courseowner'} eq
                   9254:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9255:                                $refused = '';
                   9256:                            }
                   9257:                        }
                   9258:                    }
                   9259:                }
                   9260:            }
                   9261:            if ($refused) {
                   9262:                &logthis('Refused custom assignrole: '.
                   9263:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9264:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9265:                return 'refused';
                   9266:            }
1.104     www      9267:         }
1.21      www      9268:         $mrole='cr';
1.678     raeburn  9269:     } elsif ($role =~ /^gr\//) {
                   9270:         my $cwogrp=$url;
1.811     albertel 9271:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9272:         unless (&allowed('mdg',$cwogrp)) {
                   9273:             &logthis('Refused group assignrole: '.
                   9274:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9275:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9276:             return 'refused';
                   9277:         }
                   9278:         $mrole='gr';
1.21      www      9279:     } else {
1.82      www      9280:         my $cwosec=$url;
1.811     albertel 9281:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9282:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9283:             my $refused;
                   9284:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9285:                 if (!(&allowed('c'.$role,$url))) {
                   9286:                     $refused = 1;
                   9287:                 }
                   9288:             } else {
                   9289:                 $refused = 1;
                   9290:             }
1.947     raeburn  9291:             if ($refused) {
1.1045    raeburn  9292:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9293:                 if (!$selfenroll && $context eq 'course') {
                   9294:                     my %crsenv;
                   9295:                     if ($role eq 'cc' || $role eq 'co') {
                   9296:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9297:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9298:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9299:                                 if ($crsenv{'internal.courseowner'} eq 
                   9300:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9301:                                     $refused = '';
                   9302:                                 }
                   9303:                             }
                   9304:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9305:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9306:                                 if ($crsenv{'internal.courseowner'} eq 
                   9307:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9308:                                     $refused = '';
                   9309:                                 }
                   9310:                             }
                   9311:                         }
                   9312:                     }
1.1368    raeburn  9313:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9314:                     if ($role eq 'st') {
                   9315:                         $refused = '';
                   9316:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti'})) {
                   9317:                         $refused = '';
                   9318:                     }
1.1017    raeburn  9319:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9320:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9321:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9322:                         my $wrongcc;
                   9323:                         if ($cnum =~ /^$match_community$/) {
                   9324:                             $wrongcc = 1 if ($role eq 'cc');
                   9325:                         } else {
                   9326:                             $wrongcc = 1 if ($role eq 'co');
                   9327:                         }
                   9328:                         unless ($wrongcc) {
                   9329:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9330:                             if ($crsenv{'internal.courseowner'} eq 
                   9331:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9332:                                 $refused = '';
                   9333:                             }
1.1017    raeburn  9334:                         }
                   9335:                     }
1.1183    raeburn  9336:                 } elsif ($context eq 'requestauthor') {
                   9337:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9338:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9339:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9340:                             $refused = '';
                   9341:                         } else {
                   9342:                             my %domdefaults = &get_domain_defaults($udom);
                   9343:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9344:                                 my $checkbystatus;
                   9345:                                 if ($env{'user.adv'}) { 
                   9346:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9347:                                     if ($disposition eq 'automatic') {
                   9348:                                         $refused = '';
                   9349:                                     } elsif ($disposition eq '') {
                   9350:                                         $checkbystatus = 1;
                   9351:                                     } 
                   9352:                                 } else {
                   9353:                                     $checkbystatus = 1;
                   9354:                                 }
                   9355:                                 if ($checkbystatus) {
                   9356:                                     if ($env{'environment.inststatus'}) {
                   9357:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9358:                                         foreach my $type (@inststatuses) {
                   9359:                                             if (($type ne '') &&
                   9360:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9361:                                                 $refused = '';
                   9362:                                             }
                   9363:                                         }
                   9364:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9365:                                         $refused = '';
                   9366:                                     }
                   9367:                                 }
                   9368:                             }
                   9369:                         }
                   9370:                     }
1.1017    raeburn  9371:                 }
                   9372:                 if ($refused) {
1.947     raeburn  9373:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9374:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9375: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9376:                     return 'refused';
                   9377:                 }
1.932     raeburn  9378:             }
1.1131    raeburn  9379:         } elsif ($role eq 'au') {
                   9380:             if ($url ne '/'.$udom.'/') {
                   9381:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9382:                          ' to assign author role for '.$uname.':'.$udom.
                   9383:                          ' in domain: '.$url.' refused (wrong domain).');
                   9384:                 return 'refused';
                   9385:             }
1.104     www      9386:         }
1.21      www      9387:         $mrole=$role;
                   9388:     }
1.620     albertel 9389:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9390:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9391:     if ($end) { $command.='_'.$end; }
1.21      www      9392:     if ($start) {
                   9393: 	if ($end) { 
1.81      www      9394:            $command.='_'.$start; 
1.21      www      9395:         } else {
1.81      www      9396:            $command.='_0_'.$start;
1.21      www      9397:         }
                   9398:     }
1.739     raeburn  9399:     my $origstart = $start;
                   9400:     my $origend = $end;
1.957     raeburn  9401:     my $delflag;
1.357     www      9402: # actually delete
                   9403:     if ($deleteflag) {
1.373     www      9404: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9405: # modify command to delete the role
1.620     albertel 9406:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9407:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9408: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9409: # set start and finish to negative values for userrolelog
                   9410:            $start=-1;
                   9411:            $end=-1;
1.957     raeburn  9412:            $delflag = 1;
1.357     www      9413:         }
                   9414:     }
                   9415: # send command
1.349     www      9416:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9417: # log new user role if status is ok
1.349     www      9418:     if ($answer eq 'ok') {
1.663     raeburn  9419: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9420:         if (($role eq 'cc') || ($role eq 'in') ||
                   9421:             ($role eq 'ep') || ($role eq 'ad') ||
                   9422:             ($role eq 'ta') || ($role eq 'st') ||
                   9423:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9424:             ($role eq 'co')) {
1.1200    raeburn  9425: # for course roles, perform group memberships changes triggered by role change.
                   9426:             unless ($role =~ /^gr/) {
                   9427:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9428:                                                  $origstart,$selfenroll,$context);
                   9429:             }
1.1184    raeburn  9430:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9431:                            $selfenroll,$context);
                   9432:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9433:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9434:                  ($role eq 'da')) {
1.1184    raeburn  9435:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9436:                            $context);
                   9437:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9438:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9439:                              $context); 
                   9440:         }
1.1053    raeburn  9441:         if ($role eq 'cc') {
                   9442:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9443:         }
1.349     www      9444:     }
                   9445:     return $answer;
1.169     harris41 9446: }
                   9447: 
1.1053    raeburn  9448: sub autoupdate_coowners {
                   9449:     my ($url,$end,$start,$uname,$udom) = @_;
                   9450:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9451:     if (($cdom ne '') && ($cnum ne '')) {
                   9452:         my $now = time;
                   9453:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9454:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9455:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9456:             my $instcode = $coursehash{'internal.coursecode'};
                   9457:             if ($instcode ne '') {
1.1056    raeburn  9458:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9459:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9460:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9461:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9462:                         if ($result eq 'valid') {
                   9463:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9464:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9465:                                     push(@newcoowners,$coowner);
                   9466:                                 }
                   9467:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9468:                                     push(@newcoowners,$uname.':'.$udom);
                   9469:                                 }
                   9470:                                 @newcoowners = sort(@newcoowners);
                   9471:                             } else {
                   9472:                                 push(@newcoowners,$uname.':'.$udom);
                   9473:                             }
                   9474:                         } else {
                   9475:                             if ($coursehash{'internal.co-owners'}) {
                   9476:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9477:                                     unless ($coowner eq $uname.':'.$udom) {
                   9478:                                         push(@newcoowners,$coowner);
                   9479:                                     }
                   9480:                                 }
                   9481:                                 unless (@newcoowners > 0) {
                   9482:                                     $delcoowners = 1;
                   9483:                                     $coowners = '';
                   9484:                                 }
                   9485:                             }
                   9486:                         }
                   9487:                         if (@newcoowners || $delcoowners) {
                   9488:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9489:                                             $delcoowners,@newcoowners);
                   9490:                         }
                   9491:                     }
                   9492:                 }
                   9493:             }
                   9494:         }
                   9495:     }
                   9496: }
                   9497: 
                   9498: sub store_coowners {
                   9499:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9500:     my $cid = $cdom.'_'.$cnum;
                   9501:     my ($coowners,$delresult,$putresult);
                   9502:     if (@newcoowners) {
                   9503:         $coowners = join(',',@newcoowners);
                   9504:         my %coownershash = (
                   9505:                             'internal.co-owners' => $coowners,
                   9506:                            );
                   9507:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9508:         if ($putresult eq 'ok') {
                   9509:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9510:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9511:             }
                   9512:         }
                   9513:     }
                   9514:     if ($delcoowners) {
                   9515:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9516:         if ($delresult eq 'ok') {
                   9517:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9518:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9519:             }
                   9520:         }
                   9521:     }
                   9522:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9523:         my %crsinfo =
                   9524:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9525:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9526:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9527:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9528:         }
                   9529:     }
                   9530: }
                   9531: 
1.169     harris41 9532: # -------------------------------------------------- Modify user authentication
1.197     www      9533: # Overrides without validation
                   9534: 
1.169     harris41 9535: sub modifyuserauth {
                   9536:     my ($udom,$uname,$umode,$upass)=@_;
                   9537:     my $uhome=&homeserver($uname,$udom);
1.197     www      9538:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9539:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9540:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9541:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9542:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9543: 		     &escape($upass),$uhome);
1.620     albertel 9544:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9545:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9546:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9547:     &log($udom,,$uname,$uhome,
1.620     albertel 9548:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9549:                                      $env{'user.name'}.', '.$umode.
1.197     www      9550:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9551:     unless ($reply eq 'ok') {
1.197     www      9552:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9553: 	return 'error: '.$reply;
                   9554:     }   
1.170     harris41 9555:     return 'ok';
1.80      www      9556: }
                   9557: 
1.81      www      9558: # --------------------------------------------------------------- Modify a user
1.80      www      9559: 
1.81      www      9560: sub modifyuser {
1.206     matthew  9561:     my ($udom,    $uname, $uid,
                   9562:         $umode,   $upass, $first,
                   9563:         $middle,  $last,  $gene,
1.1058    raeburn  9564:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9565:     $udom= &LONCAPA::clean_domain($udom);
                   9566:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9567:     my $showcandelete = 'none';
                   9568:     if (ref($candelete) eq 'ARRAY') {
                   9569:         if (@{$candelete} > 0) {
                   9570:             $showcandelete = join(', ',@{$candelete});
                   9571:         }
                   9572:     }
1.81      www      9573:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9574:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9575: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9576:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9577:                                      ' desiredhome not specified'). 
1.620     albertel 9578:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9579:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9580:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9581:     my $newuser;
                   9582:     if ($uhome eq 'no_host') {
                   9583:         $newuser = 1;
1.1368    raeburn  9584:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9585:                 ($umode eq 'lti')) {
                   9586:             return 'error: more information needed to create new user';
                   9587:         }
1.1075    raeburn  9588:     }
1.80      www      9589: # ----------------------------------------------------------------- Create User
1.406     albertel 9590:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9591: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9592:         my $unhome='';
1.844     albertel 9593:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9594:             $unhome = $desiredhome;
1.620     albertel 9595: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9596: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9597:         } else { # load balancing routine for determining $unhome
1.81      www      9598:             my $loadm=10000000;
1.841     albertel 9599: 	    my %servers = &get_servers($udom,'library');
                   9600: 	    foreach my $tryserver (keys(%servers)) {
                   9601: 		my $answer=reply('load',$tryserver);
                   9602: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9603: 		    $loadm=$answer;
                   9604: 		    $unhome=$tryserver;
                   9605: 		}
1.80      www      9606: 	    }
                   9607:         }
                   9608:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9609: 	    return 'error: unable to find a home server for '.$uname.
                   9610:                    ' in domain '.$udom;
1.80      www      9611:         }
                   9612:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9613:                          &escape($upass),$unhome);
                   9614: 	unless ($reply eq 'ok') {
                   9615:             return 'error: '.$reply;
                   9616:         }   
1.230     stredwic 9617:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9618:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9619: 	    return 'error: unable verify users home machine.';
1.80      www      9620:         }
1.209     matthew  9621:     }   # End of creation of new user
1.80      www      9622: # ---------------------------------------------------------------------- Add ID
                   9623:     if ($uid) {
                   9624:        $uid=~tr/A-Z/a-z/;
                   9625:        my %uidhash=&idrget($udom,$uname);
1.196     www      9626:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9627:          && (!$forceid)) {
1.80      www      9628: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9629: 	      return 'error: user id "'.$uid.'" does not match '.
                   9630:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9631:           }
                   9632:        } else {
1.1300    raeburn  9633: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9634:        }
                   9635:     }
                   9636: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9637:     my @tmp=&get('environment',
1.899     raeburn  9638: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9639:                     'permanentemail','inststatus'],
1.134     albertel 9640: 		   $udom,$uname);
1.1075    raeburn  9641:     my (%names,%oldnames);
1.313     matthew  9642:     if ($tmp[0] =~ m/^error:.*/) { 
                   9643:         %names=(); 
                   9644:     } else {
                   9645:         %names = @tmp;
1.1075    raeburn  9646:         %oldnames = %names;
1.313     matthew  9647:     }
1.388     www      9648: #
1.1058    raeburn  9649: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9650: # of users did not contain them), do not overwrite existing values
                   9651: # unless field is in $candelete array ref.  
                   9652: #
                   9653: 
                   9654:     my @fields = ('firstname','middlename','lastname','generation',
                   9655:                   'permanentemail','id');
                   9656:     my %newvalues;
                   9657:     if (ref($candelete) eq 'ARRAY') {
                   9658:         foreach my $field (@fields) {
                   9659:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9660:                 if ($field eq 'firstname') {
                   9661:                     $names{$field} = $first;
                   9662:                 } elsif ($field eq 'middlename') {
                   9663:                     $names{$field} = $middle;
                   9664:                 } elsif ($field eq 'lastname') {
                   9665:                     $names{$field} = $last;
                   9666:                 } elsif ($field eq 'generation') { 
                   9667:                     $names{$field} = $gene;
                   9668:                 } elsif ($field eq 'permanentemail') {
                   9669:                     $names{$field} = $email;
                   9670:                 } elsif ($field eq 'id') {
                   9671:                     $names{$field}  = $uid;
                   9672:                 }
                   9673:             }
                   9674:         }
                   9675:     }
1.388     www      9676:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9677:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9678:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9679:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9680:     if ($email) {
                   9681:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9682:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9683:     }
1.899     raeburn  9684:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9685:     if (defined($inststatus)) {
                   9686:         $names{'inststatus'} = '';
                   9687:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9688:         if (ref($usertypes) eq 'HASH') {
                   9689:             my @okstatuses; 
                   9690:             foreach my $item (split(/:/,$inststatus)) {
                   9691:                 if (defined($usertypes->{$item})) {
                   9692:                     push(@okstatuses,$item);  
                   9693:                 }
                   9694:             }
                   9695:             if (@okstatuses) {
                   9696:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9697:             }
                   9698:         }
                   9699:     }
1.1075    raeburn  9700:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9701:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9702:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9703:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9704:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9705:     } else {
                   9706:         $logmsg .= ' during self creation';
                   9707:     }
1.1075    raeburn  9708:     my $changed;
                   9709:     if ($newuser) {
                   9710:         $changed = 1;
                   9711:     } else {
                   9712:         foreach my $field (@fields) {
                   9713:             if ($names{$field} ne $oldnames{$field}) {
                   9714:                 $changed = 1;
                   9715:                 last;
                   9716:             }
                   9717:         }
                   9718:     }
                   9719:     unless ($changed) {
                   9720:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9721:         &logthis($logmsg);
                   9722:         return 'ok';
                   9723:     }
                   9724:     my $reply = &put('environment', \%names, $udom,$uname);
                   9725:     if ($reply ne 'ok') { 
                   9726:         return 'error: '.$reply;
                   9727:     }
1.1087    raeburn  9728:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9729:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9730:     }
1.1075    raeburn  9731:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9732:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9733:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9734:     &logthis($logmsg);
1.134     albertel 9735:     return 'ok';
1.80      www      9736: }
                   9737: 
1.81      www      9738: # -------------------------------------------------------------- Modify student
1.80      www      9739: 
1.81      www      9740: sub modifystudent {
                   9741:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9742:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9743:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9744:     if (!$cid) {
1.620     albertel 9745: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9746: 	    return 'not_in_class';
                   9747: 	}
1.80      www      9748:     }
                   9749: # --------------------------------------------------------------- Make the user
1.81      www      9750:     my $reply=&modifyuser
1.209     matthew  9751: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9752:          $desiredhome,$email,$inststatus);
1.80      www      9753:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9754:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9755:     # student's environment
1.297     matthew  9756:     $uid = undef if (!$forceid);
1.455     albertel 9757:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9758:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9759:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9760:     return $reply;
                   9761: }
                   9762: 
                   9763: sub modify_student_enrollment {
1.1216    raeburn  9764:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9765:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9766:     my ($cdom,$cnum,$chome);
                   9767:     if (!$cid) {
1.620     albertel 9768: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9769: 	    return 'not_in_class';
                   9770: 	}
1.620     albertel 9771: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9772: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9773:     } else {
                   9774: 	($cdom,$cnum)=split(/_/,$cid);
                   9775:     }
1.620     albertel 9776:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9777:     if (!$chome) {
1.457     raeburn  9778: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9779:     }
1.455     albertel 9780:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9781:     # Make sure the user exists
1.81      www      9782:     my $uhome=&homeserver($uname,$udom);
                   9783:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9784: 	return 'error: no such user';
                   9785:     }
1.297     matthew  9786:     # Get student data if we were not given enough information
                   9787:     if (!defined($first)  || $first  eq '' || 
                   9788:         !defined($last)   || $last   eq '' || 
                   9789:         !defined($uid)    || $uid    eq '' || 
                   9790:         !defined($middle) || $middle eq '' || 
                   9791:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9792:         # They did not supply us with enough data to enroll the student, so
                   9793:         # we need to pick up more information.
1.297     matthew  9794:         my %tmp = &get('environment',
1.294     matthew  9795:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9796:                        ,$udom,$uname);
                   9797: 
1.800     albertel 9798:         #foreach my $key (keys(%tmp)) {
                   9799:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9800:         #}
1.294     matthew  9801:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9802:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9803:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9804:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9805:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9806:     }
1.556     albertel 9807:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9808:     my $user = "$uname:$udom";
                   9809:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9810:     my $reply=cput('classlist',
1.1148    raeburn  9811: 		   {$user => 
1.1314    raeburn  9812: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9813: 		   $cdom,$cnum);
1.1148    raeburn  9814:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9815:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9816:     } else { 
1.81      www      9817: 	return 'error: '.$reply;
                   9818:     }
1.297     matthew  9819:     # Add student role to user
1.83      www      9820:     my $uurl='/'.$cid;
1.81      www      9821:     $uurl=~s/\_/\//g;
                   9822:     if ($usec) {
                   9823: 	$uurl.='/'.$usec;
                   9824:     }
1.1148    raeburn  9825:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9826:                              $selfenroll,$context);
                   9827:     if ($result ne 'ok') {
                   9828:         if ($old_entry{$user} ne '') {
                   9829:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9830:         } else {
                   9831:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9832:         }
                   9833:     }
                   9834:     return $result; 
1.21      www      9835: }
                   9836: 
1.556     albertel 9837: sub format_name {
                   9838:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9839:     my $name;
                   9840:     if ($first ne 'lastname') {
                   9841: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9842:     } else {
                   9843: 	if ($lastname=~/\S/) {
                   9844: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9845: 	    $name=~s/\s+,/,/;
                   9846: 	} else {
                   9847: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9848: 	}
                   9849:     }
                   9850:     $name=~s/^\s+//;
                   9851:     $name=~s/\s+$//;
                   9852:     $name=~s/\s+/ /g;
                   9853:     return $name;
                   9854: }
                   9855: 
1.84      www      9856: # ------------------------------------------------- Write to course preferences
                   9857: 
                   9858: sub writecoursepref {
                   9859:     my ($courseid,%prefs)=@_;
                   9860:     $courseid=~s/^\///;
                   9861:     $courseid=~s/\_/\//g;
                   9862:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9863:     my $chome=homeserver($cnum,$cdomain);
                   9864:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9865: 	return 'error: no such course';
                   9866:     }
                   9867:     my $cstring='';
1.800     albertel 9868:     foreach my $pref (keys(%prefs)) {
                   9869: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9870:     }
1.84      www      9871:     $cstring=~s/\&$//;
                   9872:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9873: }
                   9874: 
                   9875: # ---------------------------------------------------------- Make/modify course
                   9876: 
                   9877: sub createcourse {
1.741     raeburn  9878:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9879:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9880:     $url=&declutter($url);
                   9881:     my $cid='';
1.1028    raeburn  9882:     if ($context eq 'requestcourses') {
                   9883:         my $can_create = 0;
                   9884:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9885:         if ($udom eq $ownerdom) {
                   9886:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9887:                                   $context)) {
                   9888:                 $can_create = 1;
                   9889:             }
                   9890:         } else {
                   9891:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9892:                                            $category);
                   9893:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9894:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9895:                 if (@curr > 0) {
                   9896:                     my @options = qw(approval validate autolimit);
                   9897:                     my $optregex = join('|',@options);
                   9898:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9899:                         $can_create = 1;
                   9900:                     }
                   9901:                 }
                   9902:             }
                   9903:         }
                   9904:         if ($can_create) {
                   9905:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9906:                 unless (&allowed('ccc',$udom)) {
                   9907:                     return 'refused'; 
                   9908:                 }
1.1017    raeburn  9909:             }
                   9910:         } else {
                   9911:             return 'refused';
                   9912:         }
1.1028    raeburn  9913:     } elsif (!&allowed('ccc',$udom)) {
                   9914:         return 'refused';
1.84      www      9915:     }
1.1011    raeburn  9916: # --------------------------------------------------------------- Get Unique ID
                   9917:     my $uname;
                   9918:     if ($cnum =~ /^$match_courseid$/) {
                   9919:         my $chome=&homeserver($cnum,$udom,'true');
                   9920:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9921:             $uname = $cnum;
                   9922:         } else {
1.1038    raeburn  9923:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9924:         }
                   9925:     } else {
1.1038    raeburn  9926:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9927:     }
                   9928:     return $uname if ($uname =~ /^error/);
                   9929: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9930:     if (!defined($course_server)) {
                   9931:         if (defined(&domain($udom,'primary'))) {
                   9932:             $course_server = &domain($udom,'primary');
                   9933:         } else {
                   9934:             $course_server = $env{'user.home'}; 
                   9935:         }
                   9936:     }
                   9937:     my %host_servers =
                   9938:         &Apache::lonnet::get_servers($udom,'library');
                   9939:     unless ($host_servers{$course_server}) {
                   9940:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9941:     }
1.84      www      9942: # ------------------------------------------------------------- Make the course
                   9943:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9944:                       $course_server);
1.84      www      9945:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9946:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9947:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9948: 	return 'error: no such course';
                   9949:     }
1.271     www      9950: # ----------------------------------------------------------------- Course made
1.516     raeburn  9951: # log existence
1.1029    raeburn  9952:     my $now = time;
1.918     raeburn  9953:     my $newcourse = {
                   9954:                     $udom.'_'.$uname => {
1.921     raeburn  9955:                                      description => $description,
                   9956:                                      inst_code   => $inst_code,
                   9957:                                      owner       => $course_owner,
                   9958:                                      type        => $crstype,
1.1029    raeburn  9959:                                      creator     => $env{'user.name'}.':'.
                   9960:                                                     $env{'user.domain'},
                   9961:                                      created     => $now,
                   9962:                                      context     => $context,
1.918     raeburn  9963:                                                 },
                   9964:                     };
1.921     raeburn  9965:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9966: # set toplevel url
1.271     www      9967:     my $topurl=$url;
                   9968:     unless ($nonstandard) {
                   9969: # ------------------------------------------ For standard courses, make top url
                   9970:         my $mapurl=&clutter($url);
1.278     www      9971:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9972:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9973: <map>
                   9974: <resource id="1" type="start"></resource>
                   9975: <resource id="2" src="$mapurl"></resource>
                   9976: <resource id="3" type="finish"></resource>
                   9977: <link index="1" from="1" to="2"></link>
                   9978: <link index="2" from="2" to="3"></link>
                   9979: </map>
                   9980: ENDINITMAP
                   9981:         $topurl=&declutter(
1.638     albertel 9982:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9983:                           );
                   9984:     }
                   9985: # ----------------------------------------------------------- Write preferences
1.84      www      9986:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9987:                      ('description'              => $description,
                   9988:                       'url'                      => $topurl,
                   9989:                       'internal.creator'         => $env{'user.name'}.':'.
                   9990:                                                     $env{'user.domain'},
                   9991:                       'internal.created'         => $now,
                   9992:                       'internal.creationcontext' => $context)
                   9993:                     );
1.84      www      9994:     return '/'.$udom.'/'.$uname;
                   9995: }
                   9996: 
1.1011    raeburn  9997: # ------------------------------------------------------------------- Create ID
                   9998: sub generate_coursenum {
1.1038    raeburn  9999:     my ($udom,$crstype) = @_;
1.1011    raeburn  10000:     my $domdesc = &domain($udom);
                   10001:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  10002:     my $first;
                   10003:     if ($crstype eq 'Community') {
                   10004:         $first = '0';
                   10005:     } else {
                   10006:         $first = int(1+rand(9)); 
                   10007:     } 
                   10008:     my $uname=$first.
1.1011    raeburn  10009:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10010:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10011:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10012: # ----------------------------------------------- Make sure that does not exist
                   10013:     my $uhome=&homeserver($uname,$udom,'true');
                   10014:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10015:         if ($crstype eq 'Community') {
                   10016:             $first = '0';
                   10017:         } else {
                   10018:             $first = int(1+rand(9));
                   10019:         }
                   10020:         $uname=$first.
1.1011    raeburn  10021:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10022:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10023:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10024:         $uhome=&homeserver($uname,$udom,'true');
                   10025:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10026:             return 'error: unable to generate unique course-ID';
                   10027:         }
                   10028:     }
                   10029:     return $uname;
                   10030: }
                   10031: 
1.813     albertel 10032: sub is_course {
1.1167    droeschl 10033:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10034:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10035: 
                   10036:     return unless $cdom and $cnum;
                   10037: 
                   10038:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   10039:         '.');
                   10040: 
1.1219    raeburn  10041:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 10042:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10043: }
                   10044: 
1.1015    raeburn  10045: sub store_userdata {
                   10046:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10047:     my $result;
1.1016    raeburn  10048:     if ($datakey ne '') {
1.1013    raeburn  10049:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10050:             if ($udom eq '' || $uname eq '') {
                   10051:                 $udom = $env{'user.domain'};
                   10052:                 $uname = $env{'user.name'};
                   10053:             }
                   10054:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10055:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10056:                 $result = 'error: no_host';
                   10057:             } else {
                   10058:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10059:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10060: 
                   10061:                 my $namevalue='';
                   10062:                 foreach my $key (keys(%{$storehash})) {
                   10063:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10064:                 }
                   10065:                 $namevalue=~s/\&$//;
1.1224    raeburn  10066:                 unless ($namespace eq 'courserequests') {
                   10067:                     $datakey = &escape($datakey);
                   10068:                 }
1.1105    raeburn  10069:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10070:                                   $namevalue,$uhome);
1.1013    raeburn  10071:             }
                   10072:         } else {
                   10073:             $result = 'error: data to store was not a hash reference'; 
                   10074:         }
                   10075:     } else {
                   10076:         $result= 'error: invalid requestkey'; 
                   10077:     }
                   10078:     return $result;
                   10079: }
                   10080: 
1.21      www      10081: # ---------------------------------------------------------- Assign Custom Role
                   10082: 
                   10083: sub assigncustomrole {
1.957     raeburn  10084:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10085:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10086:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10087: }
                   10088: 
                   10089: # ----------------------------------------------------------------- Revoke Role
                   10090: 
                   10091: sub revokerole {
1.957     raeburn  10092:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10093:     my $now=time;
1.965     raeburn  10094:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10095: }
                   10096: 
                   10097: # ---------------------------------------------------------- Revoke Custom Role
                   10098: 
                   10099: sub revokecustomrole {
1.957     raeburn  10100:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10101:     my $now=time;
1.357     www      10102:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10103:            $deleteflag,$selfenroll,$context);
1.17      www      10104: }
                   10105: 
1.533     banghart 10106: # ------------------------------------------------------------ Disk usage
1.535     albertel 10107: sub diskusage {
1.955     raeburn  10108:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10109:     $directorypath =~ s/\/$//;
                   10110:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10111:                        .&escape($getpropath).':'.&escape($uname).':'
                   10112:                        .&escape($udom),homeserver($uname,$udom));
                   10113:     if ($listing eq 'unknown_cmd') {
                   10114:         if ($getpropath) {
                   10115:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10116:         }
                   10117:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10118:     }
1.514     albertel 10119:     return $listing;
1.512     banghart 10120: }
                   10121: 
1.566     banghart 10122: sub is_locked {
1.1096    raeburn  10123:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10124:     my @check;
                   10125:     my $is_locked;
1.1093    raeburn  10126:     push (@check,$file_name);
1.613     albertel 10127:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10128: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10129:     my ($tmp)=keys(%locked);
                   10130:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10131:     
1.566     banghart 10132:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10133:         $is_locked = 'false';
                   10134:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10135:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10136:                $is_locked = 'true';
1.1096    raeburn  10137:                if (ref($which) eq 'ARRAY') {
                   10138:                    push(@{$which},$entry);
                   10139:                } else {
                   10140:                    last;
                   10141:                }
1.745     raeburn  10142:            }
                   10143:        }
1.566     banghart 10144:     } else {
                   10145:         $is_locked = 'false';
                   10146:     }
1.1093    raeburn  10147:     return $is_locked;
1.566     banghart 10148: }
                   10149: 
1.759     albertel 10150: sub declutter_portfile {
                   10151:     my ($file) = @_;
1.833     albertel 10152:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10153:     return $file;
                   10154: }
                   10155: 
1.559     banghart 10156: # ------------------------------------------------------------- Mark as Read Only
                   10157: 
                   10158: sub mark_as_readonly {
                   10159:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10160:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10161:     my ($tmp)=keys(%current_permissions);
                   10162:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10163:     foreach my $file (@{$files}) {
1.759     albertel 10164: 	$file = &declutter_portfile($file);
1.561     banghart 10165:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10166:     }
1.613     albertel 10167:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10168:     return;
                   10169: }
                   10170: 
1.572     banghart 10171: # ------------------------------------------------------------Save Selected Files
                   10172: 
                   10173: sub save_selected_files {
                   10174:     my ($user, $path, @files) = @_;
                   10175:     my $filename = $user."savedfiles";
1.573     banghart 10176:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10177:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10178:     foreach my $file (@files) {
1.620     albertel 10179:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10180:     }
                   10181:     foreach my $file (@other_files) {
1.574     banghart 10182:         print (OUT $file."\n");
1.572     banghart 10183:     }
1.574     banghart 10184:     close (OUT);
1.572     banghart 10185:     return 'ok';
                   10186: }
                   10187: 
1.574     banghart 10188: sub clear_selected_files {
                   10189:     my ($user) = @_;
                   10190:     my $filename = $user."savedfiles";
1.1359    raeburn  10191:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10192:     print (OUT undef);
                   10193:     close (OUT);
                   10194:     return ("ok");    
                   10195: }
                   10196: 
1.572     banghart 10197: sub files_in_path {
                   10198:     my ($user, $path) = @_;
                   10199:     my $filename = $user."savedfiles";
                   10200:     my %return_files;
1.1359    raeburn  10201:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10202:     while (my $line_in = <IN>) {
1.574     banghart 10203:         chomp ($line_in);
                   10204:         my @paths_and_file = split (m!/!, $line_in);
                   10205:         my $file_part = pop (@paths_and_file);
                   10206:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10207:         $path_part.='/';
                   10208:         my $path_and_file = $path_part.$file_part;
                   10209:         if ($path_part eq $path) {
                   10210:             $return_files{$file_part}= 'selected';
                   10211:         }
                   10212:     }
1.574     banghart 10213:     close (IN);
                   10214:     return (\%return_files);
1.572     banghart 10215: }
                   10216: 
                   10217: # called in portfolio select mode, to show files selected NOT in current directory
                   10218: sub files_not_in_path {
                   10219:     my ($user, $path) = @_;
                   10220:     my $filename = $user."savedfiles";
                   10221:     my @return_files;
                   10222:     my $path_part;
1.1359    raeburn  10223:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10224:     while (my $line = <IN>) {
1.572     banghart 10225:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10226:         my @paths_and_file = split(m|/|, $line);
                   10227:         my $file_part = pop(@paths_and_file);
                   10228:         chomp($file_part);
                   10229:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10230:         $path_part .= '/';
                   10231:         my $path_and_file = $path_part.$file_part;
                   10232:         if ($path_part ne $path) {
1.800     albertel 10233:             push(@return_files, ($path_and_file));
1.572     banghart 10234:         }
                   10235:     }
1.800     albertel 10236:     close(OUT);
1.574     banghart 10237:     return (@return_files);
1.572     banghart 10238: }
                   10239: 
1.1273    raeburn  10240: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10241:  
                   10242: sub portfiles_versioning {
                   10243:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10244:     my $portfolio_root = '/userfiles/portfolio';
                   10245:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10246:     foreach my $file (@{$portfiles}) {
                   10247:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10248:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10249:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10250:         my $getpropath = 1;
                   10251:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10252:                                              $stu_name,$getpropath);
                   10253:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10254:         my $new_answer = 
                   10255:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10256:         if ($new_answer ne 'problem getting file') {
                   10257:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10258:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10259:                               [$symb,$env{'request.course.id'},'graded']);
                   10260:         }
                   10261:     }
                   10262: }
                   10263: 
                   10264: sub get_next_version {
                   10265:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10266:     my $version;
                   10267:     if (ref($dir_list) eq 'ARRAY') {
                   10268:         foreach my $row (@{$dir_list}) {
                   10269:             my ($file) = split(/\&/,$row,2);
                   10270:             my ($file_name,$file_version,$file_ext) =
                   10271:                 &file_name_version_ext($file);
                   10272:             if (($file_name eq $answer_name) &&
                   10273:                 ($file_ext eq $answer_ext)) {
                   10274:                      # gets here if filename and extension match,
                   10275:                      # regardless of version
                   10276:                 if ($file_version ne '') {
                   10277:                     # a versioned file is found  so save it for later
                   10278:                     if ($file_version > $version) {
                   10279:                         $version = $file_version;
                   10280:                     }
                   10281:                 }
                   10282:             }
                   10283:         }
                   10284:     }
                   10285:     $version ++;
                   10286:     return($version);
                   10287: }
                   10288: 
                   10289: sub version_selected_portfile {
                   10290:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10291:     my ($answer_name,$answer_ver,$answer_ext) =
                   10292:         &file_name_version_ext($file_name);
                   10293:     my $new_answer;
                   10294:     $env{'form.copy'} =
                   10295:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10296:     if($env{'form.copy'} eq '-1') {
                   10297:         $new_answer = 'problem getting file';
                   10298:     } else {
                   10299:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10300:         my $copy_result = 
                   10301:             &finishuserfileupload($stu_name,$domain,'copy',
                   10302:                                   '/portfolio'.$directory.$new_answer);
                   10303:     }
                   10304:     undef($env{'form.copy'});
                   10305:     return ($new_answer);
                   10306: }
                   10307: 
                   10308: sub file_name_version_ext {
                   10309:     my ($file)=@_;
                   10310:     my @file_parts = split(/\./, $file);
                   10311:     my ($name,$version,$ext);
                   10312:     if (@file_parts > 1) {
                   10313:         $ext=pop(@file_parts);
                   10314:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10315:             $version=pop(@file_parts);
                   10316:         }
                   10317:         $name=join('.',@file_parts);
                   10318:     } else {
                   10319:         $name=join('.',@file_parts);
                   10320:     }
                   10321:     return($name,$version,$ext);
                   10322: }
                   10323: 
1.745     raeburn  10324: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10325: 
1.745     raeburn  10326: sub get_portfile_permissions {
                   10327:     my ($domain,$user) = @_;
1.613     albertel 10328:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10329:     my ($tmp)=keys(%current_permissions);
                   10330:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10331:     return \%current_permissions;
                   10332: }
                   10333: 
                   10334: #---------------------------------------------Get portfolio file access controls
                   10335: 
1.749     raeburn  10336: sub get_access_controls {
1.745     raeburn  10337:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10338:     my %access;
                   10339:     my $real_file = $file;
                   10340:     $file =~ s/\.meta$//;
1.745     raeburn  10341:     if (defined($file)) {
1.749     raeburn  10342:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10343:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10344:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10345:             }
                   10346:         }
1.745     raeburn  10347:     } else {
1.749     raeburn  10348:         foreach my $key (keys(%{$current_permissions})) {
                   10349:             if ($key =~ /\0accesscontrol$/) {
                   10350:                 if (defined($group)) {
                   10351:                     if ($key !~ m-^\Q$group\E/-) {
                   10352:                         next;
                   10353:                     }
                   10354:                 }
                   10355:                 my ($fullpath) = split(/\0/,$key);
                   10356:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10357:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10358:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10359:                     }
                   10360:                 }
                   10361:             }
                   10362:         }
                   10363:     }
                   10364:     return %access;
                   10365: }
                   10366: 
                   10367: sub modify_access_controls {
                   10368:     my ($file_name,$changes,$domain,$user)=@_;
                   10369:     my ($outcome,$deloutcome);
                   10370:     my %store_permissions;
                   10371:     my %new_values;
                   10372:     my %new_control;
                   10373:     my %translation;
                   10374:     my @deletions = ();
                   10375:     my $now = time;
                   10376:     if (exists($$changes{'activate'})) {
                   10377:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10378:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10379:             my $numnew = scalar(@newitems);
                   10380:             for (my $i=0; $i<$numnew; $i++) {
                   10381:                 my $newkey = $newitems[$i];
                   10382:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10383:                 if ($newkey =~ /^\d+:/) { 
                   10384:                     $newkey =~ s/^(\d+)/$newid/;
                   10385:                     $translation{$1} = $newid;
                   10386:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10387:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10388:                     $translation{$1} = $newid;
                   10389:                 }
1.749     raeburn  10390:                 $new_values{$file_name."\0".$newkey} = 
                   10391:                                           $$changes{'activate'}{$newitems[$i]};
                   10392:                 $new_control{$newkey} = $now;
                   10393:             }
                   10394:         }
                   10395:     }
                   10396:     my %todelete;
                   10397:     my %changed_items;
                   10398:     foreach my $action ('delete','update') {
                   10399:         if (exists($$changes{$action})) {
                   10400:             if (ref($$changes{$action}) eq 'HASH') {
                   10401:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10402:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10403:                     if ($action eq 'delete') { 
                   10404:                         $todelete{$itemnum} = 1;
                   10405:                     } else {
                   10406:                         $changed_items{$itemnum} = $key;
                   10407:                     }
                   10408:                 }
1.745     raeburn  10409:             }
                   10410:         }
1.749     raeburn  10411:     }
                   10412:     # get lock on access controls for file.
                   10413:     my $lockhash = {
                   10414:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10415:                                                        ':'.$env{'user.domain'},
                   10416:                    }; 
                   10417:     my $tries = 0;
                   10418:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10419:    
1.1288    damieng  10420:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10421:         $tries ++;
1.1289    damieng  10422:         sleep(0.1);
1.749     raeburn  10423:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10424:     }
                   10425:     if ($gotlock eq 'ok') {
                   10426:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10427:         my ($tmp)=keys(%curr_permissions);
                   10428:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10429:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10430:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10431:             if (ref($curr_controls) eq 'HASH') {
                   10432:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10433:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10434:                     if (defined($todelete{$itemnum})) {
                   10435:                         push(@deletions,$file_name."\0".$control_item);
                   10436:                     } else {
                   10437:                         if (defined($changed_items{$itemnum})) {
                   10438:                             $new_control{$changed_items{$itemnum}} = $now;
                   10439:                             push(@deletions,$file_name."\0".$control_item);
                   10440:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10441:                         } else {
                   10442:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10443:                         }
                   10444:                     }
1.745     raeburn  10445:                 }
                   10446:             }
                   10447:         }
1.970     raeburn  10448:         my ($group);
                   10449:         if (&is_course($domain,$user)) {
                   10450:             ($group,my $file) = split(/\//,$file_name,2);
                   10451:         }
1.749     raeburn  10452:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10453:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10454:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10455:         #  remove lock
                   10456:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10457:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10458:         my $sqlresult =
1.970     raeburn  10459:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10460:                                     $group);
1.749     raeburn  10461:     } else {
                   10462:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10463:     }
1.749     raeburn  10464:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10465: }
                   10466: 
1.827     raeburn  10467: sub make_public_indefinitely {
1.1271    raeburn  10468:     my (@requrl) = @_;
                   10469:     return &automated_portfile_access('public',\@requrl);
                   10470: }
                   10471: 
                   10472: sub automated_portfile_access {
                   10473:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10474:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10475:         return 'invalid';
                   10476:     }
1.1271    raeburn  10477:     my %urls;
                   10478:     if (ref($addsref) eq 'ARRAY') {
                   10479:         foreach my $requrl (@{$addsref}) {
                   10480:             if (&is_portfolio_url($requrl)) {
                   10481:                 unless (exists($urls{$requrl})) {
                   10482:                     $urls{$requrl} = 'add';
                   10483:                 }
                   10484:             }
                   10485:         }
                   10486:     }
                   10487:     if (ref($delsref) eq 'ARRAY') {
                   10488:         foreach my $requrl (@{$delsref}) { 
                   10489:             if (&is_portfolio_url($requrl)) {
                   10490:                 unless (exists($urls{$requrl})) {
                   10491:                     $urls{$requrl} = 'delete'; 
                   10492:                 }
                   10493:             }
                   10494:         }
                   10495:     }
                   10496:     unless (keys(%urls)) {
                   10497:         return 'invalid';
                   10498:     }
                   10499:     my $ip;
                   10500:     if ($accesstype eq 'ip') {
                   10501:         if (ref($info) eq 'HASH') {
                   10502:             if ($info->{'ip'} ne '') {
                   10503:                 $ip = $info->{'ip'};
                   10504:             }
                   10505:         }
                   10506:         if ($ip eq '') {
                   10507:             return 'invalid';
                   10508:         }
                   10509:     }
                   10510:     my $errors;
1.827     raeburn  10511:     my $now = time;
1.1271    raeburn  10512:     my %current_perms;
                   10513:     foreach my $requrl (sort(keys(%urls))) {
                   10514:         my $action;
                   10515:         if ($urls{$requrl} eq 'add') {
                   10516:             $action = 'activate';
                   10517:         } else {
                   10518:             $action = 'none';
                   10519:         }
                   10520:         my $aclnum = 0;
1.827     raeburn  10521:         my (undef,$udom,$unum,$file_name,$group) =
                   10522:             &parse_portfolio_url($requrl);
1.1271    raeburn  10523:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10524:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10525:         }
                   10526:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10527:                                                    $group,$file_name);
                   10528:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10529:             my ($num,$scope,$end,$start) = 
                   10530:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10531:             if ($scope eq $accesstype) {
                   10532:                 if (($start <= $now) && ($end == 0)) {
                   10533:                     if ($accesstype eq 'ip') {
                   10534:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10535:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10536:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10537:                                     if ($urls{$requrl} eq 'add') {
                   10538:                                         $action = 'none';
                   10539:                                         last;
                   10540:                                     } else {
                   10541:                                         $action = 'delete';
                   10542:                                         $aclnum = $num;
                   10543:                                         last;
                   10544:                                     }
                   10545:                                 }
                   10546:                             }
                   10547:                         }
                   10548:                     } elsif ($accesstype eq 'public') {
                   10549:                         if ($urls{$requrl} eq 'add') {
                   10550:                             $action = 'none';
                   10551:                             last;
                   10552:                         } else {
                   10553:                             $action = 'delete';
                   10554:                             $aclnum = $num;
                   10555:                             last;
                   10556:                         }
                   10557:                     }
                   10558:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10559:                     $action = 'update';
                   10560:                     $aclnum = $num;
1.1271    raeburn  10561:                     last;
1.827     raeburn  10562:                 }
                   10563:             }
                   10564:         }
                   10565:         if ($action eq 'none') {
1.1271    raeburn  10566:             next;
1.827     raeburn  10567:         } else {
                   10568:             my %changes;
                   10569:             my $newend = 0;
                   10570:             my $newstart = $now;
1.1271    raeburn  10571:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10572:             $changes{$action}{$newkey} = {
1.1271    raeburn  10573:                 type => $accesstype,
1.827     raeburn  10574:                 time => {
                   10575:                     start => $newstart,
                   10576:                     end   => $newend,
                   10577:                 },
                   10578:             };
1.1271    raeburn  10579:             if ($accesstype eq 'ip') {
                   10580:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10581:             }
1.827     raeburn  10582:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10583:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10584:             unless ($outcome eq 'ok') {
                   10585:                 $errors .= $outcome.' ';
                   10586:             }
1.827     raeburn  10587:         }
1.1271    raeburn  10588:     }
                   10589:     if ($errors) {
                   10590:         $errors =~ s/\s$//;
                   10591:         return $errors;
1.827     raeburn  10592:     } else {
1.1271    raeburn  10593:         return 'ok';
1.827     raeburn  10594:     }
                   10595: }
                   10596: 
1.745     raeburn  10597: #------------------------------------------------------Get Marked as Read Only
                   10598: 
                   10599: sub get_marked_as_readonly {
                   10600:     my ($domain,$user,$what,$group) = @_;
                   10601:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10602:     my @readonly_files;
1.629     banghart 10603:     my $cmp1=$what;
                   10604:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10605:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10606:         if (defined($group)) {
                   10607:             if ($file_name !~ m-^\Q$group\E/-) {
                   10608:                 next;
                   10609:             }
                   10610:         }
1.561     banghart 10611:         if (ref($value) eq "ARRAY"){
                   10612:             foreach my $stored_what (@{$value}) {
1.629     banghart 10613:                 my $cmp2=$stored_what;
1.759     albertel 10614:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10615:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10616:                 }
1.629     banghart 10617:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10618:                     push(@readonly_files, $file_name);
1.745     raeburn  10619:                     last;
1.563     banghart 10620:                 } elsif (!defined($what)) {
                   10621:                     push(@readonly_files, $file_name);
1.745     raeburn  10622:                     last;
1.561     banghart 10623:                 }
                   10624:             }
1.745     raeburn  10625:         }
1.561     banghart 10626:     }
                   10627:     return @readonly_files;
                   10628: }
1.577     banghart 10629: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10630: 
1.577     banghart 10631: sub get_marked_as_readonly_hash {
1.745     raeburn  10632:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10633:     my %readonly_files;
1.745     raeburn  10634:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10635:         if (defined($group)) {
                   10636:             if ($file_name !~ m-^\Q$group\E/-) {
                   10637:                 next;
                   10638:             }
                   10639:         }
1.577     banghart 10640:         if (ref($value) eq "ARRAY"){
                   10641:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10642:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10643:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10644:                         if ($lock_descriptor eq 'graded') {
                   10645:                             $readonly_files{$file_name} = 'graded';
                   10646:                         } elsif ($lock_descriptor eq 'handback') {
                   10647:                             $readonly_files{$file_name} = 'handback';
                   10648:                         } else {
                   10649:                             if (!exists($readonly_files{$file_name})) {
                   10650:                                 $readonly_files{$file_name} = 'locked';
                   10651:                             }
                   10652:                         }
1.745     raeburn  10653:                     }
1.750     banghart 10654:                 } 
1.577     banghart 10655:             }
                   10656:         } 
                   10657:     }
                   10658:     return %readonly_files;
                   10659: }
1.559     banghart 10660: # ------------------------------------------------------------ Unmark as Read Only
                   10661: 
                   10662: sub unmark_as_readonly {
1.629     banghart 10663:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10664:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10665:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10666:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10667:     my $symb_crs = $what;
                   10668:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10669:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10670:     my ($tmp)=keys(%current_permissions);
                   10671:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10672:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10673:     foreach my $file (@readonly_files) {
1.759     albertel 10674: 	my $clean_file = &declutter_portfile($file);
                   10675: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10676: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10677:         my @new_locks;
                   10678:         my @del_keys;
                   10679:         if (ref($current_locks) eq "ARRAY"){
                   10680:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10681:                 my $compare=$locker;
1.749     raeburn  10682:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10683:                     $compare=join('',@{$locker});
1.746     raeburn  10684:                     if ($compare ne $symb_crs) {
                   10685:                         push(@new_locks, $locker);
                   10686:                     }
1.563     banghart 10687:                 }
                   10688:             }
1.650     albertel 10689:             if (scalar(@new_locks) > 0) {
1.563     banghart 10690:                 $current_permissions{$file} = \@new_locks;
                   10691:             } else {
                   10692:                 push(@del_keys, $file);
1.613     albertel 10693:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10694:                 delete($current_permissions{$file});
1.563     banghart 10695:             }
                   10696:         }
1.561     banghart 10697:     }
1.613     albertel 10698:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10699:     return;
                   10700: }
1.512     banghart 10701: 
1.17      www      10702: # ------------------------------------------------------------ Directory lister
                   10703: 
                   10704: sub dirlist {
1.955     raeburn  10705:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10706:     $uri=~s/^\///;
                   10707:     $uri=~s/\/$//;
1.253     stredwic 10708:     my ($udom, $uname);
1.955     raeburn  10709:     if ($getuserdir) {
1.253     stredwic 10710:         $udom = $userdomain;
                   10711:         $uname = $username;
1.955     raeburn  10712:     } else {
                   10713:         (undef,$udom,$uname)=split(/\//,$uri);
                   10714:         if(defined($userdomain)) {
                   10715:             $udom = $userdomain;
                   10716:         }
                   10717:         if(defined($username)) {
                   10718:             $uname = $username;
                   10719:         }
1.253     stredwic 10720:     }
1.955     raeburn  10721:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10722: 
1.955     raeburn  10723:     $dirRoot = $perlvar{'lonDocRoot'};
                   10724:     if (defined($getpropath)) {
                   10725:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10726:         $dirRoot =~ s/\/$//;
1.955     raeburn  10727:     } elsif (defined($getuserdir)) {
                   10728:         my $subdir=$uname.'__';
                   10729:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10730:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10731:                    ."/$udom/$subdir/$uname";
                   10732:     } elsif (defined($alternateRoot)) {
                   10733:         $dirRoot = $alternateRoot;
1.751     banghart 10734:     }
1.253     stredwic 10735: 
                   10736:     if($udom) {
                   10737:         if($uname) {
1.1135    raeburn  10738:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10739:             if ($uhome eq 'no_host') {
                   10740:                 return ([],'no_host');
                   10741:             }
1.955     raeburn  10742:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10743:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10744:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10745:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10746:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10747:             } else {
                   10748:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10749:             }
1.605     matthew  10750:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10751:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10752:                 @listing_results = split(/:/,$listing);
                   10753:             } else {
                   10754:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10755:             }
1.1135    raeburn  10756:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10757:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10758:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10759:                 return ([],$listing);
                   10760:             } else {
                   10761:                 return (\@listing_results);
1.1135    raeburn  10762:             }
1.955     raeburn  10763:         } elsif(!$alternateRoot) {
1.1136    raeburn  10764:             my (%allusers,%listerror);
1.841     albertel 10765: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10766:  	    foreach my $tryserver (keys(%servers)) {
                   10767:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10768:                                   &escape($udom),$tryserver);
                   10769:                 if ($listing eq 'unknown_cmd') {
                   10770: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10771: 				      $udom, $tryserver);
                   10772:                 } else {
                   10773:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10774:                 }
1.841     albertel 10775: 		if ($listing eq 'unknown_cmd') {
                   10776: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10777: 				      $udom, $tryserver);
                   10778: 		    @listing_results = split(/:/,$listing);
                   10779: 		} else {
                   10780: 		    @listing_results =
                   10781: 			map { &unescape($_); } split(/:/,$listing);
                   10782: 		}
1.1136    raeburn  10783:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10784:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10785:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10786:                     $listerror{$tryserver} = $listing;
                   10787:                 } else {
1.841     albertel 10788: 		    foreach my $line (@listing_results) {
                   10789: 			my ($entry) = split(/&/,$line,2);
                   10790: 			$allusers{$entry} = 1;
                   10791: 		    }
                   10792: 		}
1.253     stredwic 10793:             }
1.1136    raeburn  10794:             my @alluserslist=();
1.800     albertel 10795:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10796:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10797:             }
1.1318    droeschl 10798: 
                   10799:             if (!%listerror) {
                   10800:                 # no errors
                   10801:                 return (\@alluserslist);
                   10802:             } elsif (scalar(keys(%servers)) == 1) {
                   10803:                 # one library server, one error 
                   10804:                 my ($key) = keys(%listerror);
                   10805:                 return (\@alluserslist, $listerror{$key});
                   10806:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10807:                 # con_lost indicates that we might miss data from at least one
                   10808:                 # library server
                   10809:                 return (\@alluserslist, 'con_lost');
                   10810:             } else {
                   10811:                 # multiple library servers and no con_lost -> data should be
                   10812:                 # complete. 
                   10813:                 return (\@alluserslist);
                   10814:             }
                   10815: 
1.253     stredwic 10816:         } else {
1.1136    raeburn  10817:             return ([],'missing username');
1.253     stredwic 10818:         }
1.955     raeburn  10819:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10820:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10821:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10822:         return (\@all_domains);
1.955     raeburn  10823:     } else {
1.1136    raeburn  10824:         return ([],'missing domain');
1.275     stredwic 10825:     }
                   10826: }
                   10827: 
                   10828: # --------------------------------------------- GetFileTimestamp
                   10829: # This function utilizes dirlist and returns the date stamp for
                   10830: # when it was last modified.  It will also return an error of -1
                   10831: # if an error occurs
                   10832: 
                   10833: sub GetFileTimestamp {
1.955     raeburn  10834:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10835:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10836:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10837:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10838:                                     undef,$getuserdir);
                   10839:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10840:         return -1;
                   10841:     }
                   10842:     if (ref($fileref) eq 'ARRAY') {
                   10843:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10844:         # @stats contains first the filename, then the stat output
                   10845:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10846:     } else {
                   10847:         return -1;
1.253     stredwic 10848:     }
1.26      www      10849: }
                   10850: 
1.712     albertel 10851: sub stat_file {
                   10852:     my ($uri) = @_;
1.787     albertel 10853:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10854: 
1.955     raeburn  10855:     my ($udom,$uname,$file);
1.712     albertel 10856:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10857: 	($udom,$uname,$file) =
1.811     albertel 10858: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10859: 	$file = 'userfiles/'.$file;
                   10860:     }
                   10861:     if ($uri =~ m-^/res/-) {
                   10862: 	($udom,$uname) = 
1.807     albertel 10863: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10864: 	$file = $uri;
                   10865:     }
                   10866: 
                   10867:     if (!$udom || !$uname || !$file) {
                   10868: 	# unable to handle the uri
                   10869: 	return ();
                   10870:     }
1.956     raeburn  10871:     my $getpropath;
                   10872:     if ($file =~ /^userfiles\//) {
                   10873:         $getpropath = 1;
                   10874:     }
1.1136    raeburn  10875:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10876:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10877:         return ();
                   10878:     } else {
                   10879:         if (ref($listref) eq 'ARRAY') {
                   10880:             my @stats = split('&',$listref->[0]);
                   10881: 	    shift(@stats); #filename is first
                   10882: 	    return @stats;
                   10883:         }
1.712     albertel 10884:     }
                   10885:     return ();
                   10886: }
                   10887: 
1.1313    raeburn  10888: # --------------------------------------------------------- recursedirs
                   10889: # Recursive function to traverse either a specific user's Authoring Space
                   10890: # or corresponding Published Resource Space, and populate the hash ref:
                   10891: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10892: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10893: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10894: # files in Authoring Space.
                   10895: #
                   10896: # Inputs:
                   10897: #
                   10898: # $is_home - true if current server is home server for user's space
                   10899: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10900: # $docroot - Document root (i.e., /home/httpd/html
                   10901: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10902: # $relpath - Current path (relative to top level).
                   10903: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10904: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10905: #
                   10906: # Returns: nothing
                   10907: #
                   10908: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10909: #
                   10910: # Currently used by interface/londocs.pm to create linked select boxes for
                   10911: # directory and filename to import a Course "Author" resource into a course, and
                   10912: # also to create linked select boxes for Authoring Space and Directory to choose
                   10913: # save location for creation of a new "standard" problem from the Course Editor.
                   10914: #
                   10915: 
                   10916: sub recursedirs {
                   10917:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10918:     return unless (ref($dirhashref) eq 'HASH');
                   10919:     my $currpath = $docroot.$toppath;
                   10920:     if ($relpath) {
                   10921:         $currpath .= "/$relpath";
                   10922:     }
                   10923:     my $savefile;
                   10924:     if (ref($filehashref)) {
                   10925:         $savefile = 1;
                   10926:     }
                   10927:     if ($is_home) {
                   10928:         if (opendir(my $dirh,$currpath)) {
                   10929:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10930:                 next if ($item eq '');
                   10931:                 if (-d "$currpath/$item") {
                   10932:                     my $newpath;
                   10933:                     if ($relpath) {
                   10934:                         $newpath = "$relpath/$item";
                   10935:                     } else {
                   10936:                         $newpath = $item;
                   10937:                     }
                   10938:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10939:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10940:                 } elsif ($savefile) {
                   10941:                     if ($context eq 'priv') {
                   10942:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10943:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10944:                         }
                   10945:                     } else {
                   10946:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10947:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10948:                         }
                   10949:                     }
                   10950:                 }
                   10951:             }
                   10952:             closedir($dirh);
                   10953:         }
                   10954:     } else {
                   10955:         my ($dirlistref,$listerror) =
                   10956:             &dirlist($toppath.$relpath);
                   10957:         my @dir_lines;
                   10958:         my $dirptr=16384;
                   10959:         if (ref($dirlistref) eq 'ARRAY') {
                   10960:             foreach my $dir_line (sort
                   10961:                               {
                   10962:                                   my ($afile)=split('&',$a,2);
                   10963:                                   my ($bfile)=split('&',$b,2);
                   10964:                                   return (lc($afile) cmp lc($bfile));
                   10965:                               } (@{$dirlistref})) {
                   10966:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10967:                     split(/\&/,$dir_line,16);
                   10968:                 $item =~ s/\s+$//;
                   10969:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10970:                 if ($dirptr&$testdir) {
                   10971:                     my $newpath;
                   10972:                     if ($relpath) {
                   10973:                         $newpath = "$relpath/$item";
                   10974:                     } else {
                   10975:                         $relpath = '/';
                   10976:                         $newpath = $item;
                   10977:                     }
                   10978:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10979:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10980:                 } elsif ($savefile) {
                   10981:                     if ($context eq 'priv') {
                   10982:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10983:                             $filehashref->{$relpath}{$item} = 1;
                   10984:                         }
                   10985:                     } else {
                   10986:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10987:                             $filehashref->{$relpath}{$item} = 1;
                   10988:                         }
                   10989:                     }
                   10990:                 }
                   10991:             }
                   10992:         }
                   10993:     }
                   10994:     return;
                   10995: }
                   10996: 
1.26      www      10997: # -------------------------------------------------------- Value of a Condition
                   10998: 
1.713     albertel 10999: # gets the value of a specific preevaluated condition
                   11000: #    stored in the string  $env{user.state.<cid>}
                   11001: # or looks up a condition reference in the bighash and if if hasn't
                   11002: # already been evaluated recurses into docondval to get the value of
                   11003: # the condition, then memoizing it to 
                   11004: #   $env{user.state.<cid>.<condition>}
1.40      www      11005: sub directcondval {
                   11006:     my $number=shift;
1.620     albertel 11007:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11008: 	&Apache::lonuserstate::evalstate();
                   11009:     }
1.713     albertel 11010:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11011: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11012:     } elsif ($number =~ /^_/) {
                   11013: 	my $sub_condition;
                   11014: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11015: 		&GDBM_READER(),0640)) {
                   11016: 	    $sub_condition=$bighash{'conditions'.$number};
                   11017: 	    untie(%bighash);
                   11018: 	}
                   11019: 	my $value = &docondval($sub_condition);
1.949     raeburn  11020: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11021: 	return $value;
                   11022:     }
1.620     albertel 11023:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11024:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11025:     } else {
                   11026:        return 2;
                   11027:     }
                   11028: }
                   11029: 
1.713     albertel 11030: # get the collection of conditions for this resource
1.26      www      11031: sub condval {
                   11032:     my $condidx=shift;
1.54      www      11033:     my $allpathcond='';
1.713     albertel 11034:     foreach my $cond (split(/\|/,$condidx)) {
                   11035: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11036: 	    $allpathcond.=
                   11037: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11038: 	}
1.191     harris41 11039:     }
1.54      www      11040:     $allpathcond=~s/\|$//;
1.713     albertel 11041:     return &docondval($allpathcond);
                   11042: }
                   11043: 
                   11044: #evaluates an expression of conditions
                   11045: sub docondval {
                   11046:     my ($allpathcond) = @_;
                   11047:     my $result=0;
                   11048:     if ($env{'request.course.id'}
                   11049: 	&& defined($allpathcond)) {
                   11050: 	my $operand='|';
                   11051: 	my @stack;
                   11052: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11053: 	    if ($chunk eq '(') {
                   11054: 		push @stack,($operand,$result);
                   11055: 	    } elsif ($chunk eq ')') {
                   11056: 		my $before=pop @stack;
                   11057: 		if (pop @stack eq '&') {
                   11058: 		    $result=$result>$before?$before:$result;
                   11059: 		} else {
                   11060: 		    $result=$result>$before?$result:$before;
                   11061: 		}
                   11062: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11063: 		$operand=$chunk;
                   11064: 	    } else {
                   11065: 		my $new=directcondval($chunk);
                   11066: 		if ($operand eq '&') {
                   11067: 		    $result=$result>$new?$new:$result;
                   11068: 		} else {
                   11069: 		    $result=$result>$new?$result:$new;
                   11070: 		}
                   11071: 	    }
                   11072: 	}
1.26      www      11073:     }
                   11074:     return $result;
1.421     albertel 11075: }
                   11076: 
                   11077: # ---------------------------------------------------- Devalidate courseresdata
                   11078: 
                   11079: sub devalidatecourseresdata {
                   11080:     my ($coursenum,$coursedomain)=@_;
                   11081:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11082:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11083: }
                   11084: 
1.763     www      11085: 
1.200     www      11086: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11087: #
                   11088: #  Parameters:
                   11089: #      $coursenum    - Number of the course.
                   11090: #      $coursedomain - Domain at which the course was created.
                   11091: #  Returns:
                   11092: #     A hash of the course parameters along (I think) with timestamps
                   11093: #     and version info.
1.877     foxr     11094: 
1.624     albertel 11095: sub get_courseresdata {
                   11096:     my ($coursenum,$coursedomain)=@_;
1.200     www      11097:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11098:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11099:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11100:     my %dumpreply;
1.417     albertel 11101:     unless (defined($cached)) {
1.624     albertel 11102: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11103: 	$result=\%dumpreply;
1.251     albertel 11104: 	my ($tmp) = keys(%dumpreply);
                   11105: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11106: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11107: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11108: 	    return $tmp;
1.416     albertel 11109: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11110: 	    $result=undef;
1.599     albertel 11111: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11112: 	}
                   11113:     }
1.624     albertel 11114:     return $result;
                   11115: }
                   11116: 
1.633     albertel 11117: sub devalidateuserresdata {
                   11118:     my ($uname,$udom)=@_;
                   11119:     my $hashid="$udom:$uname";
                   11120:     &devalidate_cache_new('userres',$hashid);
                   11121: }
                   11122: 
1.624     albertel 11123: sub get_userresdata {
                   11124:     my ($uname,$udom)=@_;
                   11125:     #most student don\'t have any data set, check if there is some data
                   11126:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11127: 
                   11128:     my $hashid="$udom:$uname";
                   11129:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11130:     if (!defined($cached)) {
                   11131: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11132: 	$result=\%resourcedata;
                   11133: 	&do_cache_new('userres',$hashid,$result,600);
                   11134:     }
                   11135:     my ($tmp)=keys(%$result);
                   11136:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11137: 	return $result;
                   11138:     }
                   11139:     #error 2 occurs when the .db doesn't exist
                   11140:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11141:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11142: 	    &logthis("<font color=\"blue\">WARNING:".
                   11143: 		     " Trying to get resource data for ".
                   11144: 		     $uname." at ".$udom.": ".
                   11145: 		     $tmp."</font>");
                   11146:         }
1.624     albertel 11147:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11148: 	#&EXT_cache_set($udom,$uname);
                   11149: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11150: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11151:     }
                   11152:     return $tmp;
                   11153: }
1.879     foxr     11154: #----------------------------------------------- resdata - return resource data
                   11155: #  Purpose:
                   11156: #    Return resource data for either users or for a course.
                   11157: #  Parameters:
                   11158: #     $name      - Course/user name.
                   11159: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11160: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11161: #     $mapp      - decluttered URL of enclosing map  
                   11162: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11163: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11164: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11165: #     $courseid  - CourseID (first part of param identifier).
                   11166: #     $modifier  - Middle part of param identifier.
                   11167: #     $what      - Last part of param identifier.
1.879     foxr     11168: #     @which     - Array of names of resources desired.
                   11169: #  Returns:
                   11170: #     The value of the first reasource in @which that is found in the
                   11171: #     resource hash.
                   11172: #  Exceptional Conditions:
                   11173: #     If the $type passed in is not valid (not the string 'course' or 
                   11174: #     'user', an undefined  reference is returned.
                   11175: #     If none of the resources are found, an undef is returned
1.624     albertel 11176: sub resdata {
1.1301    raeburn  11177:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11178:         $modifier,$what,@which)=@_;
1.624     albertel 11179:     my $result;
                   11180:     if ($type eq 'course') {
                   11181: 	$result=&get_courseresdata($name,$domain);
                   11182:     } elsif ($type eq 'user') {
                   11183: 	$result=&get_userresdata($name,$domain);
                   11184:     }
                   11185:     if (!ref($result)) { return $result; }    
1.251     albertel 11186:     foreach my $item (@which) {
1.1301    raeburn  11187:         if ($item->[1] eq 'course') {
                   11188:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11189:                 unless ($$recursed) {
1.1302    raeburn  11190:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11191:                     $$recursed = 1;
                   11192:                 }
                   11193:                 foreach my $item (@${recurseup}) {
                   11194:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11195:                     last if (defined($result->{$norecursechk}));
                   11196:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11197:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11198:                 }
                   11199:             }
                   11200:         }
                   11201:         if (defined($result->{$item->[0]})) {
1.927     albertel 11202: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11203: 	}
1.250     albertel 11204:     }
1.291     albertel 11205:     return undef;
1.200     www      11206: }
                   11207: 
1.1360    raeburn  11208: sub get_domain_lti {
                   11209:     my ($cdom,$context) = @_;
                   11210:     my ($name,%lti);
                   11211:     if ($context eq 'consumer') {
                   11212:         $name = 'ltitools';
                   11213:     } elsif ($context eq 'provider') {
                   11214:         $name = 'lti';
                   11215:     } else {
                   11216:         return %lti;
                   11217:     }
                   11218:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11219:     if (defined($cached)) {
                   11220:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11221:             %lti = %{$result};
1.1298    raeburn  11222:         }
                   11223:     } else {
1.1360    raeburn  11224:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11225:         if (ref($domconfig{$name}) eq 'HASH') {
                   11226:             %lti = %{$domconfig{$name}};
                   11227:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11228:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11229:                 foreach my $id (keys(%lti)) {
                   11230:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11231:                         foreach my $item ('key','secret') {
1.1360    raeburn  11232:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11233:                         }
                   11234:                     }
                   11235:                 }
                   11236:             }
1.1298    raeburn  11237:         }
                   11238:         my $cachetime = 24*60*60;
1.1360    raeburn  11239:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11240:     }
1.1360    raeburn  11241:     return %lti;
1.1298    raeburn  11242: }
                   11243: 
1.1236    raeburn  11244: sub get_numsuppfiles {
                   11245:     my ($cnum,$cdom,$ignorecache)=@_;
                   11246:     my $hashid=$cnum.':'.$cdom;
                   11247:     my ($suppcount,$cached);
                   11248:     unless ($ignorecache) {
                   11249:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11250:     }
                   11251:     unless (defined($cached)) {
                   11252:         my $chome=&homeserver($cnum,$cdom);
                   11253:         unless ($chome eq 'no_host') {
1.1366    raeburn  11254:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11255:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11256:             ($suppcount,$supptools,$errors) =
                   11257:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11258:                                                          $supptools,$errors);
1.1236    raeburn  11259:         }
                   11260:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11261:     }
                   11262:     return $suppcount;
                   11263: }
                   11264: 
1.379     matthew  11265: #
                   11266: # EXT resource caching routines
                   11267: #
                   11268: 
1.1302    raeburn  11269: {
                   11270: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11271: #
                   11272: # The course for which we cache
                   11273: my $cachedmapkey='';
                   11274: # The cached recursive maps for this course
                   11275: my %cachedmaps=();
                   11276: # When this was last done
                   11277: my $cachedmaptime='';
                   11278: 
1.379     matthew  11279: sub clear_EXT_cache_status {
1.383     albertel 11280:     &delenv('cache.EXT.');
1.379     matthew  11281: }
                   11282: 
                   11283: sub EXT_cache_status {
                   11284:     my ($target_domain,$target_user) = @_;
1.383     albertel 11285:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11286:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11287:         # We know already the user has no data
                   11288:         return 1;
                   11289:     } else {
                   11290:         return 0;
                   11291:     }
                   11292: }
                   11293: 
                   11294: sub EXT_cache_set {
                   11295:     my ($target_domain,$target_user) = @_;
1.383     albertel 11296:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11297:     #&appenv({$cachename => time});
1.379     matthew  11298: }
                   11299: 
1.28      www      11300: # --------------------------------------------------------- Value of a Variable
1.58      www      11301: sub EXT {
1.715     albertel 11302: 
1.1228    raeburn  11303:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11304:     unless ($varname) { return ''; }
1.218     albertel 11305:     #get real user name/domain, courseid and symb
                   11306:     my $courseid;
1.359     albertel 11307:     my $publicuser;
1.427     www      11308:     if ($symbparm) {
                   11309: 	$symbparm=&get_symb_from_alias($symbparm);
                   11310:     }
1.218     albertel 11311:     if (!($uname && $udom)) {
1.790     albertel 11312:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11313:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11314:     } else {
1.620     albertel 11315: 	$courseid=$env{'request.course.id'};
1.218     albertel 11316:     }
1.48      www      11317:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11318:     my $rest;
1.320     albertel 11319:     if (defined($therest[0])) {
1.48      www      11320:        $rest=join('.',@therest);
                   11321:     } else {
                   11322:        $rest='';
                   11323:     }
1.320     albertel 11324: 
1.57      www      11325:     my $qualifierrest=$qualifier;
                   11326:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11327:     my $spacequalifierrest=$space;
                   11328:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11329:     if ($realm eq 'user') {
1.48      www      11330: # --------------------------------------------------------------- user.resource
                   11331: 	if ($space eq 'resource') {
1.651     albertel 11332: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11333: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11334: 		 &&
1.744     albertel 11335: 		 ($symbparm eq &symbread()) ) {	
                   11336: 		# if we are in the middle of processing the resource the
                   11337: 		# get the value we are planning on committing
                   11338:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11339:                     return $Apache::lonhomework::results{$qualifierrest};
                   11340:                 } else {
                   11341:                     return $Apache::lonhomework::history{$qualifierrest};
                   11342:                 }
1.335     albertel 11343: 	    } else {
1.359     albertel 11344: 		my %restored;
1.620     albertel 11345: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11346: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11347: 		} else {
                   11348: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11349: 		}
1.335     albertel 11350: 		return $restored{$qualifierrest};
                   11351: 	    }
1.48      www      11352: # ----------------------------------------------------------------- user.access
                   11353:         } elsif ($space eq 'access') {
1.218     albertel 11354: 	    # FIXME - not supporting calls for a specific user
1.48      www      11355:             return &allowed($qualifier,$rest);
                   11356: # ------------------------------------------ user.preferences, user.environment
                   11357:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11358: 	    if (($uname eq $env{'user.name'}) &&
                   11359: 		($udom eq $env{'user.domain'})) {
                   11360: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11361: 	    } else {
1.359     albertel 11362: 		my %returnhash;
                   11363: 		if (!$publicuser) {
                   11364: 		    %returnhash=&userenvironment($udom,$uname,
                   11365: 						 $qualifierrest);
                   11366: 		}
1.218     albertel 11367: 		return $returnhash{$qualifierrest};
                   11368: 	    }
1.48      www      11369: # ----------------------------------------------------------------- user.course
                   11370:         } elsif ($space eq 'course') {
1.218     albertel 11371: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11372:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11373: # ------------------------------------------------------------------- user.role
                   11374:         } elsif ($space eq 'role') {
1.218     albertel 11375: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11376:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11377:             if ($qualifier eq 'value') {
                   11378: 		return $role;
                   11379:             } elsif ($qualifier eq 'extent') {
                   11380:                 return $where;
                   11381:             }
                   11382: # ----------------------------------------------------------------- user.domain
                   11383:         } elsif ($space eq 'domain') {
1.218     albertel 11384:             return $udom;
1.48      www      11385: # ------------------------------------------------------------------- user.name
                   11386:         } elsif ($space eq 'name') {
1.218     albertel 11387:             return $uname;
1.48      www      11388: # ---------------------------------------------------- Any other user namespace
1.29      www      11389:         } else {
1.359     albertel 11390: 	    my %reply;
                   11391: 	    if (!$publicuser) {
                   11392: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11393: 	    }
                   11394: 	    return $reply{$qualifierrest};
1.48      www      11395:         }
1.236     www      11396:     } elsif ($realm eq 'query') {
                   11397: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11398:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11399: 						[$spacequalifierrest]);
1.620     albertel 11400: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11401:    } elsif ($realm eq 'request') {
1.48      www      11402: # ------------------------------------------------------------- request.browser
                   11403:         if ($space eq 'browser') {
1.1145    bisitz   11404:             return $env{'browser.'.$qualifier};
1.57      www      11405: # ------------------------------------------------------------ request.filename
                   11406:         } else {
1.620     albertel 11407:             return $env{'request.'.$spacequalifierrest};
1.29      www      11408:         }
1.28      www      11409:     } elsif ($realm eq 'course') {
1.48      www      11410: # ---------------------------------------------------------- course.description
1.620     albertel 11411:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11412:     } elsif ($realm eq 'resource') {
1.165     www      11413: 
1.620     albertel 11414: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11415: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11416: 	}
1.693     albertel 11417: 
1.1232    raeburn  11418:         if ($qualifier eq '') {
                   11419: 	    if ($space eq 'title') {
                   11420: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11421: 	        return &gettitle($symbparm);
                   11422: 	    }
1.693     albertel 11423: 	
1.1232    raeburn  11424: 	    if ($space eq 'map') {
                   11425: 	        my ($map) = &decode_symb($symbparm);
                   11426: 	        return &symbread($map);
                   11427: 	    }
                   11428:             if ($space eq 'maptitle') {
                   11429:                 my ($map) = &decode_symb($symbparm);
                   11430:                 return &gettitle($map);
                   11431:             }
                   11432: 	    if ($space eq 'filename') {
                   11433: 	        if ($symbparm) {
                   11434: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11435: 	        }
                   11436: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11437: 	    }
1.1232    raeburn  11438: 
1.1233    raeburn  11439:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11440:                 if ($space eq 'visibleparts') {
                   11441:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11442:                     my $item;
                   11443:                     if (ref($navmap)) {
                   11444:                         my $res = $navmap->getBySymb($symbparm);
                   11445:                         my $parts = $res->parts();
                   11446:                         if (ref($parts) eq 'ARRAY') {
                   11447:                             $item = join(',',@{$parts});
                   11448:                         }
                   11449:                         undef($navmap);
1.1232    raeburn  11450:                     }
1.1233    raeburn  11451:                     return $item;
1.1232    raeburn  11452:                 }
                   11453:             }
                   11454:         }
1.693     albertel 11455: 
1.1301    raeburn  11456: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11457: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11458:         if (($courseid eq '') && ($cid)) {
                   11459:             $courseid = $cid;
                   11460:         }
                   11461: 	if (($symbparm && $courseid) && 
                   11462: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11463: 
1.218     albertel 11464: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11465: 
1.60      www      11466: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11467: 	    my $symbp=$symbparm;
1.1301    raeburn  11468: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11469: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11470:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11471: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11472: 	    if (($env{'user.name'} eq $uname) &&
                   11473: 		($env{'user.domain'} eq $udom)) {
                   11474: 		$section=$env{'request.course.sec'};
1.733     raeburn  11475:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11476:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11477: 	    } else {
1.539     albertel 11478: 		if (! defined($usection)) {
1.551     albertel 11479: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11480: 		} else {
                   11481: 		    $section = $usection;
                   11482: 		}
1.733     raeburn  11483:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11484: 	    }
                   11485: 
                   11486: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11487: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11488:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11489: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11490: 
1.593     albertel 11491: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11492: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11493:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11494: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11495: 
1.60      www      11496: # ----------------------------------------------------------- first, check user
1.624     albertel 11497: 
1.1301    raeburn  11498: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11499:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11500: 				       ([$courselevelr,'resource'],
                   11501: 					[$courselevelm,'map'     ],
1.1301    raeburn  11502:                                         [$courseleveli,'map'     ],
1.927     albertel 11503: 					[$courselevel, 'course'  ]));
1.931     albertel 11504: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11505: 
1.594     albertel 11506: # ------------------------------------------------ second, check some of course
1.684     raeburn  11507:             my $coursereply;
1.691     raeburn  11508:             if (@groups > 0) {
                   11509:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11510:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11511:                                        $mapp,\$recursed,\@recurseup);
                   11512:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11513:             }
1.96      www      11514: 
1.684     raeburn  11515: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11516: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11517: 				  'course',$mapp,\$recursed,\@recurseup,
                   11518:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11519: 				  ([$seclevelr,   'resource'],
                   11520: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11521:                                    [$secleveli,   'map'     ],
1.927     albertel 11522: 				   [$seclevel,    'course'  ],
                   11523: 				   [$courselevelr,'resource']));
                   11524: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11525: 
1.60      www      11526: # ------------------------------------------------------ third, check map parms
1.218     albertel 11527: 	    my %parmhash=();
                   11528: 	    my $thisparm='';
                   11529: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11530: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11531: 		    &GDBM_READER(),0640)) {
1.218     albertel 11532: 		$thisparm=$parmhash{$symbparm};
                   11533: 		untie(%parmhash);
                   11534: 	    }
1.927     albertel 11535: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11536: 	}
1.594     albertel 11537: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11538:  
                   11539:         my $what = $spacequalifierrest;
                   11540: 	$what=~s/\./\_/;
1.282     albertel 11541: 	my $filename;
                   11542: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11543: 	if ($symbparm) {
1.409     www      11544: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11545: 	} else {
1.620     albertel 11546: 	    $filename=$env{'request.filename'};
1.282     albertel 11547: 	}
1.1362    raeburn  11548:         my $toolsymb;
                   11549:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11550:             $toolsymb = $symbparm;
                   11551:         }
                   11552: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11553: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11554: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11555: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11556: 
1.1301    raeburn  11557: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11558: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11559: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11560: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11561: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11562: 				     'course',$mapp,\$recursed,\@recurseup,
                   11563:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11564: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11565:                                       [$courseleveli,'map'   ],
1.927     albertel 11566: 				      [$courselevel, 'course']));
                   11567: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11568: 	}
1.145     www      11569: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11570: 	unless ($space eq '0') {
1.336     albertel 11571: 	    my @parts=split(/_/,$space);
                   11572: 	    my $id=pop(@parts);
                   11573: 	    my $part=join('_',@parts);
                   11574: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11575: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11576: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11577: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11578: 	}
1.395     albertel 11579: 	if ($recurse) { return undef; }
1.1362    raeburn  11580: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11581: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11582: # ---------------------------------------------------- Any other user namespace
                   11583:     } elsif ($realm eq 'environment') {
                   11584: # ----------------------------------------------------------------- environment
1.620     albertel 11585: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11586: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11587: 	} else {
1.770     albertel 11588: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11589: 		return '';
                   11590: 	    }
1.219     albertel 11591: 	    my %returnhash=&userenvironment($udom,$uname,
                   11592: 					    $spacequalifierrest);
                   11593: 	    return $returnhash{$spacequalifierrest};
                   11594: 	}
1.28      www      11595:     } elsif ($realm eq 'system') {
1.48      www      11596: # ----------------------------------------------------------------- system.time
                   11597: 	if ($space eq 'time') {
                   11598: 	    return time;
                   11599:         }
1.696     albertel 11600:     } elsif ($realm eq 'server') {
                   11601: # ----------------------------------------------------------------- system.time
                   11602: 	if ($space eq 'name') {
                   11603: 	    return $ENV{'SERVER_NAME'};
                   11604:         }
1.28      www      11605:     }
1.48      www      11606:     return '';
1.61      www      11607: }
                   11608: 
1.927     albertel 11609: sub get_reply {
                   11610:     my ($reply_value) = @_;
1.940     raeburn  11611:     if (ref($reply_value) eq 'ARRAY') {
                   11612:         if (wantarray) {
                   11613: 	    return @$reply_value;
                   11614:         }
                   11615:         return $reply_value->[0];
                   11616:     } else {
                   11617:         return $reply_value;
1.927     albertel 11618:     }
                   11619: }
                   11620: 
1.691     raeburn  11621: sub check_group_parms {
1.1301    raeburn  11622:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11623:         $recursed,$recurseupref) = @_;
                   11624:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11625:                   [$what,'course']);
                   11626:     my $coursereply;
1.691     raeburn  11627:     foreach my $group (@{$groups}) {
1.1301    raeburn  11628:         my @groupitems = ();
1.691     raeburn  11629:         foreach my $level (@levels) {
1.927     albertel 11630:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11631:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11632:         }
1.1301    raeburn  11633:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11634:                                    $env{'course.'.$courseid.'.domain'},
                   11635:                                    'course',$mapp,$recursed,$recurseupref,
                   11636:                                    $courseid,'.['.$group.'].',$what,
                   11637:                                    @groupitems);
                   11638:         last if (defined($coursereply));
1.691     raeburn  11639:     }
                   11640:     return $coursereply;
                   11641: }
                   11642: 
1.1301    raeburn  11643: sub get_map_hierarchy {
1.1302    raeburn  11644:     my ($mapname,$courseid) = @_;
                   11645:     my @recurseup = ();
1.1301    raeburn  11646:     if ($mapname) {
1.1302    raeburn  11647:         if (($cachedmapkey eq $courseid) &&
                   11648:             (abs($cachedmaptime-time)<5)) {
                   11649:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11650:                 return @{$cachedmaps{$mapname}};
                   11651:             }
                   11652:         }
1.1301    raeburn  11653:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11654:         if (ref($navmap)) {
                   11655:             @recurseup = $navmap->recurseup_maps($mapname);
                   11656:             undef($navmap);
1.1302    raeburn  11657:             $cachedmaps{$mapname} = \@recurseup;
                   11658:             $cachedmaptime=time;
                   11659:             $cachedmapkey=$courseid;
1.1301    raeburn  11660:         }
                   11661:     }
                   11662:     return @recurseup;
                   11663: }
                   11664: 
1.1302    raeburn  11665: }
                   11666: 
1.691     raeburn  11667: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11668:     my ($courseid,@groups) = @_;
                   11669:     @groups = sort(@groups);
1.691     raeburn  11670:     return @groups;
                   11671: }
                   11672: 
1.395     albertel 11673: sub packages_tab_default {
1.1362    raeburn  11674:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11675:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11676: 
                   11677:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11678:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11679: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11680: 	if ($pack_type eq 'default') {
                   11681: 	    $do_default=1;
                   11682: 	} elsif ($pack_type eq 'extension') {
                   11683: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11684: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11685: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11686: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11687: 	}
                   11688:     }
                   11689:     # first look for a package that matches the requested part id
                   11690:     foreach my $package (@specifics) {
                   11691: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11692: 	next if ($pack_part ne $part);
                   11693: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11694: 	    return $packagetab{"$pack_type&$name&default"};
                   11695: 	}
                   11696:     }
                   11697:     # look for any possible matching non extension_ package
                   11698:     foreach my $package (@specifics) {
                   11699: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11700: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11701: 	    return $packagetab{"$pack_type&$name&default"};
                   11702: 	}
1.585     albertel 11703: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11704: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11705: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11706: 	}
                   11707:     }
1.738     albertel 11708:     # look for any posible extension_ match
                   11709:     foreach my $package (@extension) {
                   11710: 	my ($package,$pack_type)=@{$package};
                   11711: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11712: 	    return $packagetab{"$pack_type&$name&default"};
                   11713: 	}
                   11714: 	if (defined($packagetab{$package."&$name&default"})) {
                   11715: 	    return $packagetab{$package."&$name&default"};
                   11716: 	}
                   11717:     }
                   11718:     # look for a global default setting
                   11719:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11720: 	return $packagetab{"default&$name&default"};
                   11721:     }
1.395     albertel 11722:     return undef;
                   11723: }
                   11724: 
1.334     albertel 11725: sub add_prefix_and_part {
                   11726:     my ($prefix,$part)=@_;
                   11727:     my $keyroot;
                   11728:     if (defined($prefix) && $prefix !~ /^__/) {
                   11729: 	# prefix that has a part already
                   11730: 	$keyroot=$prefix;
                   11731:     } elsif (defined($prefix)) {
                   11732: 	# prefix that is missing a part
                   11733: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11734:     } else {
                   11735: 	# no prefix at all
                   11736: 	if (defined($part)) { $keyroot='_'.$part; }
                   11737:     }
                   11738:     return $keyroot;
                   11739: }
                   11740: 
1.71      www      11741: # ---------------------------------------------------------------- Get metadata
                   11742: 
1.599     albertel 11743: my %metaentry;
1.1070    www      11744: my %importedpartids;
1.1369    raeburn  11745: my %importedrespids;
1.71      www      11746: sub metadata {
1.1362    raeburn  11747:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11748:     $uri=&declutter($uri);
1.288     albertel 11749:     # if it is a non metadata possible uri return quickly
1.529     albertel 11750:     if (($uri eq '') || 
                   11751: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11752: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11753:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11754: 	return undef;
                   11755:     }
1.1261    raeburn  11756:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11757: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11758: 	return undef;
1.288     albertel 11759:     }
1.73      www      11760:     my $filename=$uri;
                   11761:     $uri=~s/\.meta$//;
1.172     www      11762: #
                   11763: # Is the metadata already cached?
1.177     www      11764: # Look at timestamp of caching
1.172     www      11765: # Everything is cached by the main uri, libraries are never directly cached
                   11766: #
1.428     albertel 11767:     if (!defined($liburi)) {
1.599     albertel 11768: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11769: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11770:     }
1.1362    raeburn  11771: 
                   11772: #
                   11773: # If the uri is for an external tool the file from
                   11774: # which metadata should be retrieved depends on whether
                   11775: # the tool had been configured to be gradable (set in the Course
                   11776: # Editor or Resource Editor).
                   11777: #
                   11778: # If a valid symb has been included as the third arg in the call
                   11779: # to &metadata() that can be used to retrieve the value of
                   11780: # parameter_0_gradable set for the resource, and included in the
                   11781: # uploaded map containing the tool. The value is retrieved via
                   11782: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11783: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11784: # is retrieved via &get().
                   11785: #
                   11786: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11787: # hiddenresource and encrypturl (during course initialization)
                   11788: # the map-level parameter for resource.0.gradable included in the 
                   11789: # uploaded map containing the tool will not yet have been stored
                   11790: # in the user_course_parms.db file for the user's session, so in 
                   11791: # this case fall back to retrieving gradable status from the
                   11792: # exttool_$marker.db file.
1.1362    raeburn  11793: #
                   11794: # In order to avoid an infinite loop, &metadata() will return
                   11795: # before a call to &EXT(), if the uri is for an external tool
                   11796: # and the $what for which metadata is being requested is
                   11797: # parameter_0_gradable or 0_gradable.
                   11798: #
                   11799: 
                   11800:     if ($uri =~ /ext\.tool$/) {
                   11801:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11802:             return;
                   11803:         } else {
                   11804:             my ($checked,$use_passback);
                   11805:             if ($toolsymb ne '') {
                   11806:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11807:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11808:                     $checked = 1;
                   11809:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11810:                         $use_passback = 1;
                   11811:                     }
                   11812:                 }
                   11813:             }
                   11814:             unless ($checked) {
                   11815:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11816:                 $marker=~s/\D//g;
1.1363    raeburn  11817:                 if ($marker) {
1.1362    raeburn  11818:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11819:                     $use_passback = $toolsettings{'gradable'};
                   11820:                 }
                   11821:             }
                   11822:             if ($use_passback) {
                   11823:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11824:             } else {
                   11825:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11826:             }
                   11827:         }
                   11828:     }
                   11829: 
1.428     albertel 11830:     {
1.1069    www      11831: # Imported parts would go here
1.1369    raeburn  11832:         my @origfiletagids=();
1.1069    www      11833:         my $importedparts=0;
1.1369    raeburn  11834: 
                   11835: # Imported responseids would go here
                   11836:         my $importedresponses=0;
1.172     www      11837: #
                   11838: # Is this a recursive call for a library?
                   11839: #
1.599     albertel 11840: #	if (! exists($metacache{$uri})) {
                   11841: #	    $metacache{$uri}={};
                   11842: #	}
1.924     albertel 11843: 	my $cachetime = 60*60;
1.171     www      11844:         if ($liburi) {
                   11845: 	    $liburi=&declutter($liburi);
                   11846:             $filename=$liburi;
1.401     bowersj2 11847:         } else {
1.599     albertel 11848: 	    &devalidate_cache_new('meta',$uri);
                   11849: 	    undef(%metaentry);
1.401     bowersj2 11850: 	}
1.140     www      11851:         my %metathesekeys=();
1.73      www      11852:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11853: 	my $metastring;
1.1140    www      11854: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11855: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11856: 	    $metastring = 
1.929     albertel 11857: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11858: 					  ('grade_target' => 'meta'));
                   11859: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11860: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11861:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11862: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11863: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11864: 	    $metastring=&getfile($file);
1.489     albertel 11865: 	}
1.208     albertel 11866:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11867:         my $token;
1.140     www      11868:         undef %metathesekeys;
1.71      www      11869:         while ($token=$parser->get_token) {
1.339     albertel 11870: 	    if ($token->[0] eq 'S') {
                   11871: 		if (defined($token->[2]->{'package'})) {
1.172     www      11872: #
                   11873: # This is a package - get package info
                   11874: #
1.339     albertel 11875: 		    my $package=$token->[2]->{'package'};
                   11876: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11877: 		    if (defined($token->[2]->{'id'})) { 
                   11878: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11879: 		    }
1.599     albertel 11880: 		    if ($metaentry{':packages'}) {
                   11881: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11882: 		    } else {
1.599     albertel 11883: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11884: 		    }
1.736     albertel 11885: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11886: 			my $part=$keyroot;
                   11887: 			$part=~s/^\_//;
1.736     albertel 11888: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11889: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11890: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11891: 			    # ignore package.tab specified default values
                   11892:                             # here &package_tab_default() will fetch those
                   11893: 			    if ($subp eq 'default') { next; }
1.736     albertel 11894: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11895: 			    my $unikey;
                   11896: 			    if ($pack =~ /_0$/) {
                   11897: 				$unikey='parameter_0_'.$name;
                   11898: 				$part=0;
                   11899: 			    } else {
                   11900: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11901: 			    }
1.339     albertel 11902: 			    if ($subp eq 'display') {
                   11903: 				$value.=' [Part: '.$part.']';
                   11904: 			    }
1.599     albertel 11905: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11906: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11907: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11908: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11909: 			    }
1.599     albertel 11910: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11911: 				$metaentry{':'.$unikey}=
                   11912: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11913: 			    }
1.339     albertel 11914: 			}
                   11915: 		    }
                   11916: 		} else {
1.172     www      11917: #
                   11918: # This is not a package - some other kind of start tag
1.339     albertel 11919: #
                   11920: 		    my $entry=$token->[1];
1.1068    www      11921: 		    my $unikey='';
1.175     www      11922: 
1.339     albertel 11923: 		    if ($entry eq 'import') {
1.175     www      11924: #
                   11925: # Importing a library here
1.339     albertel 11926: #
1.1067    www      11927:                         my $location=$parser->get_text('/import');
                   11928:                         my $dir=$filename;
                   11929:                         $dir=~s|[^/]*$||;
                   11930:                         $location=&filelocation($dir,$location);
1.1369    raeburn  11931: 
                   11932:                         my $importid=$token->[2]->{'id'};
1.1068    www      11933:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  11934: #
                   11935: # Check metadata for imported file to
                   11936: # see if it contained response items
                   11937: #
1.1372    raeburn  11938:                         my ($origfile,@libfilekeys);
1.1370    raeburn  11939:                         my %currmetaentry = %metaentry;
1.1372    raeburn  11940:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   11941:                                                            $depthcount+1));
                   11942:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   11943:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   11944:                                                              undef,$depthcount+1);
                   11945:                             if ($libresponseorder ne '') {
                   11946:                                 if ($#origfiletagids<0) {
                   11947:                                     undef(%importedrespids);
                   11948:                                     undef(%importedpartids);
                   11949:                                 }
1.1373    raeburn  11950:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   11951:                                 if (@respids) {
                   11952:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   11953:                                 }
                   11954:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  11955:                                     $importedresponses = 1;
1.1369    raeburn  11956: # We need to get the original file and the imported file to get the response order correct
                   11957: # Load and inspect original file
1.1372    raeburn  11958:                                     if ($#origfiletagids<0) {
                   11959:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11960:                                         $origfile=&getfile($origfilelocation);
                   11961:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11962:                                     }
1.1369    raeburn  11963:                                 }
                   11964:                             }
                   11965:                         }
1.1370    raeburn  11966: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11967: # hash populated for imported library file
                   11968:                         %metaentry = %currmetaentry;
                   11969:                         undef(%currmetaentry);
1.1374    raeburn  11970:                         if ($importmode eq 'part') {
1.1068    www      11971: # Import as part(s)
1.1069    www      11972:                            $importedparts=1;
                   11973: # We need to get the original file and the imported file to get the part order correct
                   11974: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  11975: # Load and inspect original file if we didn't do that already
                   11976:                            if ($#origfiletagids<0) {
                   11977:                                undef(%importedrespids);
                   11978:                                undef(%importedpartids);
                   11979:                                if ($origfile eq '') {
                   11980:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11981:                                    $origfile=&getfile($origfilelocation);
                   11982:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11983:                                }
1.1070    www      11984:                            }
1.1372    raeburn  11985:                            my @impfilepartids;
                   11986: # If <partorder> tag is included in metadata for the imported file
                   11987: # get the parts in the imported file from that.
                   11988:                            if (grep(/^partorder$/,@libfilekeys)) {
                   11989:                                %currmetaentry = %metaentry;
                   11990:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   11991:                                                             $depthcount+1);
                   11992:                                %metaentry = %currmetaentry;
                   11993:                                undef(%currmetaentry);
                   11994:                                if ($libpartorder ne '') {
                   11995:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   11996:                                }
                   11997:                            } else {
                   11998: # If no <partorder> tag available, load and inspect imported file
                   11999:                                my $impfile=&getfile($location);
                   12000:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   12001:                            }
1.1069    www      12002:                            if ($#impfilepartids>=0) {
                   12003: # This problem had parts
1.1070    www      12004:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12005:                            } else {
                   12006: # Importing by turning a single problem into a problem part
                   12007: # It gets the import-tags ID as part-ID
                   12008:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12009:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12010:                            }
1.1068    www      12011:                         } else {
1.1374    raeburn  12012: # Import as problem or as normal import
                   12013:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12014:                             unless ($importmode eq 'problem') {
1.1068    www      12015: # Normal import
1.1374    raeburn  12016:                                 if (defined($token->[2]->{'id'})) {
                   12017:                                     $unikey.='_'.$token->[2]->{'id'};
                   12018:                                 }
                   12019:                             }
                   12020: # Check metadata for imported file to
                   12021: # see if it contained parts
                   12022:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12023:                                 %currmetaentry = %metaentry;
                   12024:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12025:                                                              $depthcount+1);
                   12026:                                 %metaentry = %currmetaentry;
                   12027:                                 undef(%currmetaentry);
                   12028:                                 if ($libpartorder ne '') {
                   12029:                                     $importedparts = 1;
                   12030:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12031:                                 }
                   12032:                             }
1.1067    www      12033:                         }
1.339     albertel 12034: 			if ($depthcount<20) {
1.736     albertel 12035: 			    my $metadata = 
1.1362    raeburn  12036: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12037: 					  $depthcount+1);
                   12038: 			    foreach my $meta (split(',',$metadata)) {
                   12039: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12040: 				$metathesekeys{$meta}=1;
1.339     albertel 12041: 			    }
1.1068    www      12042:                         }
1.1067    www      12043: 		    } else {
                   12044: #
                   12045: # Not importing, some other kind of non-package, non-library start tag
                   12046: # 
                   12047:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12048:                         if (defined($token->[2]->{'id'})) {
                   12049:                             $unikey.='_'.$token->[2]->{'id'};
                   12050:                         }
1.339     albertel 12051: 			if (defined($token->[2]->{'name'})) { 
                   12052: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12053: 			}
                   12054: 			$metathesekeys{$unikey}=1;
1.736     albertel 12055: 			foreach my $param (@{$token->[3]}) {
                   12056: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12057: 				$token->[2]->{$param};
1.339     albertel 12058: 			}
                   12059: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12060: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12061: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12062: 		 # only ws inside the tag, and not in default, so use default
                   12063: 		 # as value
1.599     albertel 12064: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12065: 			} elsif ( $internaltext =~ /\S/ ) {
                   12066: 		  # something interesting inside the tag
                   12067: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12068: 			} else {
1.908     albertel 12069: 		  # no interesting values, don't set a default
1.339     albertel 12070: 			}
1.172     www      12071: # end of not-a-package not-a-library import
1.339     albertel 12072: 		    }
1.172     www      12073: # end of not-a-package start tag
1.339     albertel 12074: 		}
1.172     www      12075: # the next is the end of "start tag"
1.339     albertel 12076: 	    }
                   12077: 	}
1.483     albertel 12078: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12079: 	$extension = lc($extension);
                   12080: 	if ($extension eq 'htm') { $extension='html'; }
                   12081: 
1.737     albertel 12082: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12083: 	    #no specific packages #how's our extension
                   12084: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12085: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12086: 					 \%metathesekeys);
                   12087: 	}
1.883     albertel 12088: 
                   12089: 	if (!exists($metaentry{':packages'})
                   12090: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12091: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12092: 		#no specific packages well let's get default then
                   12093: 		if ($key!~/^default&/) { next; }
1.488     albertel 12094: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12095: 					     \%metathesekeys);
                   12096: 	    }
                   12097: 	}
1.338     www      12098: # are there custom rights to evaluate
1.599     albertel 12099: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12100: 
1.338     www      12101:     #
                   12102:     # Importing a rights file here
1.339     albertel 12103:     #
                   12104: 	    unless ($depthcount) {
1.599     albertel 12105: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12106: 		my $dir=$filename;
                   12107: 		$dir=~s|[^/]*$||;
                   12108: 		$location=&filelocation($dir,$location);
1.736     albertel 12109: 		my $rights_metadata =
1.1362    raeburn  12110: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12111: 			      $depthcount+1);
                   12112: 		foreach my $rights (split(',',$rights_metadata)) {
                   12113: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12114: 		    $metathesekeys{$rights}=1;
1.339     albertel 12115: 		}
                   12116: 	    }
                   12117: 	}
1.737     albertel 12118: 	# uniqifiy package listing
                   12119: 	my %seen;
                   12120: 	my @uniq_packages =
                   12121: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12122: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12123: 
1.1369    raeburn  12124:         if (($importedresponses) || ($importedparts)) {
                   12125:             if ($importedparts) {
1.1070    www      12126: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12127:                 $metaentry{':partorder'}='';
                   12128:                 $metathesekeys{'partorder'}=1;
                   12129:             }
                   12130:             if ($importedresponses) {
                   12131: # We had imported responses and need to rebuil responseorder
                   12132:                 $metaentry{':responseorder'}='';
                   12133:                 $metathesekeys{'responseorder'}=1;
                   12134:             }
                   12135:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12136:                 my $origid = $origfiletagids[$index+1];
                   12137:                 if ($origfiletagids[$index] eq 'part') {
                   12138: # Original part, part of the problem
                   12139:                     if ($importedparts) {
                   12140:                         $metaentry{':partorder'}.=','.$origid;
                   12141:                     }
                   12142:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12143:                     if ($importedparts) {
                   12144: # We have imported parts at this position
1.1373    raeburn  12145:                         if ($importedpartids{$origid} ne '') {
                   12146:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12147:                         }
1.1369    raeburn  12148:                     }
                   12149:                     if ($importedresponses) {
                   12150: # We have imported responses at this position
1.1373    raeburn  12151:                         if ($importedrespids{$origid} ne '') {
                   12152:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12153:                         }
                   12154:                     }
                   12155:                 } else {
                   12156: # Original response item, part of the problem
                   12157:                     if ($importedresponses) {
                   12158:                         $metaentry{':responseorder'}.=','.$origid;
                   12159:                     }
                   12160:                 }
                   12161:             }
                   12162:             if ($importedparts) {
                   12163:                 $metaentry{':partorder'}=~s/^\,//;
                   12164:             }
                   12165:             if ($importedresponses) {
                   12166:                 $metaentry{':responseorder'}=~s/^\,//;
                   12167:             }
1.1070    www      12168:         }
1.737     albertel 12169: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12170: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12171: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12172:         unless ($liburi) {
                   12173: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12174:         }
1.177     www      12175: # this is the end of "was not already recently cached
1.71      www      12176:     }
1.599     albertel 12177:     return $metaentry{':'.$what};
1.261     albertel 12178: }
                   12179: 
1.488     albertel 12180: sub metadata_create_package_def {
1.483     albertel 12181:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12182:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12183:     if ($subp eq 'default') { next; }
                   12184:     
1.599     albertel 12185:     if (defined($metaentry{':packages'})) {
                   12186: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12187:     } else {
1.599     albertel 12188: 	$metaentry{':packages'}=$package;
1.483     albertel 12189:     }
                   12190:     my $value=$packagetab{$key};
                   12191:     my $unikey;
                   12192:     $unikey='parameter_0_'.$name;
1.599     albertel 12193:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12194:     $$metathesekeys{$unikey}=1;
1.599     albertel 12195:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12196: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12197:     }
1.599     albertel 12198:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12199: 	$metaentry{':'.$unikey}=
                   12200: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12201:     }
                   12202: }
                   12203: 
1.261     albertel 12204: sub metadata_generate_part0 {
                   12205:     my ($metadata,$metacache,$uri) = @_;
                   12206:     my %allnames;
1.737     albertel 12207:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12208: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12209: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12210: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12211: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12212: 	    $allnames{$name}=$part;
                   12213: 	  }
                   12214: 	}
                   12215:     }
                   12216:     foreach my $name (keys(%allnames)) {
                   12217:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12218:       my $key=":parameter_0_$name";
1.261     albertel 12219:       $$metacache{"$key.part"}='0';
                   12220:       $$metacache{"$key.name"}=$name;
1.428     albertel 12221:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12222: 					   $allnames{$name}.'_'.$name.
                   12223: 					   '.type'};
1.428     albertel 12224:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12225: 			     '.display'};
1.644     www      12226:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12227:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12228:       $$metacache{"$key.display"}=$olddis;
                   12229:     }
1.71      www      12230: }
                   12231: 
1.764     albertel 12232: # ------------------------------------------------------ Devalidate title cache
                   12233: 
                   12234: sub devalidate_title_cache {
                   12235:     my ($url)=@_;
                   12236:     if (!$env{'request.course.id'}) { return; }
                   12237:     my $symb=&symbread($url);
                   12238:     if (!$symb) { return; }
                   12239:     my $key=$env{'request.course.id'}."\0".$symb;
                   12240:     &devalidate_cache_new('title',$key);
                   12241: }
                   12242: 
1.1014    droeschl 12243: # ------------------------------------------------- Get the title of a course
                   12244: 
                   12245: sub current_course_title {
                   12246:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12247: }
1.301     www      12248: # ------------------------------------------------- Get the title of a resource
                   12249: 
                   12250: sub gettitle {
                   12251:     my $urlsymb=shift;
                   12252:     my $symb=&symbread($urlsymb);
1.534     albertel 12253:     if ($symb) {
1.620     albertel 12254: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12255: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12256: 	if (defined($cached)) { 
                   12257: 	    return $result;
                   12258: 	}
1.534     albertel 12259: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12260: 	my $title='';
1.907     albertel 12261: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12262: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12263: 	} else {
                   12264: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12265: 		    &GDBM_READER(),0640)) {
                   12266: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12267: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12268: 		untie(%bighash);
                   12269: 	    }
1.534     albertel 12270: 	}
                   12271: 	$title=~s/\&colon\;/\:/gs;
                   12272: 	if ($title) {
1.1159    www      12273: # Remember both $symb and $title for dynamic metadata
                   12274:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12275:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12276: # Cache this title and then return it
1.599     albertel 12277: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12278: 	}
                   12279: 	$urlsymb=$url;
                   12280:     }
                   12281:     my $title=&metadata($urlsymb,'title');
                   12282:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12283:     return $title;
1.301     www      12284: }
1.613     albertel 12285: 
1.614     albertel 12286: sub get_slot {
                   12287:     my ($which,$cnum,$cdom)=@_;
                   12288:     if (!$cnum || !$cdom) {
1.790     albertel 12289: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12290: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12291: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12292:     }
1.703     albertel 12293:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12294:     my %slotinfo;
                   12295:     if (exists($remembered{$key})) {
                   12296: 	$slotinfo{$which} = $remembered{$key};
                   12297:     } else {
                   12298: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12299: 	&Apache::lonhomework::showhash(%slotinfo);
                   12300: 	my ($tmp)=keys(%slotinfo);
                   12301: 	if ($tmp=~/^error:/) { return (); }
                   12302: 	$remembered{$key} = $slotinfo{$which};
                   12303:     }
1.616     albertel 12304:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12305: 	return %{$slotinfo{$which}};
                   12306:     }
                   12307:     return $slotinfo{$which};
1.614     albertel 12308: }
1.1150    raeburn  12309: 
                   12310: sub get_reservable_slots {
                   12311:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12312:     my $now = time;
                   12313:     my $reservable_info;
                   12314:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12315:     if (exists($remembered{$key})) {
                   12316:         $reservable_info = $remembered{$key};
                   12317:     } else {
                   12318:         my %resv;
                   12319:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12320:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12321:         $reservable_info = \%resv;
                   12322:         $remembered{$key} = $reservable_info;
                   12323:     }
                   12324:     return $reservable_info;
                   12325: }
                   12326: 
                   12327: sub get_course_slots {
                   12328:     my ($cnum,$cdom) = @_;
                   12329:     my $hashid=$cnum.':'.$cdom;
                   12330:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12331:     if (defined($cached)) {
                   12332:         if (ref($result) eq 'HASH') {
                   12333:             return %{$result};
                   12334:         }
                   12335:     } else {
                   12336:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12337:         my ($tmp) = keys(%slots);
                   12338:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12339:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12340:             return %slots;
                   12341:         }
                   12342:     }
                   12343:     return;
                   12344: }
                   12345: 
                   12346: sub devalidate_slots_cache {
                   12347:     my ($cnum,$cdom)=@_;
                   12348:     my $hashid=$cnum.':'.$cdom;
                   12349:     &devalidate_cache_new('allslots',$hashid);
                   12350: }
                   12351: 
1.1181    raeburn  12352: sub get_coursechange {
                   12353:     my ($cdom,$cnum) = @_;
                   12354:     if ($cdom eq '' || $cnum eq '') {
                   12355:         return unless ($env{'request.course.id'});
                   12356:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12357:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12358:     }
                   12359:     my $hashid=$cdom.'_'.$cnum;
                   12360:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12361:     if ((defined($cached)) && ($change ne '')) {
                   12362:         return $change;
                   12363:     } else {
                   12364:         my %crshash;
                   12365:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12366:         if ($crshash{'internal.contentchange'} eq '') {
                   12367:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12368:             if ($change eq '') {
                   12369:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12370:                 $change = $crshash{'internal.created'};
                   12371:             }
                   12372:         } else {
                   12373:             $change = $crshash{'internal.contentchange'};
                   12374:         }
                   12375:         my $cachetime = 600;
                   12376:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12377:     }
                   12378:     return $change;
                   12379: }
                   12380: 
                   12381: sub devalidate_coursechange_cache {
                   12382:     my ($cnum,$cdom)=@_;
                   12383:     my $hashid=$cnum.':'.$cdom;
                   12384:     &devalidate_cache_new('crschange',$hashid);
                   12385: }
                   12386: 
1.31      www      12387: # ------------------------------------------------- Update symbolic store links
                   12388: 
                   12389: sub symblist {
                   12390:     my ($mapname,%newhash)=@_;
1.438     www      12391:     $mapname=&deversion(&declutter($mapname));
1.31      www      12392:     my %hash;
1.620     albertel 12393:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12394:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12395:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12396: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12397: 		next if ($url eq 'last_known'
                   12398: 			 && $env{'form.no_update_last_known'});
                   12399: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12400: 						    $newhash{$url}->[1],
                   12401: 						    $newhash{$url}->[0]);
1.191     harris41 12402:             }
1.31      www      12403:             if (untie(%hash)) {
                   12404: 		return 'ok';
                   12405:             }
                   12406:         }
                   12407:     }
                   12408:     return 'error';
1.212     www      12409: }
                   12410: 
                   12411: # --------------------------------------------------------------- Verify a symb
                   12412: 
                   12413: sub symbverify {
1.1190    raeburn  12414:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12415:     my $thisfn=$thisurl;
1.439     www      12416:     $thisfn=&declutter($thisfn);
1.215     www      12417: # direct jump to resource in page or to a sequence - will construct own symbs
                   12418:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12419: # check URL part
1.409     www      12420:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12421: 
1.431     www      12422:     unless ($url eq $thisfn) { return 0; }
1.213     www      12423: 
1.216     www      12424:     $symb=&symbclean($symb);
1.510     www      12425:     $thisurl=&deversion($thisurl);
1.439     www      12426:     $thisfn=&deversion($thisfn);
1.213     www      12427: 
                   12428:     my %bighash;
                   12429:     my $okay=0;
1.431     www      12430: 
1.620     albertel 12431:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12432:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12433:         my $noclutter;
1.1032    raeburn  12434:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12435:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12436:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12437:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12438:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12439:                 $noclutter = 1;
                   12440:             }
                   12441:         }
                   12442:         my $ids;
                   12443:         if ($noclutter) {
                   12444:             $ids=$bighash{'ids_'.$thisurl};
                   12445:         } else {
                   12446:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12447:         }
1.1102    raeburn  12448:         unless ($ids) {
                   12449:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12450:             $ids=$bighash{$idkey};
1.216     www      12451:         }
                   12452:         if ($ids) {
                   12453: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12454:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12455:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12456:             }
1.800     albertel 12457: 	    foreach my $id (split(/\,/,$ids)) {
                   12458: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12459:                if (
                   12460:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12461:    eq $symb) {
                   12462:                    if (ref($encstate)) {
                   12463:                        $$encstate = $bighash{'encrypted_'.$id};
                   12464:                    }
1.620     albertel 12465: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12466: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12467:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12468: 		       $okay=1;
1.1202    raeburn  12469:                        last;
1.582     albertel 12470: 		   }
                   12471: 	       }
1.216     www      12472: 	   }
                   12473:         }
1.213     www      12474: 	untie(%bighash);
                   12475:     }
                   12476:     return $okay;
1.31      www      12477: }
                   12478: 
1.210     www      12479: # --------------------------------------------------------------- Clean-up symb
                   12480: 
                   12481: sub symbclean {
                   12482:     my $symb=shift;
1.568     albertel 12483:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12484: # remove version from map
                   12485:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12486: 
1.210     www      12487: # remove version from URL
                   12488:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12489: 
1.507     www      12490: # remove wrapper
                   12491: 
1.510     www      12492:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12493:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12494:     return $symb;
1.409     www      12495: }
                   12496: 
                   12497: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12498: 
                   12499: sub encode_symb {
                   12500:     my ($map,$resid,$url)=@_;
                   12501:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12502: }
1.409     www      12503: 
                   12504: sub decode_symb {
1.568     albertel 12505:     my $symb=shift;
                   12506:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12507:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12508:     return (&fixversion($map),$resid,&fixversion($url));
                   12509: }
                   12510: 
                   12511: sub fixversion {
                   12512:     my $fn=shift;
1.609     banghart 12513:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12514:     my %bighash;
                   12515:     my $uri=&clutter($fn);
1.620     albertel 12516:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12517: # is this cached?
1.599     albertel 12518:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12519:     if (defined($cached)) { return $result; }
                   12520: # unfortunately not cached, or expired
1.620     albertel 12521:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12522: 	    &GDBM_READER(),0640)) {
                   12523:  	if ($bighash{'version_'.$uri}) {
                   12524:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12525:  	    unless (($version eq 'mostrecent') || 
                   12526: 		    ($version==&getversion($uri))) {
1.440     www      12527:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12528:  	    }
                   12529:  	}
                   12530:  	untie %bighash;
1.413     www      12531:     }
1.599     albertel 12532:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12533: }
                   12534: 
                   12535: sub deversion {
                   12536:     my $url=shift;
                   12537:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12538:     return $url;
1.210     www      12539: }
                   12540: 
1.31      www      12541: # ------------------------------------------------------ Return symb list entry
                   12542: 
                   12543: sub symbread {
1.1282    raeburn  12544:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12545:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12546:     if (defined($env{$cache_str})) {
                   12547:         if ($ignorecachednull) {
                   12548:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12549:         } else {
                   12550:             return $env{$cache_str};
                   12551:         }
                   12552:     }
1.242     www      12553: # no filename provided? try from environment
1.1265    raeburn  12554:     unless ($thisfn) {
1.620     albertel 12555:         if ($env{'request.symb'}) {
                   12556: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12557: 	}
1.620     albertel 12558: 	$thisfn=$env{'request.filename'};
1.44      www      12559:     }
1.569     albertel 12560:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12561: # is that filename actually a symb? Verify, clean, and return
                   12562:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12563: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12564: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12565: 	}
1.242     www      12566:     }
1.44      www      12567:     $thisfn=declutter($thisfn);
1.31      www      12568:     my %hash;
1.37      www      12569:     my %bighash;
                   12570:     my $syval='';
1.620     albertel 12571:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12572:         my $targetfn = $thisfn;
1.609     banghart 12573:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12574:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12575:         }
1.687     albertel 12576: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12577: 	    $targetfn=$1;
                   12578: 	}
1.620     albertel 12579:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12580:                       &GDBM_READER(),0640)) {
1.481     raeburn  12581: 	    $syval=$hash{$targetfn};
1.37      www      12582:             untie(%hash);
                   12583:         }
                   12584: # ---------------------------------------------------------- There was an entry
                   12585:         if ($syval) {
1.601     albertel 12586: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12587: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12588: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12589: 		    #return $env{$cache_str}='';
1.601     albertel 12590: 		#}    
                   12591: 		#$syval.=$1;
                   12592: 	    #}
1.37      www      12593:         } else {
                   12594: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12595:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12596:                             &GDBM_READER(),0640)) {
1.37      www      12597: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12598:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12599:               unless ($ids) { 
                   12600:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12601:               }
                   12602:               unless ($ids) {
                   12603: # alias?
                   12604: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12605:               }
1.37      www      12606:               if ($ids) {
                   12607: # ------------------------------------------------------------------- Has ID(s)
                   12608:                  my @possibilities=split(/\,/,$ids);
1.39      www      12609:                  if ($#possibilities==0) {
                   12610: # ----------------------------------------------- There is only one possibility
1.37      www      12611: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12612: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12613: 						    $resid,$thisfn);
1.1282    raeburn  12614:                      if (ref($possibles) eq 'HASH') {
                   12615:                          $possibles->{$syval} = 1;    
                   12616:                      }
                   12617:                      if ($checkforblock) {
                   12618:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12619:                          if (@blockers) {
                   12620:                              $syval = '';
                   12621:                              return;
                   12622:                          }
                   12623:                      }
                   12624:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12625: # ------------------------------------------ There is more than one possibility
                   12626:                      my $realpossible=0;
1.800     albertel 12627:                      foreach my $id (@possibilities) {
                   12628: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12629:                          my $canaccess;
                   12630:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12631:                              $canaccess = 1;
                   12632:                          } else { 
                   12633:                              $canaccess = &allowed('bre',$file);
                   12634:                          }
                   12635:                          if ($canaccess) {
                   12636:          		     my ($mapid,$resid)=split(/\./,$id);
                   12637:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12638:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12639: 						             $resid,$thisfn);
                   12640:                                  if (ref($possibles) eq 'HASH') {
                   12641:                                      $possibles->{$syval} = 1;
                   12642:                                  }
                   12643:                                  if ($checkforblock) {
                   12644:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12645:                                      unless (@blockers > 0) {
                   12646:                                          $syval = $poss_syval;
                   12647:                                          $realpossible++;
                   12648:                                      }
                   12649:                                  } else {
                   12650:                                      $syval = $poss_syval;
                   12651:                                      $realpossible++;
                   12652:                                  }
                   12653:                              }
1.39      www      12654: 			 }
1.191     harris41 12655:                      }
1.39      www      12656: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12657:                  } else {
                   12658:                      $syval='';
1.37      www      12659:                  }
                   12660: 	      }
1.1282    raeburn  12661:               untie(%bighash);
1.481     raeburn  12662:            }
1.31      www      12663:         }
1.62      www      12664:         if ($syval) {
1.620     albertel 12665: 	    return $env{$cache_str}=$syval;
1.62      www      12666:         }
1.31      www      12667:     }
1.949     raeburn  12668:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12669:     return $env{$cache_str}='';
1.31      www      12670: }
                   12671: 
                   12672: # ---------------------------------------------------------- Return random seed
                   12673: 
1.32      www      12674: sub numval {
                   12675:     my $txt=shift;
                   12676:     $txt=~tr/A-J/0-9/;
                   12677:     $txt=~tr/a-j/0-9/;
                   12678:     $txt=~tr/K-T/0-9/;
                   12679:     $txt=~tr/k-t/0-9/;
                   12680:     $txt=~tr/U-Z/0-5/;
                   12681:     $txt=~tr/u-z/0-5/;
                   12682:     $txt=~s/\D//g;
1.564     albertel 12683:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12684:     return int($txt);
1.368     albertel 12685: }
                   12686: 
1.484     albertel 12687: sub numval2 {
                   12688:     my $txt=shift;
                   12689:     $txt=~tr/A-J/0-9/;
                   12690:     $txt=~tr/a-j/0-9/;
                   12691:     $txt=~tr/K-T/0-9/;
                   12692:     $txt=~tr/k-t/0-9/;
                   12693:     $txt=~tr/U-Z/0-5/;
                   12694:     $txt=~tr/u-z/0-5/;
                   12695:     $txt=~s/\D//g;
                   12696:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12697:     my $total;
                   12698:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12699:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12700:     return int($total);
                   12701: }
                   12702: 
1.575     albertel 12703: sub numval3 {
                   12704:     use integer;
                   12705:     my $txt=shift;
                   12706:     $txt=~tr/A-J/0-9/;
                   12707:     $txt=~tr/a-j/0-9/;
                   12708:     $txt=~tr/K-T/0-9/;
                   12709:     $txt=~tr/k-t/0-9/;
                   12710:     $txt=~tr/U-Z/0-5/;
                   12711:     $txt=~tr/u-z/0-5/;
                   12712:     $txt=~s/\D//g;
                   12713:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12714:     my $total;
                   12715:     foreach my $val (@txts) { $total+=$val; }
                   12716:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12717:     return $total;
                   12718: }
                   12719: 
1.675     albertel 12720: sub digest {
                   12721:     my ($data)=@_;
                   12722:     my $digest=&Digest::MD5::md5($data);
                   12723:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12724:     my ($e,$f);
                   12725:     {
                   12726:         use integer;
                   12727:         $e=($a+$b);
                   12728:         $f=($c+$d);
                   12729:         if ($_64bit) {
                   12730:             $e=(($e<<32)>>32);
                   12731:             $f=(($f<<32)>>32);
                   12732:         }
                   12733:     }
                   12734:     if (wantarray) {
                   12735: 	return ($e,$f);
                   12736:     } else {
                   12737: 	my $g;
                   12738: 	{
                   12739: 	    use integer;
                   12740: 	    $g=($e+$f);
                   12741: 	    if ($_64bit) {
                   12742: 		$g=(($g<<32)>>32);
                   12743: 	    }
                   12744: 	}
                   12745: 	return $g;
                   12746:     }
                   12747: }
                   12748: 
1.368     albertel 12749: sub latest_rnd_algorithm_id {
1.675     albertel 12750:     return '64bit5';
1.366     albertel 12751: }
1.32      www      12752: 
1.503     albertel 12753: sub get_rand_alg {
                   12754:     my ($courseid)=@_;
1.790     albertel 12755:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12756:     if ($courseid) {
1.620     albertel 12757: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12758:     }
                   12759:     return &latest_rnd_algorithm_id();
                   12760: }
                   12761: 
1.562     albertel 12762: sub validCODE {
                   12763:     my ($CODE)=@_;
                   12764:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12765:     return 0;
                   12766: }
                   12767: 
1.491     albertel 12768: sub getCODE {
1.620     albertel 12769:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12770:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12771: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12772: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12773: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12774:     }
                   12775:     return undef;
                   12776: }
1.1133    foxr     12777: #
                   12778: #  Determines the random seed for a specific context:
                   12779: #
                   12780: # parameters:
                   12781: #   symb      - in course context the symb for the seed.
                   12782: #   course_id - The course id of the form domain_coursenum.
                   12783: #   domain    - Domain for the user.
                   12784: #   course    - Course for the user.
                   12785: #   cenv      - environment of the course.
                   12786: #
                   12787: # NOTE:
                   12788: #   All parameters are picked out of the environment if missing
                   12789: #   or not defined.
                   12790: #   If a symb cannot be determined the current time is used instead.
                   12791: #
                   12792: #  For a given well defined symb, courside, domain, username,
                   12793: #  and course environment, the seed is reproducible.
                   12794: #
1.31      www      12795: sub rndseed {
1.1133    foxr     12796:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12797:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12798:     if (!defined($symb)) {
1.366     albertel 12799: 	unless ($symb=$wsymb) { return time; }
                   12800:     }
1.1146    foxr     12801:     if (!defined $courseid) { 
                   12802: 	$courseid=$wcourseid; 
                   12803:     }
                   12804:     if (!defined $domain) { $domain=$wdomain; }
                   12805:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12806: 
                   12807:     my $which;
                   12808:     if (defined($cenv->{'rndseed'})) {
                   12809: 	$which = $cenv->{'rndseed'};
                   12810:     } else {
                   12811: 	$which =&get_rand_alg($courseid);
                   12812:     }
1.491     albertel 12813:     if (defined(&getCODE())) {
1.1133    foxr     12814: 
1.675     albertel 12815: 	if ($which eq '64bit5') {
                   12816: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12817: 	} elsif ($which eq '64bit4') {
1.575     albertel 12818: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12819: 	} else {
                   12820: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12821: 	}
1.675     albertel 12822:     } elsif ($which eq '64bit5') {
                   12823: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12824:     } elsif ($which eq '64bit4') {
                   12825: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12826:     } elsif ($which eq '64bit3') {
                   12827: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12828:     } elsif ($which eq '64bit2') {
                   12829: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12830:     } elsif ($which eq '64bit') {
                   12831: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12832:     }
                   12833:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12834: }
                   12835: 
                   12836: sub rndseed_32bit {
                   12837:     my ($symb,$courseid,$domain,$username)=@_;
                   12838:     {
                   12839: 	use integer;
                   12840: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12841: 	my $symbseed=numval($symb) << 22;
                   12842: 	my $namechck=unpack("%32C*",$username) << 17;
                   12843: 	my $nameseed=numval($username) << 12;
                   12844: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12845: 	my $courseseed=unpack("%32C*",$courseid);
                   12846: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12847: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12848: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12849: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12850: 	return $num;
                   12851:     }
                   12852: }
                   12853: 
                   12854: sub rndseed_64bit {
                   12855:     my ($symb,$courseid,$domain,$username)=@_;
                   12856:     {
                   12857: 	use integer;
                   12858: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12859: 	my $symbseed=numval($symb) << 10;
                   12860: 	my $namechck=unpack("%32S*",$username);
                   12861: 	
                   12862: 	my $nameseed=numval($username) << 21;
                   12863: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12864: 	my $courseseed=unpack("%32S*",$courseid);
                   12865: 	
                   12866: 	my $num1=$symbchck+$symbseed+$namechck;
                   12867: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12868: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12869: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12870: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12871: 	return "$num1,$num2";
1.155     albertel 12872:     }
1.366     albertel 12873: }
                   12874: 
1.443     albertel 12875: sub rndseed_64bit2 {
                   12876:     my ($symb,$courseid,$domain,$username)=@_;
                   12877:     {
                   12878: 	use integer;
                   12879: 	# strings need to be an even # of cahracters long, it it is odd the
                   12880:         # last characters gets thrown away
                   12881: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12882: 	my $symbseed=numval($symb) << 10;
                   12883: 	my $namechck=unpack("%32S*",$username.' ');
                   12884: 	
                   12885: 	my $nameseed=numval($username) << 21;
1.501     albertel 12886: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12887: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12888: 	
                   12889: 	my $num1=$symbchck+$symbseed+$namechck;
                   12890: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12891: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12892: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12893: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12894: 	return "$num1,$num2";
                   12895:     }
                   12896: }
                   12897: 
                   12898: sub rndseed_64bit3 {
                   12899:     my ($symb,$courseid,$domain,$username)=@_;
                   12900:     {
                   12901: 	use integer;
                   12902: 	# strings need to be an even # of cahracters long, it it is odd the
                   12903:         # last characters gets thrown away
                   12904: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12905: 	my $symbseed=numval2($symb) << 10;
                   12906: 	my $namechck=unpack("%32S*",$username.' ');
                   12907: 	
                   12908: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12909: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12910: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12911: 	
                   12912: 	my $num1=$symbchck+$symbseed+$namechck;
                   12913: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12914: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12915: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12916: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12917: 	
1.503     albertel 12918: 	return "$num1:$num2";
1.443     albertel 12919:     }
                   12920: }
                   12921: 
1.575     albertel 12922: sub rndseed_64bit4 {
                   12923:     my ($symb,$courseid,$domain,$username)=@_;
                   12924:     {
                   12925: 	use integer;
                   12926: 	# strings need to be an even # of cahracters long, it it is odd the
                   12927:         # last characters gets thrown away
                   12928: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12929: 	my $symbseed=numval3($symb) << 10;
                   12930: 	my $namechck=unpack("%32S*",$username.' ');
                   12931: 	
                   12932: 	my $nameseed=numval3($username) << 21;
                   12933: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12934: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12935: 	
                   12936: 	my $num1=$symbchck+$symbseed+$namechck;
                   12937: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12938: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12939: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12940: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12941: 	
1.575     albertel 12942: 	return "$num1:$num2";
                   12943:     }
                   12944: }
                   12945: 
1.675     albertel 12946: sub rndseed_64bit5 {
                   12947:     my ($symb,$courseid,$domain,$username)=@_;
                   12948:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12949:     return "$num1:$num2";
                   12950: }
                   12951: 
1.366     albertel 12952: sub rndseed_CODE_64bit {
                   12953:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12954:     {
1.366     albertel 12955: 	use integer;
1.443     albertel 12956: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12957: 	my $symbseed=numval2($symb);
1.491     albertel 12958: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12959: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12960: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12961: 	my $num1=$symbseed+$CODEchck;
                   12962: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12963: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12964: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12965: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12966: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12967: 	return "$num1:$num2";
1.366     albertel 12968:     }
                   12969: }
                   12970: 
1.575     albertel 12971: sub rndseed_CODE_64bit4 {
                   12972:     my ($symb,$courseid,$domain,$username)=@_;
                   12973:     {
                   12974: 	use integer;
                   12975: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12976: 	my $symbseed=numval3($symb);
                   12977: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12978: 	my $CODEseed=numval3(&getCODE());
                   12979: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12980: 	my $num1=$symbseed+$CODEchck;
                   12981: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12982: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12983: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12984: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12985: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12986: 	return "$num1:$num2";
                   12987:     }
                   12988: }
                   12989: 
1.675     albertel 12990: sub rndseed_CODE_64bit5 {
                   12991:     my ($symb,$courseid,$domain,$username)=@_;
                   12992:     my $code = &getCODE();
                   12993:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12994:     return "$num1:$num2";
                   12995: }
                   12996: 
1.366     albertel 12997: sub setup_random_from_rndseed {
                   12998:     my ($rndseed)=@_;
1.503     albertel 12999:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  13000:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   13001:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   13002:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13003:         } else {
                   13004:             &Math::Random::random_set_seed($num1,$num2);
                   13005:         }
1.366     albertel 13006:     } else {
                   13007: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13008:     }
1.36      albertel 13009: }
                   13010: 
1.474     albertel 13011: sub latest_receipt_algorithm_id {
1.835     albertel 13012:     return 'receipt3';
1.474     albertel 13013: }
                   13014: 
1.480     www      13015: sub recunique {
                   13016:     my $fucourseid=shift;
                   13017:     my $unique;
1.835     albertel 13018:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13019: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13020: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13021:     } else {
                   13022: 	$unique=$perlvar{'lonReceipt'};
                   13023:     }
                   13024:     return unpack("%32C*",$unique);
                   13025: }
                   13026: 
                   13027: sub recprefix {
                   13028:     my $fucourseid=shift;
                   13029:     my $prefix;
1.835     albertel 13030:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13031: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13032: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13033:     } else {
                   13034: 	$prefix=$perlvar{'lonHostID'};
                   13035:     }
                   13036:     return unpack("%32C*",$prefix);
                   13037: }
                   13038: 
1.76      www      13039: sub ireceipt {
1.474     albertel 13040:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13041: 
                   13042:     my $return =&recprefix($fucourseid).'-';
                   13043: 
                   13044:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13045: 	$env{'request.state'} eq 'construct') {
                   13046: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13047: 	return $return;
                   13048:     }
                   13049: 
1.76      www      13050:     my $cuname=unpack("%32C*",$funame);
                   13051:     my $cudom=unpack("%32C*",$fudom);
                   13052:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13053:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13054:     my $cunique=&recunique($fucourseid);
1.474     albertel 13055:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13056:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13057: 
1.790     albertel 13058: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13059: 			       
                   13060: 	$return.= ($cunique%$cuname+
                   13061: 		   $cunique%$cudom+
                   13062: 		   $cusymb%$cuname+
                   13063: 		   $cusymb%$cudom+
                   13064: 		   $cucourseid%$cuname+
                   13065: 		   $cucourseid%$cudom+
                   13066: 		   $cpart%$cuname+
                   13067: 		   $cpart%$cudom);
                   13068:     } else {
                   13069: 	$return.= ($cunique%$cuname+
                   13070: 		   $cunique%$cudom+
                   13071: 		   $cusymb%$cuname+
                   13072: 		   $cusymb%$cudom+
                   13073: 		   $cucourseid%$cuname+
                   13074: 		   $cucourseid%$cudom);
                   13075:     }
                   13076:     return $return;
1.76      www      13077: }
                   13078: 
                   13079: sub receipt {
1.474     albertel 13080:     my ($part)=@_;
1.790     albertel 13081:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13082:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13083: }
1.260     ng       13084: 
1.790     albertel 13085: sub whichuser {
                   13086:     my ($passedsymb)=@_;
                   13087:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13088:     if (defined($env{'form.grade_symb'})) {
                   13089: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13090: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13091: 	if (!$allowed &&
                   13092: 	    exists($env{'request.course.sec'}) &&
                   13093: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13094: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13095: 			      '/'.$env{'request.course.sec'});
                   13096: 	}
                   13097: 	if ($allowed) {
                   13098: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13099: 	    $courseid=$tmp_courseid;
                   13100: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13101: 	    ($name)=&get_env_multiple('form.grade_username');
                   13102: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13103: 	}
                   13104:     }
                   13105:     if (!$passedsymb) {
                   13106: 	$symb=&symbread();
                   13107:     } else {
                   13108: 	$symb=$passedsymb;
                   13109:     }
                   13110:     $courseid=$env{'request.course.id'};
                   13111:     $domain=$env{'user.domain'};
                   13112:     $name=$env{'user.name'};
                   13113:     if ($name eq 'public' && $domain eq 'public') {
                   13114: 	if (!defined($env{'form.username'})) {
                   13115: 	    $env{'form.username'}.=time.rand(10000000);
                   13116: 	}
                   13117: 	$name.=$env{'form.username'};
                   13118:     }
                   13119:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13120: 
                   13121: }
                   13122: 
1.36      albertel 13123: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13124: # returns either the contents of the file or 
                   13125: # -1 if the file doesn't exist
1.481     raeburn  13126: #
                   13127: # if the target is a file that was uploaded via DOCS, 
                   13128: # a check will be made to see if a current copy exists on the local server,
                   13129: # if it does this will be served, otherwise a copy will be retrieved from
                   13130: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13131: # the local server.   
1.472     albertel 13132: 
1.36      albertel 13133: sub getfile {
1.538     albertel 13134:     my ($file) = @_;
1.609     banghart 13135:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13136:     &repcopy($file);
                   13137:     return &readfile($file);
                   13138: }
                   13139: 
                   13140: sub repcopy_userfile {
                   13141:     my ($file)=@_;
1.1142    raeburn  13142:     my $londocroot = $perlvar{'lonDocRoot'};
                   13143:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13144:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13145:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13146: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13147:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13148:     if (-e "$file") {
1.828     www      13149: # we already have a local copy, check it out
1.538     albertel 13150: 	my @fileinfo = stat($file);
1.828     www      13151: 	my $rtncode;
                   13152: 	my $info;
1.538     albertel 13153: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13154: 	if ($lwpresp ne 'ok') {
1.828     www      13155: # there is no such file anymore, even though we had a local copy
1.482     albertel 13156: 	    if ($rtncode eq '404') {
1.538     albertel 13157: 		unlink($file);
1.482     albertel 13158: 	    }
                   13159: 	    return -1;
                   13160: 	}
                   13161: 	if ($info < $fileinfo[9]) {
1.828     www      13162: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13163: 	    return 'ok';
1.828     www      13164: 	} else {
                   13165: # the file is outdated, get rid of it
                   13166: 	    unlink($file);
1.482     albertel 13167: 	}
1.828     www      13168:     }
                   13169: # one way or the other, at this point, we don't have the file
                   13170: # construct the correct path for the file
                   13171:     my @parts = ($cdom,$cnum); 
                   13172:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13173: 	push @parts, split(/\//,$1);
                   13174:     }
                   13175:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13176:     foreach my $part (@parts) {
                   13177: 	$path .= '/'.$part;
                   13178: 	if (!-e $path) {
                   13179: 	    mkdir($path,0770);
1.482     albertel 13180: 	}
                   13181:     }
1.828     www      13182: # now the path exists for sure
                   13183: # get a user agent
                   13184:     my $transferfile=$file.'.in.transfer';
                   13185: # FIXME: this should flock
                   13186:     if (-e $transferfile) { return 'ok'; }
                   13187:     my $request;
                   13188:     $uri=~s/^\///;
1.980     raeburn  13189:     my $homeserver = &homeserver($cnum,$cdom);
                   13190:     my $protocol = $protocol{$homeserver};
                   13191:     $protocol = 'http' if ($protocol ne 'https');
                   13192:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13193:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13194: # did it work?
                   13195:     if ($response->is_error()) {
                   13196: 	unlink($transferfile);
                   13197: 	&logthis("Userfile repcopy failed for $uri");
                   13198: 	return -1;
                   13199:     }
                   13200: # worked, rename the transfer file
                   13201:     rename($transferfile,$file);
1.607     raeburn  13202:     return 'ok';
1.481     raeburn  13203: }
                   13204: 
1.517     albertel 13205: sub tokenwrapper {
                   13206:     my $uri=shift;
1.980     raeburn  13207:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13208:     $uri=~s|^/||;
1.620     albertel 13209:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13210:     my $token=$1;
1.552     albertel 13211:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13212:     if ($udom && $uname && $file) {
                   13213: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13214:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13215:         my $homeserver = &homeserver($uname,$udom);
                   13216:         my $protocol = $protocol{$homeserver};
                   13217:         $protocol = 'http' if ($protocol ne 'https');
                   13218:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13219:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13220:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13221:     } else {
                   13222:         return '/adm/notfound.html';
                   13223:     }
                   13224: }
                   13225: 
1.828     www      13226: # call with reqtype HEAD: get last modification time
                   13227: # call with reqtype GET: get the file contents
                   13228: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13229: #
1.481     raeburn  13230: sub getuploaded {
                   13231:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13232:     $uri=~s/^\///;
1.980     raeburn  13233:     my $homeserver = &homeserver($cnum,$cdom);
                   13234:     my $protocol = $protocol{$homeserver};
                   13235:     $protocol = 'http' if ($protocol ne 'https');
                   13236:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13237:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13238:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13239:     $$rtncode = $response->code;
1.482     albertel 13240:     if (! $response->is_success()) {
                   13241: 	return 'failed';
                   13242:     }      
                   13243:     if ($reqtype eq 'HEAD') {
1.486     www      13244: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13245:     } elsif ($reqtype eq 'GET') {
                   13246: 	$$info = $response->content;
1.472     albertel 13247:     }
1.482     albertel 13248:     return 'ok';
1.36      albertel 13249: }
                   13250: 
1.481     raeburn  13251: sub readfile {
                   13252:     my $file = shift;
                   13253:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13254:     my $fh;
1.1359    raeburn  13255:     open($fh,"<",$file);
1.481     raeburn  13256:     my $a='';
1.800     albertel 13257:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13258:     return $a;
                   13259: }
                   13260: 
1.36      albertel 13261: sub filelocation {
1.590     banghart 13262:     my ($dir,$file) = @_;
                   13263:     my $location;
                   13264:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13265: 
                   13266:     if ($file =~ m-^/adm/-) {
                   13267: 	$file=~s-^/adm/wrapper/-/-;
                   13268: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13269:     }
1.882     albertel 13270: 
1.1139    www      13271:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13272:         $location = $file;
1.609     banghart 13273:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13274:         my ($udom,$uname,$filename)=
1.811     albertel 13275:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13276:         my $home=&homeserver($uname,$udom);
                   13277:         my $is_me=0;
                   13278:         my @ids=&current_machine_ids();
                   13279:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13280:         if ($is_me) {
1.1117    foxr     13281:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13282:         } else {
                   13283:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13284:   	      $udom.'/'.$uname.'/'.$filename;
                   13285:         }
1.882     albertel 13286:     } elsif ($file =~ m-^/adm/-) {
                   13287: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13288:     } else {
                   13289:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13290:         $file=~s:^/(res|priv)/:/:;
                   13291:         my $space=$1;
1.590     banghart 13292:         if ( !( $file =~ m:^/:) ) {
                   13293:             $location = $dir. '/'.$file;
                   13294:         } else {
1.1142    raeburn  13295:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13296:         }
1.59      albertel 13297:     }
1.590     banghart 13298:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13299:     while ($location=~m{/\.\./}) {
                   13300: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13301: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13302: 	} else {
                   13303: 	    $location=~ s{/\.\./}{/}g;
                   13304: 	}
                   13305:     } #remove dir/..
1.590     banghart 13306:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13307:     return $location;
1.46      www      13308: }
1.36      albertel 13309: 
1.46      www      13310: sub hreflocation {
                   13311:     my ($dir,$file)=@_;
1.980     raeburn  13312:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13313: 	$file=filelocation($dir,$file);
1.700     albertel 13314:     } elsif ($file=~m-^/adm/-) {
                   13315: 	$file=~s-^/adm/wrapper/-/-;
                   13316: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13317:     }
                   13318:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13319: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13320:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13321: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13322: 	        {/uploaded/$1/$2/}x;
1.46      www      13323:     }
1.913     albertel 13324:     if ($file=~ m{^/userfiles/}) {
                   13325: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13326:     }
1.462     albertel 13327:     return $file;
1.465     albertel 13328: }
                   13329: 
1.1139    www      13330: 
                   13331: 
                   13332: 
                   13333: 
1.465     albertel 13334: sub current_machine_domains {
1.853     albertel 13335:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13336: }
                   13337: 
                   13338: sub machine_domains {
                   13339:     my ($hostname) = @_;
1.465     albertel 13340:     my @domains;
1.838     albertel 13341:     my %hostname = &all_hostnames();
1.465     albertel 13342:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13343: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13344: 	if ($hostname eq $name) {
1.844     albertel 13345: 	    push(@domains,&host_domain($id));
1.465     albertel 13346: 	}
                   13347:     }
                   13348:     return @domains;
                   13349: }
                   13350: 
                   13351: sub current_machine_ids {
1.853     albertel 13352:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13353: }
                   13354: 
                   13355: sub machine_ids {
                   13356:     my ($hostname) = @_;
                   13357:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13358:     my @ids;
1.888     albertel 13359:     my %name_to_host = &all_names();
1.889     albertel 13360:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13361: 	return @{ $name_to_host{$hostname} };
                   13362:     }
                   13363:     return;
1.31      www      13364: }
                   13365: 
1.824     raeburn  13366: sub additional_machine_domains {
                   13367:     my @domains;
1.1359    raeburn  13368:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13369:     while( my $line = <$fh>) {
                   13370:         $line =~ s/\s//g;
                   13371:         push(@domains,$line);
                   13372:     }
                   13373:     return @domains;
                   13374: }
                   13375: 
                   13376: sub default_login_domain {
                   13377:     my $domain = $perlvar{'lonDefDomain'};
                   13378:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13379:     foreach my $posdom (&current_machine_domains(),
                   13380:                         &additional_machine_domains()) {
                   13381:         if (lc($posdom) eq lc($testdomain)) {
                   13382:             $domain=$posdom;
                   13383:             last;
                   13384:         }
                   13385:     }
                   13386:     return $domain;
                   13387: }
                   13388: 
1.31      www      13389: # ------------------------------------------------------------- Declutters URLs
                   13390: 
                   13391: sub declutter {
                   13392:     my $thisfn=shift;
1.569     albertel 13393:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13394:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13395:         $thisfn=~s{^/home/httpd/html}{};
                   13396:     }
1.31      www      13397:     $thisfn=~s/^\///;
1.697     albertel 13398:     $thisfn=~s|^adm/wrapper/||;
                   13399:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13400:     $thisfn=~s/^res\///;
1.1172    bisitz   13401:     $thisfn=~s/^priv\///;
1.1032    raeburn  13402:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13403:         $thisfn=~s/\?.+$//;
                   13404:     }
1.268     www      13405:     return $thisfn;
                   13406: }
                   13407: 
                   13408: # ------------------------------------------------------------- Clutter up URLs
                   13409: 
                   13410: sub clutter {
                   13411:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13412:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13413: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13414:        $thisfn='/res'.$thisfn; 
                   13415:     }
1.1031    raeburn  13416:     if ($thisfn !~m|^/adm|) {
                   13417: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13418: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13419: 	} else {
                   13420: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13421: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13422: 	    if ($embstyle eq 'ssi'
                   13423: 		|| ($embstyle eq 'hdn')
                   13424: 		|| ($embstyle eq 'rat')
                   13425: 		|| ($embstyle eq 'prv')
                   13426: 		|| ($embstyle eq 'ign')) {
                   13427: 		#do nothing with these
                   13428: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13429: 		|| ($embstyle eq 'emb')
                   13430: 		|| ($embstyle eq 'wrp')) {
                   13431: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13432: 	    } elsif ($embstyle eq 'unk'
                   13433: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13434: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13435: 	    } else {
1.718     www      13436: #		&logthis("Got a blank emb style");
1.695     albertel 13437: 	    }
1.694     albertel 13438: 	}
1.1343    raeburn  13439:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13440:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13441:     }
1.31      www      13442:     return $thisfn;
1.12      www      13443: }
                   13444: 
1.787     albertel 13445: sub clutter_with_no_wrapper {
                   13446:     my $uri = &clutter(shift);
                   13447:     if ($uri =~ m-^/adm/-) {
                   13448: 	$uri =~ s-^/adm/wrapper/-/-;
                   13449: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13450:     }
                   13451:     return $uri;
                   13452: }
                   13453: 
1.557     albertel 13454: sub freeze_escape {
                   13455:     my ($value)=@_;
                   13456:     if (ref($value)) {
                   13457: 	$value=&nfreeze($value);
                   13458: 	return '__FROZEN__'.&escape($value);
                   13459:     }
                   13460:     return &escape($value);
                   13461: }
                   13462: 
1.11      www      13463: 
1.557     albertel 13464: sub thaw_unescape {
                   13465:     my ($value)=@_;
                   13466:     if ($value =~ /^__FROZEN__/) {
                   13467: 	substr($value,0,10,undef);
                   13468: 	$value=&unescape($value);
                   13469: 	return &thaw($value);
                   13470:     }
                   13471:     return &unescape($value);
                   13472: }
                   13473: 
1.436     albertel 13474: sub correct_line_ends {
                   13475:     my ($result)=@_;
                   13476:     $$result =~s/\r\n/\n/mg;
                   13477:     $$result =~s/\r/\n/mg;
1.415     albertel 13478: }
1.1       albertel 13479: # ================================================================ Main Program
                   13480: 
1.184     www      13481: sub goodbye {
1.204     albertel 13482:    &logthis("Starting Shut down");
1.443     albertel 13483: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13484:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13485: #converted
1.599     albertel 13486: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13487:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13488: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13489: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13490: #1.1 only
1.870     albertel 13491: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13492: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13493: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13494: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13495:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13496:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13497:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13498:    &flushcourselogs();
                   13499:    &logthis("Shutting down");
                   13500: }
                   13501: 
1.852     albertel 13502: sub get_dns {
1.1210    raeburn  13503:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13504:     if (!$ignore_cache) {
                   13505: 	my ($content,$cached)=
                   13506: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13507: 	if ($cached) {
1.1210    raeburn  13508: 	    &$func($content,$hashref);
1.869     albertel 13509: 	    return;
                   13510: 	}
                   13511:     }
                   13512: 
                   13513:     my %alldns;
1.1359    raeburn  13514:     open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13515:     foreach my $dns (<$config>) {
                   13516: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13517:         my $line = $1;
                   13518:         my ($host,$protocol) = split(/:/,$line);
                   13519:         if ($protocol ne 'https') {
                   13520:             $protocol = 'http';
                   13521:         }
                   13522: 	$alldns{$host} = $protocol;
1.869     albertel 13523:     }
                   13524:     while (%alldns) {
1.1263    raeburn  13525: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13526: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13527:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13528:         delete($alldns{$dns});
1.852     albertel 13529: 	next if ($response->is_error());
                   13530: 	my @content = split("\n",$response->content);
1.1210    raeburn  13531: 	unless ($nocache) {
1.1219    raeburn  13532: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13533: 	}
                   13534: 	&$func(\@content,$hashref);
1.869     albertel 13535: 	return;
1.852     albertel 13536:     }
                   13537:     close($config);
1.871     albertel 13538:     my $which = (split('/',$url))[3];
                   13539:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1359    raeburn  13540:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13541:     my @content = <$config>;
1.1210    raeburn  13542:     &$func(\@content,$hashref);
                   13543:     return;
                   13544: }
                   13545: 
                   13546: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13547: sub parse_dns_checksums_tab {
1.1210    raeburn  13548:     my ($lines,$hashref) = @_;
1.1264    raeburn  13549:     my $lonhost = $perlvar{'lonHostID'};
                   13550:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13551:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13552:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13553:     my $webconfdir = '/etc/httpd/conf';
                   13554:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13555:         $webconfdir = '/etc/apache2';
                   13556:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13557:         if ($1 >= 10) {
                   13558:             $webconfdir = '/etc/apache2';
                   13559:         }
                   13560:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13561:         if ($1 >= 10.0) {
                   13562:             $webconfdir = '/etc/apache2';
                   13563:         }
                   13564:     }
1.1210    raeburn  13565:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13566:     my (%chksum,%revnum);
                   13567:     if (ref($lines) eq 'ARRAY') {
                   13568:         chomp(@{$lines});
1.1238    raeburn  13569:         my $version = shift(@{$lines});
                   13570:         if ($version eq $release) {  
1.1210    raeburn  13571:             foreach my $line (@{$lines}) {
1.1238    raeburn  13572:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13573:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13574:                     if ($webconfdir eq '/etc/apache2') {
                   13575:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13576:                     }
                   13577:                 }
1.1238    raeburn  13578:                 $chksum{$file} = $shasum;
                   13579:                 $revnum{$file} = $version;
1.1210    raeburn  13580:             }
                   13581:             if (ref($hashref) eq 'HASH') {
                   13582:                 %{$hashref} = (
                   13583:                                 sums     => \%chksum,
                   13584:                                 versions => \%revnum,
                   13585:                               );
                   13586:             }
                   13587:         }
                   13588:     }
1.869     albertel 13589:     return;
1.852     albertel 13590: }
1.1210    raeburn  13591: 
                   13592: sub fetch_dns_checksums {
1.1238    raeburn  13593:     my %checksums;
                   13594:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13595:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13596:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13597:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13598:              \%checksums);
1.1210    raeburn  13599:     return \%checksums;
                   13600: }
                   13601: 
1.327     albertel 13602: # ------------------------------------------------------------ Read domain file
                   13603: {
1.852     albertel 13604:     my $loaded;
1.846     albertel 13605:     my %domain;
                   13606: 
1.852     albertel 13607:     sub parse_domain_tab {
                   13608: 	my ($lines) = @_;
                   13609: 	foreach my $line (@$lines) {
                   13610: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13611: 
1.846     albertel 13612: 	    chomp($line);
1.852     albertel 13613: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13614: 	    my %this_domain;
                   13615: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13616: 			       'lang_def', 'city', 'longi', 'lati',
                   13617: 			       'primary') {
                   13618: 		$this_domain{$field} = shift(@elements);
                   13619: 	    }
                   13620: 	    $domain{$name} = \%this_domain;
1.852     albertel 13621: 	}
                   13622:     }
1.864     albertel 13623: 
                   13624:     sub reset_domain_info {
                   13625: 	undef($loaded);
                   13626: 	undef(%domain);
                   13627:     }
                   13628: 
1.852     albertel 13629:     sub load_domain_tab {
1.1293    raeburn  13630: 	my ($ignore_cache,$nocache) = @_;
                   13631: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13632: 	my $fh;
1.1359    raeburn  13633: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13634: 	    my @lines = <$fh>;
                   13635: 	    &parse_domain_tab(\@lines);
1.448     albertel 13636: 	}
1.852     albertel 13637: 	close($fh);
                   13638: 	$loaded = 1;
1.327     albertel 13639:     }
1.846     albertel 13640: 
                   13641:     sub domain {
1.852     albertel 13642: 	&load_domain_tab() if (!$loaded);
                   13643: 
1.846     albertel 13644: 	my ($name,$what) = @_;
                   13645: 	return if ( !exists($domain{$name}) );
                   13646: 
                   13647: 	if (!$what) {
                   13648: 	    return $domain{$name}{'description'};
                   13649: 	}
                   13650: 	return $domain{$name}{$what};
                   13651:     }
1.974     raeburn  13652: 
                   13653:     sub domain_info {
                   13654:         &load_domain_tab() if (!$loaded);
                   13655:         return %domain;
                   13656:     }
                   13657: 
1.327     albertel 13658: }
                   13659: 
                   13660: 
1.1       albertel 13661: # ------------------------------------------------------------- Read hosts file
                   13662: {
1.838     albertel 13663:     my %hostname;
1.844     albertel 13664:     my %hostdom;
1.845     albertel 13665:     my %libserv;
1.852     albertel 13666:     my $loaded;
1.888     albertel 13667:     my %name_to_host;
1.1074    raeburn  13668:     my %internetdom;
1.1107    raeburn  13669:     my %LC_dns_serv;
1.852     albertel 13670: 
                   13671:     sub parse_hosts_tab {
                   13672: 	my ($file) = @_;
                   13673: 	foreach my $configline (@$file) {
                   13674: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13675:             chomp($configline);
                   13676: 	    if ($configline =~ /^\^/) {
                   13677:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13678:                     $LC_dns_serv{$1} = 1;
                   13679:                 }
                   13680:                 next;
                   13681:             }
1.1074    raeburn  13682: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13683: 	    $name=~s/\s//g;
                   13684: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13685:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13686:                     my $curr = $hostname{$id};
                   13687:                     my $skip;
                   13688:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13689:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13690:                             $skip = 1;
                   13691:                         } else {
                   13692:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13693:                         }
                   13694:                     }
                   13695:                     unless ($skip) {
                   13696:                         push(@{$name_to_host{$name}},$id);
                   13697:                     }
                   13698:                 } else {
                   13699:                     push(@{$name_to_host{$name}},$id);
                   13700:                 }
1.852     albertel 13701: 		$hostname{$id}=$name;
                   13702: 		$hostdom{$id}=$domain;
                   13703: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13704:                 if (defined($protocol)) {
                   13705:                     if ($protocol eq 'https') {
                   13706:                         $protocol{$id} = $protocol;
                   13707:                     } else {
                   13708:                         $protocol{$id} = 'http'; 
                   13709:                     }
1.968     raeburn  13710:                 } else {
1.969     raeburn  13711:                     $protocol{$id} = 'http';
1.968     raeburn  13712:                 }
1.1074    raeburn  13713:                 if (defined($intdom)) {
                   13714:                     $internetdom{$id} = $intdom;
                   13715:                 }
1.852     albertel 13716: 	    }
                   13717: 	}
                   13718:     }
1.864     albertel 13719:     
                   13720:     sub reset_hosts_info {
1.897     albertel 13721: 	&purge_remembered();
1.864     albertel 13722: 	&reset_domain_info();
                   13723: 	&reset_hosts_ip_info();
1.1339    raeburn  13724:         undef(%internetdom);
1.892     albertel 13725: 	undef(%name_to_host);
1.864     albertel 13726: 	undef(%hostname);
                   13727: 	undef(%hostdom);
                   13728: 	undef(%libserv);
                   13729: 	undef($loaded);
                   13730:     }
1.1       albertel 13731: 
1.852     albertel 13732:     sub load_hosts_tab {
1.1293    raeburn  13733: 	my ($ignore_cache,$nocache) = @_;
                   13734: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13735: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13736: 	my @config = <$config>;
                   13737: 	&parse_hosts_tab(\@config);
                   13738: 	close($config);
                   13739: 	$loaded=1;
1.1       albertel 13740:     }
1.852     albertel 13741: 
1.838     albertel 13742:     sub hostname {
1.852     albertel 13743: 	&load_hosts_tab() if (!$loaded);
                   13744: 
1.838     albertel 13745: 	my ($lonid) = @_;
                   13746: 	return $hostname{$lonid};
                   13747:     }
1.845     albertel 13748: 
1.838     albertel 13749:     sub all_hostnames {
1.852     albertel 13750: 	&load_hosts_tab() if (!$loaded);
                   13751: 
1.838     albertel 13752: 	return %hostname;
                   13753:     }
1.845     albertel 13754: 
1.888     albertel 13755:     sub all_names {
1.1293    raeburn  13756:         my ($ignore_cache,$nocache) = @_;
                   13757: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13758: 
                   13759: 	return %name_to_host;
                   13760:     }
                   13761: 
1.974     raeburn  13762:     sub all_host_domain {
                   13763:         &load_hosts_tab() if (!$loaded);
                   13764:         return %hostdom;
                   13765:     }
                   13766: 
1.1339    raeburn  13767:     sub all_host_intdom {
                   13768:         &load_hosts_tab() if (!$loaded);
                   13769:         return %internetdom;
                   13770:     }
                   13771: 
1.845     albertel 13772:     sub is_library {
1.852     albertel 13773: 	&load_hosts_tab() if (!$loaded);
                   13774: 
1.845     albertel 13775: 	return exists($libserv{$_[0]});
                   13776:     }
                   13777: 
                   13778:     sub all_library {
1.852     albertel 13779: 	&load_hosts_tab() if (!$loaded);
                   13780: 
1.845     albertel 13781: 	return %libserv;
                   13782:     }
                   13783: 
1.1062    droeschl 13784:     sub unique_library {
                   13785: 	#2x reverse removes all hostnames that appear more than once
                   13786:         my %unique = reverse &all_library();
                   13787:         return reverse %unique;
                   13788:     }
                   13789: 
1.841     albertel 13790:     sub get_servers {
1.852     albertel 13791: 	&load_hosts_tab() if (!$loaded);
                   13792: 
1.841     albertel 13793: 	my ($domain,$type) = @_;
                   13794: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13795: 	                                          : %hostname;
                   13796: 	my %result;
1.842     albertel 13797: 	if (ref($domain) eq 'ARRAY') {
                   13798: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13799: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13800: 		    $result{$host} = $hostname;
                   13801: 		}
                   13802: 	    }
                   13803: 	} else {
                   13804: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13805: 		if ($hostdom{$host} eq $domain) {
                   13806: 		    $result{$host} = $hostname;
                   13807: 		}
1.841     albertel 13808: 	    }
                   13809: 	}
                   13810: 	return %result;
                   13811:     }
1.845     albertel 13812: 
1.1062    droeschl 13813:     sub get_unique_servers {
                   13814:         my %unique = reverse &get_servers(@_);
                   13815: 	return reverse %unique;
                   13816:     }
                   13817: 
1.844     albertel 13818:     sub host_domain {
1.852     albertel 13819: 	&load_hosts_tab() if (!$loaded);
                   13820: 
1.844     albertel 13821: 	my ($lonid) = @_;
                   13822: 	return $hostdom{$lonid};
                   13823:     }
                   13824: 
1.841     albertel 13825:     sub all_domains {
1.852     albertel 13826: 	&load_hosts_tab() if (!$loaded);
                   13827: 
1.841     albertel 13828: 	my %seen;
                   13829: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13830: 	return @uniq;
                   13831:     }
1.1074    raeburn  13832: 
                   13833:     sub internet_dom {
                   13834:         &load_hosts_tab() if (!$loaded);
                   13835: 
                   13836:         my ($lonid) = @_;
                   13837:         return $internetdom{$lonid};
                   13838:     }
1.1107    raeburn  13839: 
                   13840:     sub is_LC_dns {
                   13841:         &load_hosts_tab() if (!$loaded);
                   13842: 
                   13843:         my ($hostname) = @_;
                   13844:         return exists($LC_dns_serv{$hostname});
                   13845:     }
                   13846: 
1.1       albertel 13847: }
                   13848: 
1.847     albertel 13849: { 
                   13850:     my %iphost;
1.856     albertel 13851:     my %name_to_ip;
                   13852:     my %lonid_to_ip;
1.869     albertel 13853: 
1.847     albertel 13854:     sub get_hosts_from_ip {
                   13855: 	my ($ip) = @_;
                   13856: 	my %iphosts = &get_iphost();
                   13857: 	if (ref($iphosts{$ip})) {
                   13858: 	    return @{$iphosts{$ip}};
                   13859: 	}
                   13860: 	return;
1.839     albertel 13861:     }
1.864     albertel 13862:     
                   13863:     sub reset_hosts_ip_info {
                   13864: 	undef(%iphost);
                   13865: 	undef(%name_to_ip);
                   13866: 	undef(%lonid_to_ip);
                   13867:     }
1.856     albertel 13868: 
                   13869:     sub get_host_ip {
                   13870: 	my ($lonid) = @_;
                   13871: 	if (exists($lonid_to_ip{$lonid})) {
                   13872: 	    return $lonid_to_ip{$lonid};
                   13873: 	}
                   13874: 	my $name=&hostname($lonid);
                   13875:    	my $ip = gethostbyname($name);
                   13876: 	return if (!$ip || length($ip) ne 4);
                   13877: 	$ip=inet_ntoa($ip);
                   13878: 	$name_to_ip{$name}   = $ip;
                   13879: 	$lonid_to_ip{$lonid} = $ip;
                   13880: 	return $ip;
                   13881:     }
1.847     albertel 13882:     
                   13883:     sub get_iphost {
1.1293    raeburn  13884: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13885: 
1.869     albertel 13886: 	if (!$ignore_cache) {
                   13887: 	    if (%iphost) {
                   13888: 		return %iphost;
                   13889: 	    }
                   13890: 	    my ($ip_info,$cached)=
                   13891: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13892: 	    if ($cached) {
                   13893: 		%iphost      = %{$ip_info->[0]};
                   13894: 		%name_to_ip  = %{$ip_info->[1]};
                   13895: 		%lonid_to_ip = %{$ip_info->[2]};
                   13896: 		return %iphost;
                   13897: 	    }
                   13898: 	}
1.894     albertel 13899: 
                   13900: 	# get yesterday's info for fallback
                   13901: 	my %old_name_to_ip;
                   13902: 	my ($ip_info,$cached)=
                   13903: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13904: 	if ($cached) {
                   13905: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13906: 	}
                   13907: 
1.1293    raeburn  13908: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13909: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13910: 	    my $ip;
                   13911: 	    if (!exists($name_to_ip{$name})) {
                   13912: 		$ip = gethostbyname($name);
                   13913: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13914: 		    if (defined($old_name_to_ip{$name})) {
                   13915: 			$ip = $old_name_to_ip{$name};
                   13916: 			&logthis("Can't find $name defaulting to old $ip");
                   13917: 		    } else {
                   13918: 			&logthis("Name $name no IP found");
                   13919: 			next;
                   13920: 		    }
                   13921: 		} else {
                   13922: 		    $ip=inet_ntoa($ip);
1.847     albertel 13923: 		}
                   13924: 		$name_to_ip{$name} = $ip;
                   13925: 	    } else {
                   13926: 		$ip = $name_to_ip{$name};
1.653     albertel 13927: 	    }
1.888     albertel 13928: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13929: 		$lonid_to_ip{$id} = $ip;
                   13930: 	    }
                   13931: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13932: 	}
1.1293    raeburn  13933:         unless ($nocache) {
                   13934: 	    &do_cache_new('iphost','iphost',
                   13935: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13936: 		          48*60*60);
                   13937:         }
1.869     albertel 13938: 
1.847     albertel 13939: 	return %iphost;
1.598     albertel 13940:     }
                   13941: 
1.992     raeburn  13942:     #
                   13943:     #  Given a DNS returns the loncapa host name for that DNS 
                   13944:     # 
                   13945:     sub host_from_dns {
                   13946:         my ($dns) = @_;
                   13947:         my @hosts;
                   13948:         my $ip;
                   13949: 
1.993     raeburn  13950:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13951:             $ip = $name_to_ip{$dns};
                   13952:         }
                   13953:         if (!$ip) {
                   13954:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13955:             if (length($ip) == 4) { 
                   13956: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13957:             }
                   13958:         }
                   13959:         if ($ip) {
                   13960: 	    @hosts = get_hosts_from_ip($ip);
                   13961: 	    return $hosts[0];
                   13962:         }
                   13963:         return undef;
1.986     foxr     13964:     }
1.992     raeburn  13965: 
1.1074    raeburn  13966:     sub get_internet_names {
                   13967:         my ($lonid) = @_;
                   13968:         return if ($lonid eq '');
                   13969:         my ($idnref,$cached)=
                   13970:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13971:         if ($cached) {
                   13972:             return $idnref;
                   13973:         }
                   13974:         my $ip = &get_host_ip($lonid);
                   13975:         my @hosts = &get_hosts_from_ip($ip);
                   13976:         my %iphost = &get_iphost();
                   13977:         my (@idns,%seen);
                   13978:         foreach my $id (@hosts) {
                   13979:             my $dom = &host_domain($id);
                   13980:             my $prim_id = &domain($dom,'primary');
                   13981:             my $prim_ip = &get_host_ip($prim_id);
                   13982:             next if ($seen{$prim_ip});
                   13983:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13984:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13985:                     my $intdom = &internet_dom($id);
                   13986:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13987:                         push(@idns,$intdom);
                   13988:                     }
                   13989:                 }
                   13990:             }
                   13991:             $seen{$prim_ip} = 1;
                   13992:         }
1.1219    raeburn  13993:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13994:     }
                   13995: 
1.986     foxr     13996: }
                   13997: 
1.1079    raeburn  13998: sub all_loncaparevs {
1.1249    raeburn  13999:     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  14000: }
                   14001: 
1.1227    raeburn  14002: # ---------------------------------------------------------- Read loncaparev table
                   14003: {
                   14004:     sub load_loncaparevs { 
                   14005:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14006:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14007:                 while (my $configline=<$config>) {
                   14008:                     chomp($configline);
                   14009:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14010:                     $loncaparevs{$hostid}=$loncaparev;
                   14011:                 }
                   14012:                 close($config);
                   14013:             }
                   14014:         }
                   14015:     }
                   14016: }
                   14017: 
                   14018: # ---------------------------------------------------------- Read serverhostID table
                   14019: {
                   14020:     sub load_serverhomeIDs {
                   14021:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14022:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14023:                 while (my $configline=<$config>) {
                   14024:                     chomp($configline);
                   14025:                     my ($name,$id)=split(/:/,$configline);
                   14026:                     $serverhomeIDs{$name}=$id;
                   14027:                 }
                   14028:                 close($config);
                   14029:             }
                   14030:         }
                   14031:     }
                   14032: }
                   14033: 
                   14034: 
1.862     albertel 14035: BEGIN {
                   14036: 
                   14037: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14038:     unless ($readit) {
                   14039: {
                   14040:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14041:     %perlvar = (%perlvar,%{$configvars});
                   14042: }
                   14043: 
                   14044: 
1.1       albertel 14045: # ------------------------------------------------------ Read spare server file
                   14046: {
1.1359    raeburn  14047:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14048: 
                   14049:     while (my $configline=<$config>) {
                   14050:        chomp($configline);
1.284     matthew  14051:        if ($configline) {
1.784     albertel 14052: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14053: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14054: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14055:        }
                   14056:     }
1.448     albertel 14057:     close($config);
1.1       albertel 14058: }
1.11      www      14059: # ------------------------------------------------------------ Read permissions
                   14060: {
1.1359    raeburn  14061:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14062: 
                   14063:     while (my $configline=<$config>) {
1.448     albertel 14064: 	chomp($configline);
                   14065: 	if ($configline) {
                   14066: 	    my ($role,$perm)=split(/ /,$configline);
                   14067: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14068: 	}
1.11      www      14069:     }
1.448     albertel 14070:     close($config);
1.11      www      14071: }
                   14072: 
                   14073: # -------------------------------------------- Read plain texts for permissions
                   14074: {
1.1359    raeburn  14075:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14076: 
                   14077:     while (my $configline=<$config>) {
1.448     albertel 14078: 	chomp($configline);
                   14079: 	if ($configline) {
1.742     raeburn  14080: 	    my ($short,@plain)=split(/:/,$configline);
                   14081:             %{$prp{$short}} = ();
                   14082: 	    if (@plain > 0) {
                   14083:                 $prp{$short}{'std'} = $plain[0];
                   14084:                 for (my $i=1; $i<@plain; $i++) {
                   14085:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14086:                 }
                   14087:             }
1.448     albertel 14088: 	}
1.135     www      14089:     }
1.448     albertel 14090:     close($config);
1.135     www      14091: }
                   14092: 
                   14093: # ---------------------------------------------------------- Read package table
                   14094: {
1.1359    raeburn  14095:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14096: 
                   14097:     while (my $configline=<$config>) {
1.483     albertel 14098: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14099: 	chomp($configline);
                   14100: 	my ($short,$plain)=split(/:/,$configline);
                   14101: 	my ($pack,$name)=split(/\&/,$short);
                   14102: 	if ($plain ne '') {
                   14103: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14104: 	    $packagetab{$short}=$plain; 
                   14105: 	}
1.11      www      14106:     }
1.448     albertel 14107:     close($config);
1.329     matthew  14108: }
                   14109: 
1.1073    raeburn  14110: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14111: 
                   14112: &load_loncaparevs();
1.1073    raeburn  14113: 
1.1074    raeburn  14114: # ---------------------------------------------------------- Read serverhostID table
                   14115: 
1.1227    raeburn  14116: &load_serverhomeIDs();
                   14117: 
                   14118: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14119: {
                   14120:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14121:     if (-e $file) {
                   14122:         my $parser = HTML::LCParser->new($file);
                   14123:         while (my $token = $parser->get_token()) {
                   14124:             if ($token->[0] eq 'S') {
                   14125:                 my $item = $token->[1];
                   14126:                 my $name = $token->[2]{'name'};
                   14127:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14128:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14129:                 my $namematch = $token->[2]{'namematch'};
                   14130:                 if ($item eq 'parameter') {
                   14131:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14132:                         my $release = $parser->get_text();
                   14133:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14134:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14135:                     }
                   14136:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14137:                     my $release = $parser->get_text();
                   14138:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14139:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14140:                 }
                   14141:             }
                   14142:         }
                   14143:     }
1.1073    raeburn  14144: }
                   14145: 
1.1138    raeburn  14146: # ---------------------------------------------------------- Read managers table
                   14147: {
                   14148:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14149:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14150:             while (my $configline=<$config>) {
                   14151:                 chomp($configline);
                   14152:                 next if ($configline =~ /^\#/);
                   14153:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14154:                     $managerstab{$configline} = 1;
                   14155:                 }
                   14156:             }
                   14157:             close($config);
                   14158:         }
                   14159:     }
                   14160: }
                   14161: 
1.329     matthew  14162: # ------------- set up temporary directory
                   14163: {
1.1117    foxr     14164:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14165: 
1.11      www      14166: }
                   14167: 
1.794     albertel 14168: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14169: 				'compress_threshold'=> 20_000,
                   14170:  			        });
1.185     www      14171: 
1.281     www      14172: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14173: $dumpcount=0;
1.958     www      14174: $locknum=0;
1.22      www      14175: 
1.163     harris41 14176: &logtouch();
1.672     albertel 14177: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14178: $readit=1;
1.564     albertel 14179:     {
                   14180: 	use integer;
                   14181: 	my $test=(2**32)+1;
1.568     albertel 14182: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14183: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14184:     }
1.195     www      14185: }
1.1       albertel 14186: }
1.179     www      14187: 
1.1       albertel 14188: 1;
1.191     harris41 14189: __END__
                   14190: 
1.243     albertel 14191: =pod
                   14192: 
1.191     harris41 14193: =head1 NAME
                   14194: 
1.243     albertel 14195: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14196: 
                   14197: =head1 SYNOPSIS
                   14198: 
1.243     albertel 14199: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14200: 
                   14201:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14202: 
1.243     albertel 14203: Common parameters:
                   14204: 
                   14205: =over 4
                   14206: 
                   14207: =item *
                   14208: 
                   14209: $uname : an internal username (if $cname expecting a course Id specifically)
                   14210: 
                   14211: =item *
                   14212: 
                   14213: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14214: 
                   14215: =item *
                   14216: 
                   14217: $symb : a resource instance identifier
                   14218: 
                   14219: =item *
                   14220: 
                   14221: $namespace : the name of a .db file that contains the data needed or
                   14222: being set.
                   14223: 
                   14224: =back
                   14225: 
1.394     bowersj2 14226: =head1 OVERVIEW
1.191     harris41 14227: 
1.394     bowersj2 14228: lonnet provides subroutines which interact with the
                   14229: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14230: about classes, users, and resources.
1.243     albertel 14231: 
                   14232: For many of these objects you can also use this to store data about
                   14233: them or modify them in various ways.
1.191     harris41 14234: 
1.394     bowersj2 14235: =head2 Symbs
1.191     harris41 14236: 
1.394     bowersj2 14237: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14238: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14239: map, the resource number of the resource in the map, and the URL of
                   14240: the resource itself. The latter is somewhat redundant, but might help
                   14241: if maps change.
                   14242: 
                   14243: An example is
                   14244: 
                   14245:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14246: 
                   14247: The respective map entry is
                   14248: 
                   14249:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14250:   title="Problem 2">
                   14251:  </resource>
                   14252: 
                   14253: Symbs are used by the random number generator, as well as to store and
                   14254: restore data specific to a certain instance of for example a problem.
                   14255: 
                   14256: =head2 Storing And Retrieving Data
                   14257: 
                   14258: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14259: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14260: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14261: is is the non-critical message twin of cstore. These functions are for
                   14262: handlers to store a perl hash to a user's permanent data space in an
                   14263: easy manner, and to retrieve it again on another call. It is expected
                   14264: that a handler would use this once at the beginning to retrieve data,
                   14265: and then again once at the end to send only the new data back.
                   14266: 
                   14267: The data is stored in the user's data directory on the user's
                   14268: homeserver under the ID of the course.
                   14269: 
                   14270: The hash that is returned by restore will have all of the previous
                   14271: value for all of the elements of the hash.
                   14272: 
                   14273: Example:
                   14274: 
                   14275:  #creating a hash
                   14276:  my %hash;
                   14277:  $hash{'foo'}='bar';
                   14278: 
                   14279:  #storing it
                   14280:  &Apache::lonnet::cstore(\%hash);
                   14281: 
                   14282:  #changing a value
                   14283:  $hash{'foo'}='notbar';
                   14284: 
                   14285:  #adding a new value
                   14286:  $hash{'bar'}='foo';
                   14287:  &Apache::lonnet::cstore(\%hash);
                   14288: 
                   14289:  #retrieving the hash
                   14290:  my %history=&Apache::lonnet::restore();
                   14291: 
                   14292:  #print the hash
                   14293:  foreach my $key (sort(keys(%history))) {
                   14294:    print("\%history{$key} = $history{$key}");
                   14295:  }
                   14296: 
                   14297: Will print out:
1.191     harris41 14298: 
1.394     bowersj2 14299:  %history{1:foo} = bar
                   14300:  %history{1:keys} = foo:timestamp
                   14301:  %history{1:timestamp} = 990455579
                   14302:  %history{2:bar} = foo
                   14303:  %history{2:foo} = notbar
                   14304:  %history{2:keys} = foo:bar:timestamp
                   14305:  %history{2:timestamp} = 990455580
                   14306:  %history{bar} = foo
                   14307:  %history{foo} = notbar
                   14308:  %history{timestamp} = 990455580
                   14309:  %history{version} = 2
                   14310: 
                   14311: Note that the special hash entries C<keys>, C<version> and
                   14312: C<timestamp> were added to the hash. C<version> will be equal to the
                   14313: total number of versions of the data that have been stored. The
                   14314: C<timestamp> attribute will be the UNIX time the hash was
                   14315: stored. C<keys> is available in every historical section to list which
                   14316: keys were added or changed at a specific historical revision of a
                   14317: hash.
                   14318: 
                   14319: B<Warning>: do not store the hash that restore returns directly. This
                   14320: will cause a mess since it will restore the historical keys as if the
                   14321: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14322: 
1.394     bowersj2 14323: Calling convention:
1.191     harris41 14324: 
1.1225    raeburn  14325:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14326:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14327: 
1.394     bowersj2 14328: For more detailed information, see lonnet specific documentation.
1.191     harris41 14329: 
1.394     bowersj2 14330: =head1 RETURN MESSAGES
1.191     harris41 14331: 
1.394     bowersj2 14332: =over 4
1.191     harris41 14333: 
1.394     bowersj2 14334: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14335: 
1.394     bowersj2 14336: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14337: when the connection is brought back up
1.191     harris41 14338: 
1.394     bowersj2 14339: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14340: for later delivery
1.191     harris41 14341: 
1.967     bisitz   14342: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14343: 
1.394     bowersj2 14344: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14345: that was requested
1.191     harris41 14346: 
1.243     albertel 14347: =back
1.191     harris41 14348: 
1.243     albertel 14349: =head1 PUBLIC SUBROUTINES
1.191     harris41 14350: 
1.243     albertel 14351: =head2 Session Environment Functions
1.191     harris41 14352: 
1.243     albertel 14353: =over 4
1.191     harris41 14354: 
1.394     bowersj2 14355: =item * 
                   14356: X<appenv()>
1.949     raeburn  14357: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14358: the user envirnoment file, and will be restored for each access this
1.620     albertel 14359: user makes during this session, also modifies the %env for the current
1.949     raeburn  14360: process. Optional rolesarrayref - if defined contains a reference to an array
                   14361: of roles which are exempt from the restriction on modifying user.role entries 
                   14362: in the user's environment.db and in %env.    
1.191     harris41 14363: 
                   14364: =item *
1.394     bowersj2 14365: X<delenv()>
1.987     raeburn  14366: B<delenv($delthis,$regexp)>: removes all items from the session
                   14367: environment file that begin with $delthis. If the 
                   14368: optional second arg - $regexp - is true, $delthis is treated as a 
                   14369: regular expression, otherwise \Q$delthis\E is used. 
                   14370: The values are also deleted from the current processes %env.
1.191     harris41 14371: 
1.795     albertel 14372: =item * get_env_multiple($name) 
                   14373: 
                   14374: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14375: values may be defined and end up as an array ref.
                   14376: 
                   14377: returns an array of values
                   14378: 
1.243     albertel 14379: =back
                   14380: 
                   14381: =head2 User Information
1.191     harris41 14382: 
1.243     albertel 14383: =over 4
1.191     harris41 14384: 
                   14385: =item *
1.394     bowersj2 14386: X<queryauthenticate()>
                   14387: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14388: authentication scheme
                   14389: 
                   14390: =item *
1.394     bowersj2 14391: X<authenticate()>
1.1073    raeburn  14392: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14393: authenticate user from domain's lib servers (first use the current
                   14394: one). C<$upass> should be the users password.
1.1073    raeburn  14395: $checkdefauth is optional (value is 1 if a check should be made to
                   14396:    authenticate user using default authentication method, and allow
                   14397:    account creation if username does not have account in the domain).
                   14398: $clientcancheckhost is optional (value is 1 if checking whether the
                   14399:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14400: 
                   14401: =item *
1.394     bowersj2 14402: X<homeserver()>
                   14403: B<homeserver($uname,$udom)>: find the server which has
                   14404: the user's directory and files (there must be only one), this caches
                   14405: the answer, and also caches if there is a borken connection.
1.191     harris41 14406: 
                   14407: =item *
1.394     bowersj2 14408: X<idget()>
1.1300    raeburn  14409: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14410: a list of student/employee IDs or clicker IDs
                   14411: (student/employee IDs are a unique resource in a domain, there must be 
                   14412: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14413: clickerIDs are not necessarily unique, as students might share clickers.
                   14414: (returns hash: id=>name,id=>name)
1.191     harris41 14415: 
                   14416: =item *
1.394     bowersj2 14417: X<idrget()>
                   14418: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14419: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14420: 
                   14421: =item *
1.394     bowersj2 14422: X<idput()>
1.1300    raeburn  14423: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14424: names and associated student/employee IDs or clicker IDs.
                   14425: 
                   14426: =item *
                   14427: X<iddel()>
                   14428: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14429: student/employee ID or clicker ID username look-ups from domain.
                   14430: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14431: If no $uhome is provided, it will be determined usig &homeserver()
                   14432: for each user.  If no $namespace is provided, the default is ids.
                   14433: 
                   14434: =item *
                   14435: X<updateclickers()>
                   14436: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14437: clicker ID-to-username look-ups in clickers.db on library server.
                   14438: Permitted actions are add or del (i.e., add or delete). The 
                   14439: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14440: value is an escaped comma-separated list of usernames (for whom the
                   14441: library server is the homeserver), who registered that particular ID.
                   14442: If $critical is true, the update will be sent via &critical, otherwise
                   14443: &reply() will be used.
1.191     harris41 14444: 
                   14445: =item *
1.394     bowersj2 14446: X<rolesinit()>
1.1169    droeschl 14447: B<rolesinit($udom,$username)>: get user privileges.
                   14448: returns user role, first access and timer interval hashes
1.243     albertel 14449: 
                   14450: =item *
1.1171    droeschl 14451: X<privileged()>
                   14452: B<privileged($username,$domain)>: returns a true if user has a
                   14453: privileged and active role (i.e. su or dc), false otherwise.
                   14454: 
                   14455: =item *
1.551     albertel 14456: X<getsection()>
                   14457: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14458: course $cname, return section name/number or '' for "not in course"
                   14459: and '-1' for "no section"
                   14460: 
                   14461: =item *
1.394     bowersj2 14462: X<userenvironment()>
                   14463: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14464: passed in @what from the requested user's environment, returns a hash
                   14465: 
1.858     raeburn  14466: =item * 
                   14467: X<userlog_query()>
1.859     albertel 14468: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14469: activity.log file. %filters defines filters applied when parsing the
                   14470: log file. These can be start or end timestamps, or the type of action
                   14471: - log to look for Login or Logout events, check for Checkin or
                   14472: Checkout, role for role selection. The response is in the form
                   14473: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14474: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14475: 
1.243     albertel 14476: =back
                   14477: 
                   14478: =head2 User Roles
                   14479: 
                   14480: =over 4
                   14481: 
                   14482: =item *
                   14483: 
1.1284    raeburn  14484: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14485: returns codes for allowed actions.
                   14486: 
                   14487: The first argument is required, all others are optional.
                   14488: 
                   14489: $priv is the privilege being checked.
                   14490: $uri contains additional information about what is being checked for access (e.g.,
                   14491: URL, course ID etc.). 
                   14492: $symb is the unique resource instance identifier in a course; if needed,
                   14493: but not provided, it will be retrieved via a call to &symbread(). 
                   14494: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14495: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14496: files).
                   14497: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14498: prevents recursive calls to &allowed.
                   14499: 
1.243     albertel 14500:  F: full access
                   14501:  U,I,K: authentication modes (cxx only)
                   14502:  '': forbidden
                   14503:  1: user needs to choose course
                   14504:  2: browse allowed
1.766     albertel 14505:  A: passphrase authentication needed
1.1284    raeburn  14506:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14507: 
                   14508: =item *
                   14509: 
1.1192    raeburn  14510: constructaccess($url,$setpriv) : check for access to construction space URL
                   14511: 
                   14512: See if the owner domain and name in the URL match those in the
                   14513: expected environment.  If so, return three element list
                   14514: ($ownername,$ownerdomain,$ownerhome).
                   14515: 
                   14516: Otherwise return the null string.
                   14517: 
                   14518: If second argument 'setpriv' is true, it assigns the privileges,
                   14519: and returns the same three element list, unless the owner has
                   14520: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14521: in which case the null string is returned.
                   14522: 
                   14523: =item *
                   14524: 
1.1326    raeburn  14525: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14526: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14527: for system, domain, and course level. $uname and $udom are optional (current
                   14528: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14529: 
                   14530: =item *
                   14531: 
1.988     raeburn  14532: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14533: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14534: $type is Course (default) or Community.
1.988     raeburn  14535: If $forcedefault evaluates to true, text returned will be default 
                   14536: text for $type. Otherwise, if this is a course, the text returned 
                   14537: will be a custom name for the role (if defined in the course's 
                   14538: environment).  If no custom name is defined the default is returned.
                   14539:    
1.832     raeburn  14540: =item *
                   14541: 
1.1219    raeburn  14542: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14543: All arguments are optional. Returns a hash of a roles, either for
                   14544: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14545: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14546: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14547: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14548: For each key, value is set to colon-separated start and end times for
                   14549: the role.  If no username and domain are specified, will default to
1.934     raeburn  14550: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14551: of role statuses (active, future or previous), roles 
                   14552: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14553: to restrict the list of roles reported. If no array ref is 
                   14554: provided for types, will default to return only active roles.
1.834     albertel 14555: 
1.1195    raeburn  14556: =item *
                   14557: 
                   14558: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14559: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14560: 
                   14561: Additional optional arguments are: $type (if role checking is to be restricted 
                   14562: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14563: available roles) or future (roles available in the future), and
                   14564: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14565: have active Domain Coordinator role in course's domain or in additional
                   14566: domains (specified in 'Domains to check for privileged users' in course
                   14567: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14568: 
                   14569: =item *
                   14570: 
                   14571: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14572: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14573: $possdomains and $possroles are optional array refs -- to domains to check and
                   14574: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14575: users' roles.db to check for a dc or su role in any domain. This can be
                   14576: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14577: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14578: this then allows &privileged_by_domain() to be used, which caches the identity
                   14579: of privileged users, eliminating the need for repeated calls to &dump().
                   14580: 
                   14581: =item *
                   14582: 
                   14583: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14584: where the outer hash keys are domains specified in the $possdomains array ref,
                   14585: next inner hash keys are privileged roles specified in the $roles array ref,
                   14586: and the innermost hash contains key = value pairs for username:domain = end:start
                   14587: for active or future "privileged" users with that role in that domain. To avoid
                   14588: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14589: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14590: 
1.243     albertel 14591: =back
                   14592: 
                   14593: =head2 User Modification
                   14594: 
                   14595: =over 4
                   14596: 
                   14597: =item *
                   14598: 
1.957     raeburn  14599: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14600: user for the level given by URL.  Optional start and end dates (leave empty
                   14601: string or zero for "no date")
1.191     harris41 14602: 
                   14603: =item *
                   14604: 
1.243     albertel 14605: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14606: change a users, password, possible return values are: ok,
                   14607: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14608: refused
1.191     harris41 14609: 
                   14610: =item *
                   14611: 
1.243     albertel 14612: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14613: 
                   14614: =item *
                   14615: 
1.1058    raeburn  14616: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14617:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14618: 
                   14619: will update user information (firstname,middlename,lastname,generation,
                   14620: permanentemail), and if forceid is true, student/employee ID also.
                   14621: A user's institutional affiliation(s) can also be updated.
                   14622: User information fields will not be overwritten with empty entries 
                   14623: unless the field is included in the $candelete array reference.
                   14624: This array is included when a single user is modified via "Manage Users",
                   14625: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14626: 
                   14627: =item *
                   14628: 
1.286     matthew  14629: modifystudent
                   14630: 
1.957     raeburn  14631: modify a student's enrollment and identification information.
1.1235    raeburn  14632: The course id is resolved based on the current user's environment.  
                   14633: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14634: associated with a course.
                   14635: 
1.297     matthew  14636: This call is essentially a wrapper for lonnet::modifyuser and
                   14637: lonnet::modify_student_enrollment
1.286     matthew  14638: 
                   14639: Inputs: 
                   14640: 
                   14641: =over 4
                   14642: 
1.957     raeburn  14643: =item B<$udom> Student's loncapa domain
1.286     matthew  14644: 
1.957     raeburn  14645: =item B<$uname> Student's loncapa login name
1.286     matthew  14646: 
1.964     bisitz   14647: =item B<$uid> Student/Employee ID
1.286     matthew  14648: 
1.957     raeburn  14649: =item B<$umode> Student's authentication mode
1.286     matthew  14650: 
1.957     raeburn  14651: =item B<$upass> Student's password
1.286     matthew  14652: 
1.957     raeburn  14653: =item B<$first> Student's first name
1.286     matthew  14654: 
1.957     raeburn  14655: =item B<$middle> Student's middle name
1.286     matthew  14656: 
1.957     raeburn  14657: =item B<$last> Student's last name
1.286     matthew  14658: 
1.957     raeburn  14659: =item B<$gene> Student's generation
1.286     matthew  14660: 
1.957     raeburn  14661: =item B<$usec> Student's section in course
1.286     matthew  14662: 
                   14663: =item B<$end> Unix time of the roles expiration
                   14664: 
                   14665: =item B<$start> Unix time of the roles start date
                   14666: 
                   14667: =item B<$forceid> If defined, allow $uid to be changed
                   14668: 
                   14669: =item B<$desiredhome> server to use as home server for student
                   14670: 
1.957     raeburn  14671: =item B<$email> Student's permanent e-mail address
                   14672: 
                   14673: =item B<$type> Type of enrollment (auto or manual)
                   14674: 
1.963     raeburn  14675: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14676: 
                   14677: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14678: 
1.963     raeburn  14679: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14680: 
1.963     raeburn  14681: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14682: 
1.1216    raeburn  14683: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14684: 
                   14685: =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  14686: 
1.286     matthew  14687: =back
1.297     matthew  14688: 
                   14689: =item *
                   14690: 
                   14691: modify_student_enrollment
                   14692: 
1.1235    raeburn  14693: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14694: 'role.request.course' must be defined for this function to proceed.
                   14695: 
                   14696: Inputs:
                   14697: 
                   14698: =over 4
                   14699: 
1.1235    raeburn  14700: =item $udom, student's domain
1.297     matthew  14701: 
1.1235    raeburn  14702: =item $uname, student's name
1.297     matthew  14703: 
1.1235    raeburn  14704: =item $uid, student's user id
1.297     matthew  14705: 
1.1235    raeburn  14706: =item $first, student's first name
1.297     matthew  14707: 
                   14708: =item $middle
                   14709: 
                   14710: =item $last
                   14711: 
                   14712: =item $gene
                   14713: 
                   14714: =item $usec
                   14715: 
                   14716: =item $end
                   14717: 
                   14718: =item $start
                   14719: 
1.957     raeburn  14720: =item $type
                   14721: 
                   14722: =item $locktype
                   14723: 
                   14724: =item $cid
                   14725: 
                   14726: =item $selfenroll
                   14727: 
                   14728: =item $context
                   14729: 
1.1216    raeburn  14730: =item $credits, number of credits student will earn from this class
                   14731: 
1.1314    raeburn  14732: =item $instsec, institutional course section code for student
                   14733: 
1.297     matthew  14734: =back
                   14735: 
1.191     harris41 14736: 
                   14737: =item *
                   14738: 
1.243     albertel 14739: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14740: custom role; give a custom role to a user for the level given by URL.  Specify
                   14741: name and domain of role author, and role name
1.191     harris41 14742: 
                   14743: =item *
                   14744: 
1.243     albertel 14745: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14746: 
                   14747: =item *
                   14748: 
1.243     albertel 14749: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14750: 
                   14751: =back
                   14752: 
                   14753: =head2 Course Infomation
                   14754: 
                   14755: =over 4
1.191     harris41 14756: 
                   14757: =item *
                   14758: 
1.1118    foxr     14759: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14760: specified course id, including all environment settings for the
                   14761: course, the description of the course will be in the hash under the
                   14762: key 'description'
1.191     harris41 14763: 
1.1118    foxr     14764: $options is an optional parameter that if supplied is a hash reference that controls
                   14765: what how this function works.  It has the following key/values:
                   14766: 
                   14767: =over 4
                   14768: 
                   14769: =item freshen_cache
                   14770: 
                   14771: If defined, and the environment cache for the course is valid, it is 
                   14772: returned in the returned hash.
                   14773: 
                   14774: =item one_time
                   14775: 
                   14776: If defined, the last cache time is set to _now_
                   14777: 
                   14778: =item user
                   14779: 
                   14780: If defined, the supplied username is used instead of the current user.
                   14781: 
                   14782: 
                   14783: =back
                   14784: 
1.191     harris41 14785: =item *
                   14786: 
1.624     albertel 14787: resdata($name,$domain,$type,@which) : request for current parameter
                   14788: setting for a specific $type, where $type is either 'course' or 'user',
                   14789: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14790: answers for 10 minutes.
1.243     albertel 14791: 
1.877     foxr     14792: =item *
                   14793: 
                   14794: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14795: data base, returning a hash that is keyed by the resource name and has
                   14796: values that are the resource value.  I believe that the timestamps and
                   14797: versions are also returned.
                   14798: 
1.1236    raeburn  14799: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14800: supplemental content area. This routine caches the number of files for 
                   14801: 10 minutes.
                   14802: 
1.243     albertel 14803: =back
                   14804: 
                   14805: =head2 Course Modification
                   14806: 
                   14807: =over 4
1.191     harris41 14808: 
                   14809: =item *
                   14810: 
1.243     albertel 14811: writecoursepref($courseid,%prefs) : write preferences (environment
                   14812: database) for a course
1.191     harris41 14813: 
                   14814: =item *
                   14815: 
1.1011    raeburn  14816: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14817: 
                   14818: =item *
                   14819: 
1.1038    raeburn  14820: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14821: 
1.1167    droeschl 14822: =item *
                   14823: 
                   14824: is_course($courseid), is_course($cdom, $cnum)
                   14825: 
                   14826: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14827: two component version $cdom, $cnum. It checks if the specified course exists.
                   14828: 
                   14829: Returns:
                   14830:     undef if the course doesn't exist, otherwise
                   14831:     in scalar context the combined courseid.
                   14832:     in list context the two components of the course identifier, domain and 
                   14833:     courseid.    
                   14834: 
1.243     albertel 14835: =back
                   14836: 
                   14837: =head2 Resource Subroutines
                   14838: 
                   14839: =over 4
1.191     harris41 14840: 
                   14841: =item *
                   14842: 
1.243     albertel 14843: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14844: 
                   14845: =item *
                   14846: 
1.243     albertel 14847: repcopy($filename) : subscribes to the requested file, and attempts to
                   14848: replicate from the owning library server, Might return
1.607     raeburn  14849: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14850: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14851: resource. Expects the local filesystem pathname
                   14852: (/home/httpd/html/res/....)
                   14853: 
                   14854: =back
                   14855: 
                   14856: =head2 Resource Information
                   14857: 
                   14858: =over 4
1.191     harris41 14859: 
                   14860: =item *
                   14861: 
1.1228    raeburn  14862: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14863: and returns the value of a variety of different possible values,
                   14864: $varname should be a request string, and the other parameters can be
                   14865: used to specify who and what one is asking about. Ordinarily, $cid 
                   14866: does not need to be specified, as it is retrived from 
                   14867: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14868: within lonuserstate::loadmap() when initializing a course, before
                   14869: $env{'request.course.id'} has been set, so it needs to be provided
                   14870: in that one case.
1.243     albertel 14871: 
                   14872: Possible values for $varname are environment.lastname (or other item
                   14873: from the envirnment hash), user.name (or someother aspect about the
                   14874: user), resource.0.maxtries (or some other part and parameter of a
                   14875: resource)
1.204     albertel 14876: 
                   14877: =item *
                   14878: 
1.243     albertel 14879: directcondval($number) : get current value of a condition; reads from a state
                   14880: string
1.204     albertel 14881: 
                   14882: =item *
                   14883: 
1.243     albertel 14884: condval($condidx) : value of condition index based on state
1.204     albertel 14885: 
                   14886: =item *
                   14887: 
1.1362    raeburn  14888: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 14889: resource's metadata, $what should be either a specific key, or either
                   14890: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  14891: packages that this resource currently uses, the last 3 arguments are 
                   14892: only used internally for recursive metadata.
                   14893: 
                   14894: the toolsymb is only used where the uri is for an external tool (for which
                   14895: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 14896: 
1.1371    raeburn  14897: this function automatically caches all requests except any made recursively
                   14898: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   14899: defined).
1.191     harris41 14900: 
                   14901: =item *
                   14902: 
1.243     albertel 14903: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14904: network of library servers; returns file handle of where SQL and regex results
                   14905: will be stored for query
1.191     harris41 14906: 
                   14907: =item *
                   14908: 
1.1282    raeburn  14909: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14910: return symbolic list entry (all arguments optional). 
                   14911: 
                   14912: Args: filename is the filename (including path) for the file for which a symb 
                   14913: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14914: to check access status if more than one resource was found in the bighash 
                   14915: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14916: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14917: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14918: cause possible symbs to be checked to determine if they are subject to content
                   14919: blocking, if so they will not be included as possible symbs; possibles is a
                   14920: ref to a hash, which, as a side effect, will be populated with all possible 
                   14921: symbs (content blocking not tested).
                   14922:  
1.243     albertel 14923: returns the data handle
1.191     harris41 14924: 
                   14925: =item *
                   14926: 
1.1190    raeburn  14927: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14928: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14929: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14930: on failure, user must be in a course, as it assumes the existence of
                   14931: the course initial hash, and uses $env('request.course.id'}.  The third
                   14932: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14933: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14934: encrypted; otherwise it will be null.  
1.191     harris41 14935: 
                   14936: =item *
                   14937: 
1.243     albertel 14938: symbclean($symb) : removes versions numbers from a symb, returns the
                   14939: cleaned symb
1.191     harris41 14940: 
                   14941: =item *
                   14942: 
1.243     albertel 14943: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14944: course map, user must be in a course for it to work.
1.191     harris41 14945: 
                   14946: =item *
                   14947: 
1.243     albertel 14948: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14949: 
                   14950: =item *
                   14951: 
1.243     albertel 14952: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14953: a random seed, all arguments are optional, if they aren't sent it uses the
                   14954: environment to derive them. Note: if symb isn't sent and it can't get one
                   14955: from &symbread it will use the current time as its return value
1.191     harris41 14956: 
                   14957: =item *
                   14958: 
1.243     albertel 14959: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14960: unfakeable, receipt
1.191     harris41 14961: 
                   14962: =item *
                   14963: 
1.620     albertel 14964: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14965: 
                   14966: =item *
                   14967: 
1.243     albertel 14968: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14969: 
                   14970: =item *
                   14971: 
1.243     albertel 14972: 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 14973: 
                   14974: =item *
                   14975: 
1.243     albertel 14976: 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 14977: 
                   14978: =item *
                   14979: 
1.243     albertel 14980: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14981: 
                   14982: =item *
                   14983: 
1.243     albertel 14984: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14985: forcing spreadsheet to reevaluate the resource scores next time.
                   14986: 
1.1195    raeburn  14987: =item * 
                   14988: 
1.1196    raeburn  14989: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14990: when viewing in course context.
1.1195    raeburn  14991: 
1.1196    raeburn  14992:  input: six args -- filename (decluttered), course number, course domain,
                   14993:                     url, symb (if registered) and group (if this is a 
                   14994:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14995: 
1.1196    raeburn  14996:  output: array of five scalars --
1.1195    raeburn  14997:          $cfile -- url for file editing if editable on current server
                   14998:          $home -- homeserver of resource (i.e., for author if published,
                   14999:                                           or course if uploaded.).
                   15000:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  15001:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   15002:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15003: 
                   15004: =item *
                   15005: 
                   15006: is_course_upload($file,$cnum,$cdom)
                   15007: 
                   15008: Used in course context to determine if current file was uploaded to 
                   15009: the course (i.e., would be found in /userfiles/docs on the course's 
                   15010: homeserver.
                   15011: 
                   15012:   input: 3 args -- filename (decluttered), course number and course domain.
                   15013:   output: boolean -- 1 if file was uploaded.
                   15014: 
1.243     albertel 15015: =back
                   15016: 
                   15017: =head2 Storing/Retreiving Data
                   15018: 
                   15019: =over 4
1.191     harris41 15020: 
                   15021: =item *
                   15022: 
1.1269    raeburn  15023: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15024: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15025: the remaining args aren't required and if they aren't passed or are '' they will
                   15026: be derived from the env (with the exception of $laststore, which is an 
                   15027: optional arg used when a user's submission is stored in grading).
                   15028: $laststore is $version=$timestamp, where $version is the most recent version
                   15029: number retrieved for the corresponding $symb in the $namespace db file, and
                   15030: $timestamp is the timestamp for that transaction (UNIX time).
                   15031: $laststore is currently only passed when cstore() is called by 
                   15032: structuretags::finalize_storage().
1.191     harris41 15033: 
                   15034: =item *
                   15035: 
1.1269    raeburn  15036: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15037: but uses critical subroutine
1.191     harris41 15038: 
                   15039: =item *
                   15040: 
1.243     albertel 15041: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15042: all args are optional
1.191     harris41 15043: 
                   15044: =item *
                   15045: 
1.717     albertel 15046: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15047: dumps the complete (or key matching regexp) namespace into a hash
                   15048: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15049: normally &store()ed into
                   15050: 
                   15051: $range should be either an integer '100' (give me the first 100
                   15052:                                            matching records)
                   15053:               or be  two integers sperated by a - with no spaces
                   15054:                  '30-50' (give me the 30th through the 50th matching
                   15055:                           records)
                   15056: 
                   15057: 
                   15058: =item *
                   15059: 
1.1269    raeburn  15060: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15061: replaces a &store() version of data with a replacement set of data
                   15062: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15063: reference. If $tolog is true, the transaction is logged in the courselog
                   15064: with an action=PUTSTORE.
1.717     albertel 15065: 
                   15066: =item *
                   15067: 
1.243     albertel 15068: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15069: works very similar to store/cstore, but all data is stored in a
                   15070: temporary location and can be reset using tmpreset, $storehash should
                   15071: be a hash reference, returns nothing on success
1.191     harris41 15072: 
                   15073: =item *
                   15074: 
1.243     albertel 15075: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15076: similar to restore, but all data is stored in a temporary location and
                   15077: can be reset using tmpreset. Returns a hash of values on success,
                   15078: error string otherwise.
1.191     harris41 15079: 
                   15080: =item *
                   15081: 
1.243     albertel 15082: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15083: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15084: 
                   15085: =item *
                   15086: 
1.243     albertel 15087: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15088: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15089: 
                   15090: =item *
                   15091: 
1.243     albertel 15092: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15093: namesp ($udom and $uname are optional)
1.191     harris41 15094: 
                   15095: =item *
                   15096: 
1.702     albertel 15097: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15098: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15099: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15100: 
1.702     albertel 15101: $range should be either an integer '100' (give me the first 100
                   15102:                                            matching records)
                   15103:               or be  two integers sperated by a - with no spaces
                   15104:                  '30-50' (give me the 30th through the 50th matching
                   15105:                           records)
1.449     matthew  15106: =item *
                   15107: 
                   15108: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15109: $store can be a scalar, an array reference, or if the amount to be 
                   15110: incremented is > 1, a hash reference.
                   15111: 
                   15112: ($udom and $uname are optional)
1.191     harris41 15113: 
                   15114: =item *
                   15115: 
1.243     albertel 15116: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15117: ($udom and $uname are optional)
1.191     harris41 15118: 
                   15119: =item *
                   15120: 
1.243     albertel 15121: cput($namespace,$storehash,$udom,$uname) : critical put
                   15122: ($udom and $uname are optional)
1.191     harris41 15123: 
                   15124: =item *
                   15125: 
1.748     albertel 15126: newput($namespace,$storehash,$udom,$uname) :
                   15127: 
                   15128: Attempts to store the items in the $storehash, but only if they don't
                   15129: currently exist, if this succeeds you can be certain that you have 
                   15130: successfully created a new key value pair in the $namespace db.
                   15131: 
                   15132: 
                   15133: Args:
                   15134:  $namespace: name of database to store values to
                   15135:  $storehash: hashref to store to the db
                   15136:  $udom: (optional) domain of user containing the db
                   15137:  $uname: (optional) name of user caontaining the db
                   15138: 
                   15139: Returns:
                   15140:  'ok' -> succeeded in storing all keys of $storehash
                   15141:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15142:                         least <key> already existed in the db (other
                   15143:                         requested keys may also already exist)
1.967     bisitz   15144:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15145:  'con_lost' -> unable to contact request server
                   15146:  'refused' -> action was not allowed by remote machine
                   15147: 
                   15148: 
                   15149: =item *
                   15150: 
1.243     albertel 15151: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15152: reference filled in from namesp (encrypts the return communication)
                   15153: ($udom and $uname are optional)
1.191     harris41 15154: 
                   15155: =item *
                   15156: 
1.243     albertel 15157: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15158: critical subroutine
                   15159: 
1.806     raeburn  15160: =item *
                   15161: 
1.860     raeburn  15162: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15163: array reference filled in from namespace found in domain level on either
                   15164: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15165: 
                   15166: =item *
                   15167: 
1.860     raeburn  15168: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15169: domain level either on specified domain server ($uhome) or primary domain 
                   15170: server ($udom and $uhome are optional)
1.806     raeburn  15171: 
1.943     raeburn  15172: =item * 
                   15173: 
1.1240    raeburn  15174: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15175: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15176: the target domain.
                   15177: 
                   15178: May also include additional key => value pairs for the following groups:
                   15179: 
                   15180: =over
                   15181: 
                   15182: =item
                   15183: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15184: 
                   15185: =over
                   15186: 
                   15187: =item defaultquota, authorquota
                   15188: 
                   15189: =back
                   15190: 
                   15191: =item
                   15192: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15193: portfolio for users).
                   15194: 
                   15195: =over
                   15196: 
                   15197: =item
                   15198: aboutme, blog, webdav, portfolio
                   15199: 
                   15200: =back
                   15201: 
                   15202: =item
                   15203: requestcourses: ability to request courses, and how requests are processed.
                   15204: 
                   15205: =over
                   15206: 
                   15207: =item
1.1305    raeburn  15208: official, unofficial, community, textbook, placement
1.1240    raeburn  15209: 
                   15210: =back
                   15211: 
                   15212: =item
                   15213: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15214: 
                   15215: =over
                   15216: 
                   15217: =item
1.1256    raeburn  15218: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15219: 
                   15220: =back
                   15221: 
                   15222: =item
                   15223: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15224: for course's uploaded content.
                   15225: 
                   15226: =over
                   15227: 
                   15228: =item
1.1246    raeburn  15229: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15230: communityquota, textbookquota, placementquota
1.1240    raeburn  15231: 
                   15232: =back
                   15233: 
                   15234: =item
                   15235: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15236: on your servers.
                   15237: 
                   15238: =over
                   15239: 
                   15240: =item 
                   15241: remotesessions, hostedsessions
                   15242: 
                   15243: =back
                   15244: 
                   15245: =back
                   15246: 
                   15247: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15248: utility to create a configuration.db file on a domain's primary library server 
                   15249: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15250: -- corresponding values are authentication type (internal, krb4, krb5,
                   15251: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15252: will be available. Values are retrieved from cache (if current), unless the
                   15253: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15254: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15255: 
                   15256: Typical usage:
1.943     raeburn  15257: 
1.1240    raeburn  15258: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15259: 
1.243     albertel 15260: =back
                   15261: 
                   15262: =head2 Network Status Functions
                   15263: 
                   15264: =over 4
1.191     harris41 15265: 
                   15266: =item *
                   15267: 
1.1137    raeburn  15268: dirlist() : return directory list based on URI (first arg).
                   15269: 
                   15270: Inputs: 1 required, 5 optional.
                   15271: 
                   15272: =over
                   15273: 
                   15274: =item 
                   15275: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15276: 
                   15277: =item
                   15278: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15279: 
                   15280: =item
                   15281: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15282: 
                   15283: =item
                   15284: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15285: 
                   15286: =item
                   15287: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15288: 
                   15289: =item 
                   15290: $alternateRoot - path to prepend in place of path from $uri.
                   15291: 
                   15292: =back
                   15293: 
                   15294: Returns: Array of up to two items.
                   15295: 
                   15296: =over
                   15297: 
                   15298: a reference to an array of files/subdirectories
                   15299: 
                   15300: =over
                   15301: 
                   15302: Each element in the array of files/subdirectories is a & separated list of
                   15303: item name and the result of running stat on the item.  If dirlist was requested
                   15304: for a file instead of a directory, the item name will be ''. For a directory 
                   15305: listing, if the item is a metadata file, the element will end &N&M 
                   15306: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15307: default copyright set (1).  
                   15308: 
                   15309: =back
                   15310: 
                   15311: a scalar containing error condition (if encountered).
                   15312: 
                   15313: =over
                   15314: 
                   15315: =item 
                   15316: no_host (no homeserver identified for $username:$domain).
                   15317: 
                   15318: =item 
                   15319: no_such_host (server contacted for listing not identified as valid host).
                   15320: 
                   15321: =item 
                   15322: con_lost (connection to remote server failed).
                   15323: 
                   15324: =item 
                   15325: refused (invalid $username:$domain received on lond side).
                   15326: 
                   15327: =item 
                   15328: no_such_dir (directory at specified path on lond side does not exist). 
                   15329: 
                   15330: =item 
                   15331: empty (directory at specified path on lond side is empty).
                   15332: 
                   15333: =over
                   15334: 
                   15335: This is currently not encountered because the &ls3, &ls2, 
                   15336: &ls (_handler) routines on the lond side do not filter out
                   15337: . and .. from a directory listing. 
                   15338: 
                   15339: =back
                   15340: 
                   15341: =back
                   15342: 
                   15343: =back
1.191     harris41 15344: 
                   15345: =item *
                   15346: 
1.243     albertel 15347: spareserver() : find server with least workload from spare.tab
                   15348: 
1.986     foxr     15349: 
                   15350: =item *
                   15351: 
                   15352: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15353: if there is no corresponding loncapa host.
                   15354: 
1.243     albertel 15355: =back
                   15356: 
1.986     foxr     15357: 
1.243     albertel 15358: =head2 Apache Request
                   15359: 
                   15360: =over 4
1.191     harris41 15361: 
                   15362: =item *
                   15363: 
1.243     albertel 15364: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15365: localhost, posts hash
                   15366: 
                   15367: =back
                   15368: 
                   15369: =head2 Data to String to Data
                   15370: 
                   15371: =over 4
1.191     harris41 15372: 
                   15373: =item *
                   15374: 
1.243     albertel 15375: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15376: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15377: 
                   15378: =item *
                   15379: 
1.243     albertel 15380: hashref2str($hashref) : convert a hashref into a string complete with
                   15381: escaping and '=' and '&' separators, supports elements that are
                   15382: arrayrefs and hashrefs
1.191     harris41 15383: 
                   15384: =item *
                   15385: 
1.243     albertel 15386: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15387: with escaping and '&' separators, supports elements that are arrayrefs
                   15388: and hashrefs
1.191     harris41 15389: 
                   15390: =item *
                   15391: 
1.243     albertel 15392: str2hash($string) : convert string to hash using unescaping and
                   15393: splitting on '=' and '&', supports elements that are arrayrefs and
                   15394: hashrefs
1.191     harris41 15395: 
                   15396: =item *
                   15397: 
1.243     albertel 15398: str2array($string) : convert string to hash using unescaping and
                   15399: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15400: 
                   15401: =back
                   15402: 
                   15403: =head2 Logging Routines
                   15404: 
                   15405: 
                   15406: These routines allow one to make log messages in the lonnet.log and
                   15407: lonnet.perm logfiles.
1.191     harris41 15408: 
1.1119    foxr     15409: =over 4
                   15410: 
1.191     harris41 15411: =item *
                   15412: 
1.243     albertel 15413: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15414: 
                   15415: =item *
                   15416: 
1.243     albertel 15417: logthis() : append message to the normal lonnet.log file, it gets
                   15418: preiodically rolled over and deleted.
1.191     harris41 15419: 
                   15420: =item *
                   15421: 
1.243     albertel 15422: logperm() : append a permanent message to lonnet.perm.log, this log
                   15423: file never gets deleted by any automated portion of the system, only
                   15424: messages of critical importance should go in here.
                   15425: 
1.1119    foxr     15426: 
1.243     albertel 15427: =back
                   15428: 
                   15429: =head2 General File Helper Routines
                   15430: 
                   15431: =over 4
1.191     harris41 15432: 
                   15433: =item *
                   15434: 
1.481     raeburn  15435: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15436: (a) files in /uploaded
                   15437:   (i) If a local copy of the file exists - 
                   15438:       compares modification date of local copy with last-modified date for 
                   15439:       definitive version stored on home server for course. If local copy is 
                   15440:       stale, requests a new version from the home server and stores it. 
                   15441:       If the original has been removed from the home server, then local copy 
                   15442:       is unlinked.
                   15443:   (ii) If local copy does not exist -
                   15444:       requests the file from the home server and stores it. 
                   15445:   
                   15446:   If $caller is 'uploadrep':  
                   15447:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15448:     for request for files originally uploaded via DOCS. 
                   15449:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15450:   
                   15451:   Otherwise:
                   15452:      This indicates a call from the content generation phase of the request.
                   15453:      -  returns the entire contents of the file or -1.
                   15454:      
                   15455: (b) files in /res
                   15456:    - returns the entire contents of a file or -1; 
                   15457:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15458: 
1.712     albertel 15459: 
                   15460: =item *
                   15461: 
                   15462: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15463:                   reference
                   15464: 
                   15465: returns either a stat() list of data about the file or an empty list
                   15466: if the file doesn't exist or couldn't find out about it (connection
                   15467: problems or user unknown)
                   15468: 
1.191     harris41 15469: =item *
                   15470: 
1.243     albertel 15471: filelocation($dir,$file) : returns file system location of a file
                   15472: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15473: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15474: and a file of ../bob will become /a/bob)
1.191     harris41 15475: 
                   15476: =item *
                   15477: 
                   15478: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15479: filelocation except for hrefs
                   15480: 
                   15481: =item *
                   15482: 
1.1261    raeburn  15483: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15484: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15485: 
1.243     albertel 15486: =back
                   15487: 
1.608     albertel 15488: =head2 Usererfile file routines (/uploaded*)
                   15489: 
                   15490: =over 4
                   15491: 
                   15492: =item *
                   15493: 
                   15494: userfileupload(): main rotine for putting a file in a user or course's
                   15495:                   filespace, arguments are,
                   15496: 
1.620     albertel 15497:  formname - required - this is the name of the element in $env where the
1.608     albertel 15498:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15499:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15500:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15501:  context - if coursedoc, store the file in the course of the active role
                   15502:              of the current user; 
                   15503:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15504:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15505:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15506:          if undefined, it will be placed in "unknown"
                   15507: 
                   15508:  (This routine calls clean_filename() to remove any dangerous
                   15509:  characters from the filename, and then calls finuserfileupload() to
                   15510:  complete the transaction)
                   15511: 
                   15512:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15513:  and /adm/notfound.html if unsuccessful
                   15514: 
                   15515: =item *
                   15516: 
                   15517: clean_filename(): routine for cleaing a filename up for storage in
                   15518:                  userfile space, argument is:
                   15519: 
                   15520:  filename - proposed filename
                   15521: 
                   15522: returns: the new clean filename
                   15523: 
                   15524: =item *
                   15525: 
1.1090    raeburn  15526: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15527: userspace, probably shouldn't be called directly
                   15528: 
                   15529:   docuname: username or courseid of destination for the file
                   15530:   docudom: domain of user/course of destination for the file
                   15531:   formname: same as for userfileupload()
1.1090    raeburn  15532:   fname: filename (including subdirectories) for the file
                   15533:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15534:   allfiles: reference to hash used to store objects found by parser
                   15535:   codebase: reference to hash used for codebases of java objects found by parser
                   15536:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15537:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15538:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15539:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15540:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15541:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15542:   mimetype: reference to scalar to accommodate mime type determined
                   15543:             from File::MMagic if $parser = parse.
1.608     albertel 15544: 
                   15545:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15546:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15547:  was 'overwrite').
                   15548:  
1.608     albertel 15549: 
                   15550: =item *
                   15551: 
                   15552: renameuserfile(): renames an existing userfile to a new name
                   15553: 
                   15554:   Args:
                   15555:    docuname: username or courseid of destination for the file
                   15556:    docudom: domain of user/course of destination for the file
                   15557:    old: current file name (including any subdirs under userfiles)
                   15558:    new: desired file name (including any subdirs under userfiles)
                   15559: 
                   15560: =item *
                   15561: 
                   15562: mkdiruserfile(): creates a directory is a userfiles dir
                   15563: 
                   15564:   Args:
                   15565:    docuname: username or courseid of destination for the file
                   15566:    docudom: domain of user/course of destination for the file
                   15567:    dir: dir to create (including any subdirs under userfiles)
                   15568: 
                   15569: =item *
                   15570: 
                   15571: removeuserfile(): removes a file that exists in userfiles
                   15572: 
                   15573:   Args:
                   15574:    docuname: username or courseid of destination for the file
                   15575:    docudom: domain of user/course of destination for the file
                   15576:    fname: filname to delete (including any subdirs under userfiles)
                   15577: 
                   15578: =item *
                   15579: 
                   15580: removeuploadedurl(): convience function for removeuserfile()
                   15581: 
                   15582:   Args:
                   15583:    url:  a full /uploaded/... url to delete
                   15584: 
1.747     albertel 15585: =item * 
                   15586: 
                   15587: get_portfile_permissions():
                   15588:   Args:
                   15589:     domain: domain of user or course contain the portfolio files
                   15590:     user: name of user or num of course contain the portfolio files
                   15591:   Returns:
                   15592:     hashref of a dump of the proper file_permissions.db
                   15593:    
                   15594: 
                   15595: =item * 
                   15596: 
                   15597: get_access_controls():
                   15598: 
                   15599: Args:
                   15600:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15601:   group: (optional) the group you want the files associated with
                   15602:   file: (optional) the file you want access info on
                   15603: 
                   15604: Returns:
1.749     raeburn  15605:     a hash (keys are file names) of hashes containing
                   15606:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15607:         values are XML containing access control settings (see below) 
1.747     albertel 15608: 
                   15609: Internal notes:
                   15610: 
1.749     raeburn  15611:  access controls are stored in file_permissions.db as key=value pairs.
                   15612:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15613:         where scope -> public,guest,course,group,domains or users.
                   15614:               end -> UNIX time for end of access (0 -> no end date)
                   15615:               start -> UNIX time for start of access
                   15616: 
                   15617:     value -> XML description of access control
                   15618:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15619:             <start></start>
                   15620:             <end></end>
                   15621: 
                   15622:             <password></password>  for scope type = guest
                   15623: 
                   15624:             <domain></domain>     for scope type = course or group
                   15625:             <number></number>
                   15626:             <roles id="">
                   15627:              <role></role>
                   15628:              <access></access>
                   15629:              <section></section>
                   15630:              <group></group>
                   15631:             </roles>
                   15632: 
                   15633:             <dom></dom>         for scope type = domains
                   15634: 
                   15635:             <users>             for scope type = users
                   15636:              <user>
                   15637:               <uname></uname>
                   15638:               <udom></udom>
                   15639:              </user>
                   15640:             </users>
                   15641:            </scope> 
                   15642:               
                   15643:  Access data is also aggregated for each file in an additional key=value pair:
                   15644:  key -> path to file/file_name\0accesscontrol 
                   15645:  value -> reference to hash
                   15646:           hash contains key = value pairs
                   15647:           where key = uniqueID:scope_end_start
                   15648:                 value = UNIX time record was last updated
                   15649: 
                   15650:           Used to improve speed of look-ups of access controls for each file.  
                   15651:  
                   15652:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15653: 
1.1198    raeburn  15654: =item *
                   15655: 
1.749     raeburn  15656: modify_access_controls():
                   15657: 
                   15658: Modifies access controls for a portfolio file
                   15659: Args
                   15660: 1. file name
                   15661: 2. reference to hash of required changes,
                   15662: 3. domain
                   15663: 4. username
                   15664:   where domain,username are the domain of the portfolio owner 
                   15665:   (either a user or a course) 
                   15666: 
                   15667: Returns:
                   15668: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15669: 2. result of deletions ('ok' or 'error', with error message).
                   15670: 3. reference to hash of any new or updated access controls.
                   15671: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15672:    key = integer (inbound ID)
1.1198    raeburn  15673:    value = uniqueID
                   15674: 
                   15675: =item *
                   15676: 
                   15677: get_timebased_id():
                   15678: 
                   15679: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15680: course via the Course Editor (e.g., folders, composite pages, 
                   15681: group bulletin boards).
                   15682: 
                   15683: Args: (first three required; six others optional)
                   15684: 
                   15685: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15686:    docssequence, or name of group
                   15687: 
                   15688: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15689:    e.g., num, boardids
                   15690: 
                   15691: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15692:    file will be named nohist_namespace.db
                   15693: 
                   15694: 4. cdom: domain of course; default is current course domain from %env
                   15695: 
                   15696: 5. cnum: course number; default is current course number from %env
                   15697: 
                   15698: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15699:    unix timestamp to form the suffix, if the plain timestamp is already
                   15700:    in use.  Default is to not do this, but simply increment the unix 
                   15701:    timestamp by 1 until a unique key is obtained.
                   15702: 
                   15703: 7. who: holder of locking key; defaults to user:domain for user.
                   15704: 
                   15705: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15706:    retrying); default is 3.
                   15707: 
                   15708: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15709: 
                   15710: Returns:
                   15711: 
                   15712: 1. suffix obtained (numeric)
                   15713: 
                   15714: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15715: 
                   15716: 3. error: contains (localized) error message if an error occurred.
                   15717: 
1.747     albertel 15718: 
1.608     albertel 15719: =back
                   15720: 
1.243     albertel 15721: =head2 HTTP Helper Routines
                   15722: 
                   15723: =over 4
                   15724: 
1.191     harris41 15725: =item *
                   15726: 
                   15727: escape() : unpack non-word characters into CGI-compatible hex codes
                   15728: 
                   15729: =item *
                   15730: 
                   15731: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15732: 
1.243     albertel 15733: =back
                   15734: 
                   15735: =head1 PRIVATE SUBROUTINES
                   15736: 
                   15737: =head2 Underlying communication routines (Shouldn't call)
                   15738: 
                   15739: =over 4
                   15740: 
                   15741: =item *
                   15742: 
                   15743: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15744: 
                   15745: =item *
                   15746: 
                   15747: reply() : uses subreply to send a message to remote machine, logs all failures
                   15748: 
                   15749: =item *
                   15750: 
                   15751: critical() : passes a critical message to another server; if cannot
                   15752: get through then place message in connection buffer directory and
                   15753: returns con_delayed, if incapable of saving message, returns
                   15754: con_failed
                   15755: 
                   15756: =item *
                   15757: 
                   15758: reconlonc() : tries to reconnect lonc client processes.
                   15759: 
                   15760: =back
                   15761: 
                   15762: =head2 Resource Access Logging
                   15763: 
                   15764: =over 4
                   15765: 
                   15766: =item *
                   15767: 
                   15768: flushcourselogs() : flush (save) buffer logs and access logs
                   15769: 
                   15770: =item *
                   15771: 
                   15772: courselog($what) : save message for course in hash
                   15773: 
                   15774: =item *
                   15775: 
                   15776: courseacclog($what) : save message for course using &courselog().  Perform
                   15777: special processing for specific resource types (problems, exams, quizzes, etc).
                   15778: 
1.191     harris41 15779: =item *
                   15780: 
                   15781: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15782: as a PerlChildExitHandler
1.243     albertel 15783: 
                   15784: =back
                   15785: 
                   15786: =head2 Other
                   15787: 
                   15788: =over 4
                   15789: 
                   15790: =item *
                   15791: 
                   15792: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15793: 
                   15794: =back
                   15795: 
                   15796: =cut
1.877     foxr     15797: 

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