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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1375  ! raeburn     4: # $Id: lonnet.pm,v 1.1374 2018/04/02 18:23:57 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:         }
                    765:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    766:         if ($opened
                    767: 	    && &timed_flock($env_file,LOCK_EX)
                    768: 	    &&
                    769: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    770: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    771: 	    while (my ($key,$value) = each(%{$newenv})) {
                    772: 	        $disk_env{$key} = $value;
                    773: 	    }
                    774: 	    untie(%disk_env);
1.35      www       775:         }
1.191     harris41  776:     }
1.56      www       777:     return 'ok';
                    778: }
                    779: # ----------------------------------------------------- Delete from Environment
                    780: 
                    781: sub delenv {
1.1104    raeburn   782:     my ($delthis,$regexp,$roles) = @_;
                    783:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    784:         my $refused = 1;
                    785:         if (ref($roles) eq 'ARRAY') {
                    786:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    787:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    788:                 $refused = 0;
                    789:             }
                    790:         }
                    791:         if ($refused) {
                    792:             &logthis("<font color=\"blue\">WARNING: ".
                    793:                      "Attempt to delete from environment ".$delthis);
                    794:             return 'error';
                    795:         }
1.56      www       796:     }
1.917     albertel  797:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    798:     if ($opened
1.915     albertel  799: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  800: 	&&
                    801: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    802: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  803: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   804: 	    if ($regexp) {
                    805:                 if ($key=~/^$delthis/) {
                    806:                     delete($env{$key});
                    807:                     delete($disk_env{$key});
                    808:                 } 
                    809:             } else {
                    810:                 if ($key=~/^\Q$delthis\E/) {
                    811: 		    delete($env{$key});
                    812: 		    delete($disk_env{$key});
                    813: 	        }
                    814:             }
1.448     albertel  815: 	}
1.783     albertel  816: 	untie(%disk_env);
1.5       www       817:     }
                    818:     return 'ok';
1.369     albertel  819: }
                    820: 
1.790     albertel  821: sub get_env_multiple {
                    822:     my ($name) = @_;
                    823:     my @values;
                    824:     if (defined($env{$name})) {
                    825:         # exists is it an array
                    826:         if (ref($env{$name})) {
                    827:             @values=@{ $env{$name} };
                    828:         } else {
                    829:             $values[0]=$env{$name};
                    830:         }
                    831:     }
                    832:     return(@values);
                    833: }
                    834: 
1.958     www       835: # ------------------------------------------------------------------- Locking
                    836: 
                    837: sub set_lock {
                    838:     my ($text)=@_;
                    839:     $locknum++;
                    840:     my $id=$$.'-'.$locknum;
                    841:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    842:              'session.lock.'.$id => $text});
                    843:     return $id;
                    844: }
                    845: 
                    846: sub get_locks {
                    847:     my $num=0;
                    848:     my %texts=();
                    849:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    850:        if ($lock=~/\w/) {
                    851:           $num++;
                    852:           $texts{$lock}=$env{'session.lock.'.$lock};
                    853:        }
                    854:    }
                    855:    return ($num,%texts);
                    856: }
                    857: 
                    858: sub remove_lock {
                    859:     my ($id)=@_;
                    860:     my $newlocks='';
                    861:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    862:        if (($lock=~/\w/) && ($lock ne $id)) {
                    863:           $newlocks.=','.$lock;
                    864:        }
                    865:     }
                    866:     &appenv({'session.locks' => $newlocks});
                    867:     &delenv('session.lock.'.$id);
                    868: }
                    869: 
                    870: sub remove_all_locks {
                    871:     my $activelocks=$env{'session.locks'};
                    872:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    873:        if ($lock=~/\w/) {
                    874:           &remove_lock($lock);
                    875:        }
                    876:     }
                    877: }
                    878: 
                    879: 
1.369     albertel  880: # ------------------------------------------ Find out current server userload
                    881: sub userload {
                    882:     my $numusers=0;
                    883:     {
                    884: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    885: 	my $filename;
                    886: 	my $curtime=time;
                    887: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  888: 	    next if ($filename eq '.' || $filename eq '..');
                    889: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  890: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  891: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  892: 	}
                    893: 	closedir(LONIDS);
                    894:     }
                    895:     my $userloadpercent=0;
                    896:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    897:     if ($maxuserload) {
1.371     albertel  898: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  899:     }
1.372     albertel  900:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  901:     return $userloadpercent;
1.283     www       902: }
                    903: 
1.1       albertel  904: # ------------------------------ Find server with least workload from spare.tab
1.11      www       905: 
1.1       albertel  906: sub spareserver {
1.1083    raeburn   907:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  908:     my $spare_server;
1.370     albertel  909:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  910:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    911:                                                      :  $userloadpercent;
1.1083    raeburn   912:     my ($uint_dom,$remotesessions);
                    913:     if (($udom ne '') && (&domain($udom) ne '')) {
                    914:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    915:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    916:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    917:         $remotesessions = $udomdefaults{'remotesessions'};
                    918:     }
1.1123    raeburn   919:     my $spareshash = &this_host_spares($udom);
                    920:     if (ref($spareshash) eq 'HASH') {
                    921:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    922:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
1.1279    raeburn   923:                 next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    924:                                              $try_server));
1.1123    raeburn   925: 	        ($spare_server, $lowest_load) =
                    926: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    927:             }
1.1083    raeburn   928:         }
1.784     albertel  929: 
1.1123    raeburn   930:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    931: 
                    932:         if (!$found_server) {
                    933:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    934: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
1.1279    raeburn   935:                     next unless (&spare_can_host($udom,$uint_dom,
                    936:                                                  $remotesessions,$try_server));
1.1123    raeburn   937: 	            ($spare_server, $lowest_load) =
                    938: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    939:                 }
                    940: 	    }
                    941:         }
1.784     albertel  942:     }
                    943: 
                    944:     if (!$want_server_name) {
1.968     raeburn   945:         my $protocol = 'http';
                    946:         if ($protocol{$spare_server} eq 'https') {
                    947:             $protocol = $protocol{$spare_server};
                    948:         }
1.1001    raeburn   949:         if (defined($spare_server)) {
                    950:             my $hostname = &hostname($spare_server);
1.1083    raeburn   951:             if (defined($hostname)) {
1.1001    raeburn   952: 	        $spare_server = $protocol.'://'.$hostname;
                    953:             }
                    954:         }
1.784     albertel  955:     }
                    956:     return $spare_server;
                    957: }
                    958: 
                    959: sub compare_server_load {
1.1253    raeburn   960:     my ($try_server, $spare_server, $lowest_load, $required) = @_;
                    961: 
                    962:     if ($required) {
                    963:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                    964:         my $remoterev = &get_server_loncaparev(undef,$try_server);
                    965:         my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                    966:         if (($major eq '' && $minor eq '') ||
                    967:             (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                    968:             return ($spare_server,$lowest_load);
                    969:         }
                    970:     }
1.784     albertel  971: 
                    972:     my $loadans     = &reply('load',    $try_server);
                    973:     my $userloadans = &reply('userload',$try_server);
                    974: 
                    975:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   976: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  977:     }
                    978: 
                    979:     my $load;
                    980:     if ($loadans =~ /\d/) {
                    981: 	if ($userloadans =~ /\d/) {
                    982: 	    #both are numbers, pick the bigger one
                    983: 	    $load = ($loadans > $userloadans) ? $loadans 
                    984: 		                              : $userloadans;
1.411     albertel  985: 	} else {
1.784     albertel  986: 	    $load = $loadans;
1.411     albertel  987: 	}
1.784     albertel  988:     } else {
                    989: 	$load = $userloadans;
                    990:     }
                    991: 
                    992:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    993: 	$spare_server = $try_server;
                    994: 	$lowest_load  = $load;
1.370     albertel  995:     }
1.784     albertel  996:     return ($spare_server,$lowest_load);
1.202     matthew   997: }
1.914     albertel  998: 
                    999: # --------------------------- ask offload servers if user already has a session
                   1000: sub find_existing_session {
                   1001:     my ($udom,$uname) = @_;
1.1123    raeburn  1002:     my $spareshash = &this_host_spares($udom);
                   1003:     if (ref($spareshash) eq 'HASH') {
                   1004:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                   1005:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                   1006:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1007:             }
                   1008:         }
                   1009:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                   1010:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                   1011:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                   1012:             }
                   1013:         }
1.914     albertel 1014:     }
                   1015:     return;
                   1016: }
                   1017: 
                   1018: # -------------------------------- ask if server already has a session for user
                   1019: sub has_user_session {
                   1020:     my ($lonid,$udom,$uname) = @_;
                   1021:     my $result = &reply(join(':','userhassession',
                   1022: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                   1023:     return 1 if ($result eq 'ok');
                   1024: 
                   1025:     return 0;
                   1026: }
                   1027: 
1.1076    raeburn  1028: # --------- determine least loaded server in a user's domain which allows login
                   1029: 
                   1030: sub choose_server {
1.1259    raeburn  1031:     my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1.1076    raeburn  1032:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn  1033:     my %servers = &get_servers($udom);
1.1076    raeburn  1034:     my $lowest_load = 30000;
1.1259    raeburn  1035:     my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
                   1036:     if ($skiploadbal) {
                   1037:         ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
                   1038:         unless (defined($cached)) {
                   1039:             my $cachetime = 60*60*24;
                   1040:             my %domconfig =
                   1041:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1042:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1043:                 $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
                   1044:                                            $cachetime);
                   1045:             }
                   1046:         }
                   1047:     }
1.1076    raeburn  1048:     foreach my $lonhost (keys(%servers)) {
1.1259    raeburn  1049:         if ($skiploadbal) {
                   1050:             if (ref($balancers) eq 'HASH') {
                   1051:                 next if (exists($balancers->{$lonhost}));
                   1052:             }
                   1053:         }   
1.1115    raeburn  1054:         my $loginvia;
                   1055:         if ($checkloginvia) {
                   1056:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn  1057:             if ($loginvia) {
                   1058:                 my ($server,$path) = split(/:/,$loginvia);
                   1059:                 ($login_host, $lowest_load) =
1.1253    raeburn  1060:                     &compare_server_load($server, $login_host, $lowest_load, $required);
1.1116    raeburn  1061:                 if ($login_host eq $server) {
                   1062:                     $portal_path = $path;
1.1151    raeburn  1063:                     $isredirect = 1;
1.1116    raeburn  1064:                 }
                   1065:             } else {
                   1066:                 ($login_host, $lowest_load) =
1.1253    raeburn  1067:                     &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1116    raeburn  1068:                 if ($login_host eq $lonhost) {
                   1069:                     $portal_path = '';
1.1151    raeburn  1070:                     $isredirect = ''; 
1.1116    raeburn  1071:                 }
                   1072:             }
                   1073:         } else {
1.1076    raeburn  1074:             ($login_host, $lowest_load) =
1.1253    raeburn  1075:                 &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1.1076    raeburn  1076:         }
                   1077:     }
                   1078:     if ($login_host ne '') {
1.1116    raeburn  1079:         $hostname = &hostname($login_host);
1.1076    raeburn  1080:     }
1.1331    raeburn  1081:     return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1.1076    raeburn  1082: }
                   1083: 
1.202     matthew  1084: # --------------------------------------------- Try to change a user's password
                   1085: 
                   1086: sub changepass {
1.799     raeburn  1087:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew  1088:     $currentpass = &escape($currentpass);
                   1089:     $newpass     = &escape($newpass);
1.1030    raeburn  1090:     my $lonhost = $perlvar{'lonHostID'};
                   1091:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew  1092: 		       $server);
                   1093:     if (! $answer) {
                   1094: 	&logthis("No reply on password change request to $server ".
                   1095: 		 "by $uname in domain $udom.");
                   1096:     } elsif ($answer =~ "^ok") {
                   1097:         &logthis("$uname in $udom successfully changed their password ".
                   1098: 		 "on $server.");
                   1099:     } elsif ($answer =~ "^pwchange_failure") {
                   1100: 	&logthis("$uname in $udom was unable to change their password ".
                   1101: 		 "on $server.  The action was blocked by either lcpasswd ".
                   1102: 		 "or pwchange");
                   1103:     } elsif ($answer =~ "^non_authorized") {
                   1104:         &logthis("$uname in $udom did not get their password correct when ".
                   1105: 		 "attempting to change it on $server.");
                   1106:     } elsif ($answer =~ "^auth_mode_error") {
                   1107:         &logthis("$uname in $udom attempted to change their password despite ".
                   1108: 		 "not being locally or internally authenticated on $server.");
                   1109:     } elsif ($answer =~ "^unknown_user") {
                   1110:         &logthis("$uname in $udom attempted to change their password ".
                   1111: 		 "on $server but were unable to because $server is not ".
                   1112: 		 "their home server.");
                   1113:     } elsif ($answer =~ "^refused") {
                   1114: 	&logthis("$server refused to change $uname in $udom password because ".
                   1115: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1116:     } elsif ($answer =~ "invalid_client") {
                   1117:         &logthis("$server refused to change $uname in $udom password because ".
                   1118:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1119:     }
                   1120:     return $answer;
1.1       albertel 1121: }
                   1122: 
1.169     harris41 1123: # ----------------------- Try to determine user's current authentication scheme
                   1124: 
                   1125: sub queryauthenticate {
                   1126:     my ($uname,$udom)=@_;
1.456     albertel 1127:     my $uhome=&homeserver($uname,$udom);
                   1128:     if (!$uhome) {
                   1129: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1130: 	return 'no_host';
                   1131:     }
                   1132:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1133:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1134: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1135:     }
1.456     albertel 1136:     return $answer;
1.169     harris41 1137: }
                   1138: 
1.1       albertel 1139: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1140: 
1.1       albertel 1141: sub authenticate {
1.1073    raeburn  1142:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1143:     $upass=&escape($upass);
                   1144:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1145:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1146:     my $newhome;
1.836     www      1147:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1148: # Maybe the machine was offline and only re-appeared again recently?
                   1149:         &reconlonc();
                   1150: # One more
1.952     raeburn  1151: 	$uhome=&homeserver($uname,$udom,1);
                   1152:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1153:             if (defined(&domain($udom,'primary'))) {
                   1154:                 $newhome=&domain($udom,'primary');
                   1155:             }
                   1156:             if ($newhome ne '') {
                   1157:                 $uhome = $newhome;
                   1158:             }
                   1159:         }
1.836     www      1160: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1161: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1162: 	    return 'no_host';
                   1163:         }
1.1       albertel 1164:     }
1.1073    raeburn  1165:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1166:     if ($answer eq 'authorized') {
1.952     raeburn  1167:         if ($newhome) {
                   1168:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1169:             return 'no_account_on_host'; 
                   1170:         } else {
                   1171:             &logthis("User $uname at $udom authorized by $uhome");
                   1172:             return $uhome;
                   1173:         }
1.471     albertel 1174:     }
                   1175:     if ($answer eq 'non_authorized') {
                   1176: 	&logthis("User $uname at $udom rejected by $uhome");
                   1177: 	return 'no_host'; 
1.9       www      1178:     }
1.471     albertel 1179:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1180:     return 'no_host';
                   1181: }
                   1182: 
1.1073    raeburn  1183: sub can_host_session {
1.1074    raeburn  1184:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1185:     my $canhost = 1;
1.1074    raeburn  1186:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1187:     if (ref($remotesessions) eq 'HASH') {
                   1188:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1189:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1190:                 $canhost = 0;
                   1191:             } else {
                   1192:                 $canhost = 1;
                   1193:             }
                   1194:         }
                   1195:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1196:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1197:                 $canhost = 1;
                   1198:             } else {
                   1199:                 $canhost = 0;
                   1200:             }
                   1201:         }
                   1202:         if ($canhost) {
                   1203:             if ($remotesessions->{'version'} ne '') {
                   1204:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1205:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1206:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1207:                         my $major = $1;
                   1208:                         my $minor = $2;
                   1209:                         if (($major < $reqmajor ) ||
                   1210:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1211:                             $canhost = 0;
                   1212:                         }
                   1213:                     } else {
                   1214:                         $canhost = 0;
                   1215:                     }
                   1216:                 }
                   1217:             }
                   1218:         }
                   1219:     }
                   1220:     if ($canhost) {
                   1221:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1222:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1223:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1224:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1225:                 if (($uint_dom ne '') && 
                   1226:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1227:                     $canhost = 0;
                   1228:                 } else {
                   1229:                     $canhost = 1;
                   1230:                 }
                   1231:             }
                   1232:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1233:                 if (($uint_dom ne '') && 
                   1234:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1235:                     $canhost = 1;
                   1236:                 } else {
                   1237:                     $canhost = 0;
                   1238:                 }
                   1239:             }
                   1240:         }
                   1241:     }
                   1242:     return $canhost;
                   1243: }
                   1244: 
1.1083    raeburn  1245: sub spare_can_host {
                   1246:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1247:     my $canhost=1;
1.1279    raeburn  1248:     my $try_server_hostname = &hostname($try_server);
                   1249:     my $serverhomeID = &get_server_homeID($try_server_hostname);
                   1250:     my $serverhomedom = &host_domain($serverhomeID);
                   1251:     my %defdomdefaults = &get_domain_defaults($serverhomedom);
                   1252:     if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
                   1253:         if ($defdomdefaults{'offloadnow'}{$try_server}) {
                   1254:             $canhost = 0;
                   1255:         }
                   1256:     }
                   1257:     if (($canhost) && ($uint_dom)) {
                   1258:         my @intdoms;
                   1259:         my $internet_names = &get_internet_names($try_server);
                   1260:         if (ref($internet_names) eq 'ARRAY') {
                   1261:             @intdoms = @{$internet_names};
                   1262:         }
                   1263:         unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1264:             my $remoterev = &get_server_loncaparev(undef,$try_server);
                   1265:             $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1266:                                          $remotesessions,
                   1267:                                          $defdomdefaults{'hostedsessions'});
                   1268:         }
1.1083    raeburn  1269:     }
                   1270:     return $canhost;
                   1271: }
                   1272: 
1.1123    raeburn  1273: sub this_host_spares {
                   1274:     my ($dom) = @_;
1.1126    raeburn  1275:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1276:     my @hosts = &current_machine_ids();
                   1277:     foreach my $lonhost (@hosts) {
                   1278:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1279:             $dom_in_use = $dom;
                   1280:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1281:             last;
                   1282:         }
                   1283:     }
1.1126    raeburn  1284:     if ($dom_in_use ne '') {
                   1285:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1286:     }
                   1287:     if (ref($result) ne 'HASH') {
                   1288:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1289:         $dom_in_use = &host_domain($lonhost_in_use);
                   1290:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1291:         if (ref($result) ne 'HASH') {
                   1292:             $result = \%spareid;
                   1293:         }
                   1294:     }
                   1295:     return $result;
                   1296: }
                   1297: 
                   1298: sub spares_for_offload  {
                   1299:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1300:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1301:     if (defined($cached)) {
                   1302:         return $result;
                   1303:     } else {
1.1126    raeburn  1304:         my $cachetime = 60*60*24;
                   1305:         my %domconfig =
                   1306:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1307:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1308:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1309:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1310:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1311:                 }
                   1312:             }
                   1313:         }
                   1314:     }
1.1126    raeburn  1315:     return;
1.1123    raeburn  1316: }
                   1317: 
1.1129    raeburn  1318: sub get_lonbalancer_config {
                   1319:     my ($servers) = @_;
                   1320:     my ($currbalancer,$currtargets);
                   1321:     if (ref($servers) eq 'HASH') {
                   1322:         foreach my $server (keys(%{$servers})) {
                   1323:             my %what = (
                   1324:                          spareid => 1,
                   1325:                          perlvar => 1,
                   1326:                        );
                   1327:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1328:             if ($result eq 'ok') {
                   1329:                 if (ref($returnhash) eq 'HASH') {
                   1330:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1331:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1332:                             $currbalancer = $server;
                   1333:                             $currtargets = {};
                   1334:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1335:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1336:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1337:                                 }
                   1338:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1339:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1340:                                 }
                   1341:                             }
                   1342:                             last;
                   1343:                         }
                   1344:                     }
                   1345:                 }
                   1346:             }
                   1347:         }
                   1348:     }
                   1349:     return ($currbalancer,$currtargets);
                   1350: }
                   1351: 
                   1352: sub check_loadbalancing {
1.1331    raeburn  1353:     my ($uname,$udom,$caller) = @_;
1.1191    raeburn  1354:     my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
                   1355:         $rule_in_effect,$offloadto,$otherserver);
1.1129    raeburn  1356:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1357:     my @hosts = &current_machine_ids();
1.1129    raeburn  1358:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1359:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1360:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1361:     my $serverhomedom = &host_domain($lonhost);
1.1307    raeburn  1362:     my $domneedscache;
1.1129    raeburn  1363:     my $cachetime = 60*60*24;
                   1364: 
                   1365:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1366:         $dom_in_use = $udom;
                   1367:         $homeintdom = 1;
                   1368:     } else {
                   1369:         $dom_in_use = $serverhomedom;
                   1370:     }
                   1371:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1372:     unless (defined($cached)) {
                   1373:         my %domconfig =
                   1374:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1375:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1376:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1307    raeburn  1377:         } else {
                   1378:             $domneedscache = $dom_in_use;
1.1129    raeburn  1379:         }
                   1380:     }
                   1381:     if (ref($result) eq 'HASH') {
1.1191    raeburn  1382:         ($is_balancer,$currtargets,$currrules) = 
                   1383:             &check_balancer_result($result,@hosts);
1.1129    raeburn  1384:         if ($is_balancer) {
                   1385:             if (ref($currrules) eq 'HASH') {
                   1386:                 if ($homeintdom) {
                   1387:                     if ($uname ne '') {
                   1388:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1389:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1390:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1391:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1392:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1393:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1394:                             }
                   1395:                         }
                   1396:                         if ($rule_in_effect eq '') {
                   1397:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1398:                             if ($userenv{'inststatus'} ne '') {
                   1399:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1400:                                 my ($othertitle,$usertypes,$types) =
                   1401:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1402:                                 if (ref($types) eq 'ARRAY') {
                   1403:                                     foreach my $type (@{$types}) {
                   1404:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1405:                                             if (exists($currrules->{$type})) {
                   1406:                                                 $rule_in_effect = $currrules->{$type};
                   1407:                                             }
                   1408:                                         }
                   1409:                                     }
                   1410:                                 }
                   1411:                             } else {
                   1412:                                 if (exists($currrules->{'default'})) {
                   1413:                                     $rule_in_effect = $currrules->{'default'};
                   1414:                                 }
                   1415:                             }
                   1416:                         }
                   1417:                     } else {
                   1418:                         if (exists($currrules->{'default'})) {
                   1419:                             $rule_in_effect = $currrules->{'default'};
                   1420:                         }
                   1421:                     }
                   1422:                 } else {
                   1423:                     if ($currrules->{'_LC_external'} ne '') {
                   1424:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1425:                     }
                   1426:                 }
                   1427:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1428:                                                        $uname,$udom);
                   1429:             }
                   1430:         }
                   1431:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1.1239    raeburn  1432:         ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1.1129    raeburn  1433:         unless (defined($cached)) {
                   1434:             my %domconfig =
                   1435:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1436:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1307    raeburn  1437:                 $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
                   1438:             } else {
                   1439:                 $domneedscache = $serverhomedom;
1.1129    raeburn  1440:             }
                   1441:         }
                   1442:         if (ref($result) eq 'HASH') {
1.1191    raeburn  1443:             ($is_balancer,$currtargets,$currrules) = 
                   1444:                 &check_balancer_result($result,@hosts);
                   1445:             if ($is_balancer) {
1.1129    raeburn  1446:                 if (ref($currrules) eq 'HASH') {
                   1447:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1448:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1449:                     }
                   1450:                 }
                   1451:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1452:                                                        $uname,$udom);
                   1453:             }
                   1454:         } else {
                   1455:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1456:                 $is_balancer = 1;
                   1457:                 $offloadto = &this_host_spares($dom_in_use);
                   1458:             }
1.1307    raeburn  1459:             unless (defined($cached)) {
                   1460:                 $domneedscache = $serverhomedom;
                   1461:             }
1.1129    raeburn  1462:         }
                   1463:     } else {
                   1464:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1465:             $is_balancer = 1;
                   1466:             $offloadto = &this_host_spares($dom_in_use);
                   1467:         }
1.1307    raeburn  1468:         unless (defined($cached)) {
                   1469:             $domneedscache = $serverhomedom;
                   1470:         }
                   1471:     }
                   1472:     if ($domneedscache) {
                   1473:         &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1.1129    raeburn  1474:     }
1.1176    raeburn  1475:     if ($is_balancer) {
                   1476:         my $lowest_load = 30000;
                   1477:         if (ref($offloadto) eq 'HASH') {
                   1478:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1479:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1480:                     ($otherserver,$lowest_load) =
                   1481:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1482:                 }
1.1129    raeburn  1483:             }
1.1176    raeburn  1484:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1485: 
1.1176    raeburn  1486:             if (!$found_server) {
                   1487:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1488:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1489:                         ($otherserver,$lowest_load) =
                   1490:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1491:                     }
                   1492:                 }
                   1493:             }
                   1494:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1495:             if (@{$offloadto} == 1) {
                   1496:                 $otherserver = $offloadto->[0];
                   1497:             } elsif (@{$offloadto} > 1) {
                   1498:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1499:                     ($otherserver,$lowest_load) =
                   1500:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1501:                 }
                   1502:             }
                   1503:         }
1.1331    raeburn  1504:         unless ($caller eq 'login') {
                   1505:             if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1506:                 $is_balancer = 0;
                   1507:                 if ($uname ne '' && $udom ne '') {
                   1508:                     if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1.1176    raeburn  1509:                     
1.1331    raeburn  1510:                         &appenv({'user.loadbalexempt'     => $lonhost,  
                   1511:                                  'user.loadbalcheck.time' => time});
                   1512:                     }
1.1176    raeburn  1513:                 }
1.1129    raeburn  1514:             }
                   1515:         }
                   1516:     }
                   1517:     return ($is_balancer,$otherserver);
                   1518: }
                   1519: 
1.1191    raeburn  1520: sub check_balancer_result {
                   1521:     my ($result,@hosts) = @_;
                   1522:     my ($is_balancer,$currtargets,$currrules);
                   1523:     if (ref($result) eq 'HASH') {
                   1524:         if ($result->{'lonhost'} ne '') {
                   1525:             my $currbalancer = $result->{'lonhost'};
                   1526:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1527:                 $is_balancer = 1;
                   1528:                 $currtargets = $result->{'targets'};
                   1529:                 $currrules = $result->{'rules'};
                   1530:             }
                   1531:         } else {
                   1532:             foreach my $key (keys(%{$result})) {
                   1533:                 if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
                   1534:                     (ref($result->{$key}) eq 'HASH')) {
                   1535:                     $is_balancer = 1;
                   1536:                     $currrules = $result->{$key}{'rules'};
                   1537:                     $currtargets = $result->{$key}{'targets'};
                   1538:                     last;
                   1539:                 }
                   1540:             }
                   1541:         }
                   1542:     }
                   1543:     return ($is_balancer,$currtargets,$currrules);
                   1544: }
                   1545: 
1.1129    raeburn  1546: sub get_loadbalancer_targets {
                   1547:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1548:     my $offloadto;
1.1175    raeburn  1549:     if ($rule_in_effect eq 'none') {
                   1550:         return [$perlvar{'lonHostID'}];
                   1551:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1552:         $offloadto = $currtargets;
                   1553:     } else {
                   1554:         if ($rule_in_effect eq 'homeserver') {
                   1555:             my $homeserver = &homeserver($uname,$udom);
                   1556:             if ($homeserver ne 'no_host') {
                   1557:                 $offloadto = [$homeserver];
                   1558:             }
                   1559:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1560:             my %domconfig =
                   1561:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1562:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1563:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1564:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1565:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1566:                     }
                   1567:                 }
                   1568:             } else {
1.1178    raeburn  1569:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1570:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1571:                 if (&hostname($remotebalancer) ne '') {
                   1572:                     $offloadto = [$remotebalancer];
                   1573:                 }
                   1574:             }
                   1575:         } elsif (&hostname($rule_in_effect) ne '') {
                   1576:             $offloadto = [$rule_in_effect];
                   1577:         }
                   1578:     }
                   1579:     return $offloadto;
                   1580: }
                   1581: 
1.1127    raeburn  1582: sub internet_dom_servers {
                   1583:     my ($dom) = @_;
                   1584:     my (%uniqservers,%servers);
                   1585:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1586:     my @machinedoms = &machine_domains($primaryserver);
                   1587:     foreach my $mdom (@machinedoms) {
                   1588:         my %currservers = %servers;
                   1589:         my %server = &get_servers($mdom);
                   1590:         %servers = (%currservers,%server);
                   1591:     }
                   1592:     my %by_hostname;
                   1593:     foreach my $id (keys(%servers)) {
                   1594:         push(@{$by_hostname{$servers{$id}}},$id);
                   1595:     }
                   1596:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1597:         if (@{$by_hostname{$hostname}} > 1) {
                   1598:             my $match = 0;
                   1599:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1600:                 if (&host_domain($id) eq $dom) {
                   1601:                     $uniqservers{$id} = $hostname;
                   1602:                     $match = 1;
                   1603:                 }
                   1604:             }
                   1605:             unless ($match) {
                   1606:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1607:             }
                   1608:         } else {
                   1609:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1610:         }
                   1611:     }
                   1612:     return %uniqservers;
                   1613: }
                   1614: 
1.1347    raeburn  1615: sub trusted_domains {
                   1616:     my ($cmdtype,$calldom) = @_;
1.1349    raeburn  1617:     my ($trusted,$untrusted);
1.1347    raeburn  1618:     if (&domain($calldom) eq '') {
1.1349    raeburn  1619:         return ($trusted,$untrusted);
1.1347    raeburn  1620:     }
                   1621:     unless ($cmdtype =~ /^(content|shared|enroll|coaurem|domroles|catalog|reqcrs|msg)$/) {
1.1349    raeburn  1622:         return ($trusted,$untrusted);
1.1347    raeburn  1623:     }
                   1624:     my $callprimary = &domain($calldom,'primary');
                   1625:     my $intcalldom = &Apache::lonnet::internet_dom($callprimary);
                   1626:     if ($intcalldom eq '') {
1.1349    raeburn  1627:         return ($trusted,$untrusted);
1.1347    raeburn  1628:     }
                   1629: 
                   1630:     my ($trustconfig,$cached)=&Apache::lonnet::is_cached_new('trust',$calldom);
                   1631:     unless (defined($cached)) {
                   1632:         my %domconfig = &Apache::lonnet::get_dom('configuration',['trust'],$calldom);
                   1633:         &Apache::lonnet::do_cache_new('trust',$calldom,$domconfig{'trust'},3600);
                   1634:         $trustconfig = $domconfig{'trust'};
                   1635:     }
                   1636:     if (ref($trustconfig)) {
                   1637:         my (%possexc,%possinc,@allexc,@allinc); 
                   1638:         if (ref($trustconfig->{$cmdtype}) eq 'HASH') {
                   1639:             if (ref($trustconfig->{$cmdtype}->{'exc'}) eq 'ARRAY') {
                   1640:                 map { $possexc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'exc'}}; 
                   1641:             }
                   1642:             if (ref($trustconfig->{$cmdtype}->{'inc'}) eq 'ARRAY') {
                   1643:                 map { $possinc{$_} = 1; } @{$trustconfig->{$cmdtype}->{'inc'}};
                   1644:             }
                   1645:         }
                   1646:         if (keys(%possexc)) {
                   1647:             if (keys(%possinc)) {
                   1648:                 foreach my $key (sort(keys(%possexc))) {
                   1649:                     next if ($key eq $intcalldom);
                   1650:                     unless ($possinc{$key}) {
                   1651:                         push(@allexc,$key);
                   1652:                     }
                   1653:                 }
                   1654:             } else {
                   1655:                 @allexc = sort(keys(%possexc));
                   1656:             }
                   1657:         }
                   1658:         if (keys(%possinc)) {
                   1659:             $possinc{$intcalldom} = 1;
                   1660:             @allinc = sort(keys(%possinc));
                   1661:         }
                   1662:         if ((@allexc > 0) || (@allinc > 0)) {
                   1663:             my %doms_by_intdom;
                   1664:             my %allintdoms = &all_host_intdom();
                   1665:             my %alldoms = &all_host_domain();
                   1666:             foreach my $key (%allintdoms) {
                   1667:                 if (ref($doms_by_intdom{$allintdoms{$key}}) eq 'ARRAY') {
                   1668:                     unless (grep(/^\Q$alldoms{$key}\E$/,@{$doms_by_intdom{$allintdoms{$key}}})) {
                   1669:                         push(@{$doms_by_intdom{$allintdoms{$key}}},$alldoms{$key});
                   1670:                     }
                   1671:                 } else {
                   1672:                     $doms_by_intdom{$allintdoms{$key}} = [$alldoms{$key}]; 
                   1673:                 }
                   1674:             }
                   1675:             foreach my $exc (@allexc) {
                   1676:                 if (ref($doms_by_intdom{$exc}) eq 'ARRAY') {
1.1349    raeburn  1677:                     $untrusted = $doms_by_intdom{$exc};
1.1347    raeburn  1678:                 }
                   1679:             }
                   1680:             foreach my $inc (@allinc) {
                   1681:                 if (ref($doms_by_intdom{$inc}) eq 'ARRAY') {
1.1349    raeburn  1682:                     $trusted = $doms_by_intdom{$inc};
1.1347    raeburn  1683:                 }
                   1684:             }
                   1685:         }
                   1686:     }
1.1349    raeburn  1687:     return ($trusted,$untrusted);
1.1347    raeburn  1688: }
                   1689: 
                   1690: sub will_trust {
                   1691:     my ($cmdtype,$domain,$possdom) = @_;
                   1692:     return 1 if ($domain eq $possdom);
                   1693:     my ($trustedref,$untrustedref) = &trusted_domains($cmdtype,$possdom);
                   1694:     my $willtrust; 
                   1695:     if ((ref($trustedref) eq 'ARRAY') && (@{$trustedref} > 0)) {
                   1696:         if (grep(/^\Q$domain\E$/,@{$trustedref})) {
                   1697:             $willtrust = 1;
                   1698:         }
                   1699:     } elsif ((ref($untrustedref) eq 'ARRAY') && (@{$untrustedref} > 0)) {
                   1700:         unless (grep(/^\Q$domain\E$/,@{$untrustedref})) {
                   1701:             $willtrust = 1;
                   1702:         }
                   1703:     } else {
                   1704:         $willtrust = 1;
                   1705:     }
                   1706:     return $willtrust;
                   1707: }
                   1708: 
1.1       albertel 1709: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1710: 
1.599     albertel 1711: my %homecache;
1.1       albertel 1712: sub homeserver {
1.230     stredwic 1713:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1714:     my $index="$uname:$udom";
1.426     albertel 1715: 
1.599     albertel 1716:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1717: 
                   1718:     my %servers = &get_servers($udom,'library');
                   1719:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1720:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1721: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1722: 
                   1723: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1724: 	if ($answer eq 'found') {
                   1725: 	    delete($badServerCache{$tryserver}); 
                   1726: 	    return $homecache{$index}=$tryserver;
                   1727: 	} elsif ($answer eq 'no_host') {
                   1728: 	    $badServerCache{$tryserver}=1;
                   1729: 	}
1.1       albertel 1730:     }    
                   1731:     return 'no_host';
1.70      www      1732: }
                   1733: 
1.1300    raeburn  1734: # ----- Find the usernames behind a list of student/employee IDs or clicker IDs
1.70      www      1735: 
                   1736: sub idget {
1.1300    raeburn  1737:     my ($udom,$idsref,$namespace)=@_;
1.70      www      1738:     my %returnhash=();
1.1300    raeburn  1739:     my @ids=(); 
                   1740:     if (ref($idsref) eq 'ARRAY') {
                   1741:         @ids = @{$idsref};
                   1742:     } else {
                   1743:         return %returnhash; 
                   1744:     }
                   1745:     if ($namespace eq '') {
                   1746:         $namespace = 'ids';
                   1747:     }
1.70      www      1748:     
1.841     albertel 1749:     my %servers = &get_servers($udom,'library');
                   1750:     foreach my $tryserver (keys(%servers)) {
1.1299    raeburn  1751: 	my $idlist=join('&', map { &escape($_); } @ids);
1.1300    raeburn  1752: 	if ($namespace eq 'ids') {
                   1753: 	    $idlist=~tr/A-Z/a-z/;
                   1754: 	}
                   1755: 	my $reply;
                   1756: 	if ($namespace eq 'ids') {
                   1757: 	    $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1758: 	} else {
                   1759: 	    $reply=&reply("getdom:$udom:$namespace:$idlist",$tryserver);
                   1760: 	}
1.841     albertel 1761: 	my @answer=();
                   1762: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1763: 	    @answer=split(/\&/,$reply);
                   1764: 	}                    ;
                   1765: 	my $i;
                   1766: 	for ($i=0;$i<=$#ids;$i++) {
                   1767: 	    if ($answer[$i]) {
1.1299    raeburn  1768: 		$returnhash{$ids[$i]}=&unescape($answer[$i]);
1.1300    raeburn  1769: 	    }
1.841     albertel 1770: 	}
1.1300    raeburn  1771:     }
1.70      www      1772:     return %returnhash;
                   1773: }
                   1774: 
                   1775: # ------------------------------------- Find the IDs behind a list of usernames
                   1776: 
                   1777: sub idrget {
                   1778:     my ($udom,@unames)=@_;
                   1779:     my %returnhash=();
1.800     albertel 1780:     foreach my $uname (@unames) {
                   1781:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1782:     }
1.70      www      1783:     return %returnhash;
                   1784: }
                   1785: 
1.1300    raeburn  1786: # Store away a list of names and associated student/employee IDs or clicker IDs
1.70      www      1787: 
                   1788: sub idput {
1.1300    raeburn  1789:     my ($udom,$idsref,$uhom,$namespace)=@_;
1.70      www      1790:     my %servers=();
1.1300    raeburn  1791:     my %ids=();
                   1792:     my %byid = ();
                   1793:     if (ref($idsref) eq 'HASH') {
                   1794:         %ids=%{$idsref};
                   1795:     }
                   1796:     if ($namespace eq '') {
                   1797:         $namespace = 'ids'; 
                   1798:     }
1.800     albertel 1799:     foreach my $uname (keys(%ids)) {
                   1800: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1.1300    raeburn  1801:         if ($uhom eq '') {
                   1802:             $uhom=&homeserver($uname,$udom);
                   1803:         }
1.70      www      1804:         if ($uhom ne 'no_host') {
1.800     albertel 1805:             my $esc_unam=&escape($uname);
1.1300    raeburn  1806:             if ($namespace eq 'ids') {
                   1807:                 my $id=&escape($ids{$uname});
                   1808:                 $id=~tr/A-Z/a-z/;
                   1809:                 my $esc_unam=&escape($uname);
                   1810:                 $servers{$uhom}.=$id.'='.$esc_unam.'&';
1.70      www      1811:             } else {
1.1300    raeburn  1812:                 my @currids = split(/,/,$ids{$uname});
                   1813:                 foreach my $id (@currids) {
                   1814:                     $byid{$uhom}{$id} .= $uname.',';
                   1815:                 }
                   1816:             }
                   1817:         }
                   1818:     }
                   1819:     if ($namespace eq 'clickers') {
                   1820:         foreach my $server (keys(%byid)) {
                   1821:             if (ref($byid{$server}) eq 'HASH') {
                   1822:                 foreach my $id (keys(%{$byid{$server}})) {
                   1823:                     $byid{$server} =~ s/,$//;
                   1824:                     $servers{$uhom}.=&escape($id).'='.&escape($byid{$server}).'&'; 
                   1825:                 }
1.70      www      1826:             }
                   1827:         }
1.191     harris41 1828:     }
1.800     albertel 1829:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1830:         $servers{$server} =~ s/\&$//;
                   1831:         if ($namespace eq 'ids') {     
                   1832:             &critical('idput:'.$udom.':'.$servers{$server},$server);
                   1833:         } else {
                   1834:             &critical('updateclickers:'.$udom.':add:'.$servers{$server},$server);
                   1835:         }
1.191     harris41 1836:     }
1.344     www      1837: }
                   1838: 
1.1300    raeburn  1839: # ------------- Delete unwanted student/employee IDs or clicker IDs from domain
1.1231    raeburn  1840: 
                   1841: sub iddel {
1.1300    raeburn  1842:     my ($udom,$idshashref,$uhome,$namespace)=@_;
1.1231    raeburn  1843:     my %result=();
1.1300    raeburn  1844:     my %ids=();
                   1845:     my %byid = ();
                   1846:     if (ref($idshashref) eq 'HASH') {
                   1847:         %ids=%{$idshashref};
                   1848:     } else {
1.1231    raeburn  1849:         return %result;
                   1850:     }
1.1300    raeburn  1851:     if ($namespace eq '') {
                   1852:         $namespace = 'ids';
                   1853:     }
1.1231    raeburn  1854:     my %servers=();
1.1300    raeburn  1855:     while (my ($id,$unamestr) = each(%ids)) {
                   1856:         if ($namespace eq 'ids') {
                   1857:             my $uhom = $uhome;
                   1858:             if ($uhom eq '') { 
                   1859:                 $uhom=&homeserver($unamestr,$udom);
                   1860:             }
                   1861:             if ($uhom ne 'no_host') {
                   1862:                 $servers{$uhom}.='&'.&escape($id);
                   1863:             }
                   1864:          } else {
                   1865:             my @curritems = split(/,/,$ids{$id});
                   1866:             foreach my $uname (@curritems) {
                   1867:                 my $uhom = $uhome;
                   1868:                 if ($uhom eq '') {
                   1869:                     $uhom=&homeserver($uname,$udom);
                   1870:                 }
                   1871:                 if ($uhom ne 'no_host') { 
                   1872:                     $byid{$uhom}{$id} .= $uname.',';
                   1873:                 }
                   1874:             }
1.1231    raeburn  1875:         }
1.1300    raeburn  1876:     }
                   1877:     if ($namespace eq 'clickers') {
                   1878:         foreach my $server (keys(%byid)) {
                   1879:             if (ref($byid{$server}) eq 'HASH') {
                   1880:                 foreach my $id (keys(%{$byid{$server}})) {
                   1881:                     $byid{$server}{$id} =~ s/,$//;
                   1882:                     $servers{$server}.=&escape($id).'='.&escape($byid{$server}{$id}).'&';
                   1883:                 }
1.1231    raeburn  1884:             }
                   1885:         }
                   1886:     }
                   1887:     foreach my $server (keys(%servers)) {
1.1300    raeburn  1888:         $servers{$server} =~ s/\&$//;
                   1889:         if ($namespace eq 'ids') {
                   1890:             $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
                   1891:         } elsif ($namespace eq 'clickers') {
                   1892:             $result{$server} = &critical('updateclickers:'.$udom.':del:'.$servers{$server},$server);
                   1893:         }
1.1231    raeburn  1894:     }
                   1895:     return %result;
                   1896: }
                   1897: 
1.1300    raeburn  1898: # ----- Update clicker ID-to-username look-ups in clickers.db on library server 
                   1899: 
                   1900: sub updateclickers {
                   1901:     my ($udom,$action,$idshashref,$uhome,$critical) = @_;
                   1902:     my %clickers;
                   1903:     if (ref($idshashref) eq 'HASH') {
                   1904:         %clickers=%{$idshashref};
                   1905:     } else {
                   1906:         return;
                   1907:     }
                   1908:     my $items='';
                   1909:     foreach my $item (keys(%clickers)) {
                   1910:         $items.=&escape($item).'='.&escape($clickers{$item}).'&';
                   1911:     }
                   1912:     $items=~s/\&$//;
                   1913:     my $request = "updateclickers:$udom:$action:$items";
                   1914:     if ($critical) {
                   1915:         return &critical($request,$uhome);
                   1916:     } else {
                   1917:         return &reply($request,$uhome);
                   1918:     }
                   1919: }
                   1920: 
1.1023    raeburn  1921: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1922: sub dump_dom {
1.1165    droeschl 1923:     my ($namespace, $udom, $regexp) = @_;
                   1924: 
                   1925:     $udom ||= $env{'user.domain'};
                   1926: 
                   1927:     return () unless $udom;
                   1928: 
                   1929:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1930: }
                   1931: 
1.1023    raeburn  1932: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1933: 
                   1934: sub get_dom {
1.860     raeburn  1935:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.1267    raeburn  1936:     return if ($udom eq 'public');
1.806     raeburn  1937:     my $items='';
                   1938:     foreach my $item (@$storearr) {
                   1939:         $items.=&escape($item).'&';
                   1940:     }
                   1941:     $items=~s/\&$//;
1.860     raeburn  1942:     if (!$udom) {
                   1943:         $udom=$env{'user.domain'};
1.1267    raeburn  1944:         return if ($udom eq 'public');
1.860     raeburn  1945:         if (defined(&domain($udom,'primary'))) {
                   1946:             $uhome=&domain($udom,'primary');
                   1947:         } else {
1.874     albertel 1948:             undef($uhome);
1.860     raeburn  1949:         }
                   1950:     } else {
                   1951:         if (!$uhome) {
                   1952:             if (defined(&domain($udom,'primary'))) {
                   1953:                 $uhome=&domain($udom,'primary');
                   1954:             }
                   1955:         }
                   1956:     }
                   1957:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.1344    raeburn  1958:         my $rep;
                   1959:         if ($namespace =~ /^enc/) {
                   1960:             $rep=&reply("encrypt:egetdom:$udom:$namespace:$items",$uhome);
                   1961:         } else {
                   1962:             $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
                   1963:         }
1.866     raeburn  1964:         my %returnhash;
1.875     albertel 1965:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1966:             return %returnhash;
                   1967:         }
1.806     raeburn  1968:         my @pairs=split(/\&/,$rep);
                   1969:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1970:             return @pairs;
                   1971:         }
                   1972:         my $i=0;
                   1973:         foreach my $item (@$storearr) {
                   1974:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1975:             $i++;
                   1976:         }
                   1977:         return %returnhash;
                   1978:     } else {
1.880     banghart 1979:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1980:     }
                   1981: }
                   1982: 
                   1983: # -------------------------------------------- put items in domain db files 
                   1984: 
                   1985: sub put_dom {
1.860     raeburn  1986:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1987:     if (!$udom) {
                   1988:         $udom=$env{'user.domain'};
                   1989:         if (defined(&domain($udom,'primary'))) {
                   1990:             $uhome=&domain($udom,'primary');
                   1991:         } else {
1.874     albertel 1992:             undef($uhome);
1.860     raeburn  1993:         }
                   1994:     } else {
                   1995:         if (!$uhome) {
                   1996:             if (defined(&domain($udom,'primary'))) {
                   1997:                 $uhome=&domain($udom,'primary');
                   1998:             }
                   1999:         }
                   2000:     } 
                   2001:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  2002:         my $items='';
                   2003:         foreach my $item (keys(%$storehash)) {
                   2004:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   2005:         }
                   2006:         $items=~s/\&$//;
1.1344    raeburn  2007:         if ($namespace =~ /^enc/) {
                   2008:             return &reply("encrypt:putdom:$udom:$namespace:$items",$uhome);
                   2009:         } else {
                   2010:             return &reply("putdom:$udom:$namespace:$items",$uhome);
                   2011:         }
1.806     raeburn  2012:     } else {
1.860     raeburn  2013:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  2014:     }
                   2015: }
                   2016: 
1.1023    raeburn  2017: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  2018: sub newput_dom {
1.1023    raeburn  2019:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  2020:     my $result;
                   2021:     if (!$udom) {
                   2022:         $udom=$env{'user.domain'};
                   2023:     }
1.1023    raeburn  2024:     if ($udom) {
                   2025:         my $uname = &get_domainconfiguser($udom);
                   2026:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  2027:     }
                   2028:     return $result;
                   2029: }
                   2030: 
1.1023    raeburn  2031: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  2032: sub del_dom {
1.1023    raeburn  2033:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  2034:     if (ref($storearr) eq 'ARRAY') {
                   2035:         if (!$udom) {
                   2036:             $udom=$env{'user.domain'};
                   2037:         }
1.1023    raeburn  2038:         if ($udom) {
                   2039:             my $uname = &get_domainconfiguser($udom); 
                   2040:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  2041:         }
                   2042:     }
                   2043: }
                   2044: 
1.1023    raeburn  2045: # ----------------------------------construct domainconfig user for a domain 
                   2046: sub get_domainconfiguser {
                   2047:     my ($udom) = @_;
                   2048:     return $udom.'-domainconfig';
                   2049: }
                   2050: 
1.837     raeburn  2051: sub retrieve_inst_usertypes {
                   2052:     my ($udom) = @_;
                   2053:     my (%returnhash,@order);
1.989     raeburn  2054:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   2055:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   2056:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1.1256    raeburn  2057:         return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1.989     raeburn  2058:     } else {
                   2059:         if (defined(&domain($udom,'primary'))) {
                   2060:             my $uhome=&domain($udom,'primary');
                   2061:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   2062:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1.1256    raeburn  2063:                 &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1.989     raeburn  2064:                 return (\%returnhash,\@order);
                   2065:             }
                   2066:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   2067:             my @pairs=split(/\&/,$hashitems);
                   2068:             foreach my $item (@pairs) {
                   2069:                 my ($key,$value)=split(/=/,$item,2);
                   2070:                 $key = &unescape($key);
                   2071:                 next if ($key =~ /^error: 2 /);
                   2072:                 $returnhash{$key}=&thaw_unescape($value);
                   2073:             }
                   2074:             my @esc_order = split(/\&/,$orderitems);
                   2075:             foreach my $item (@esc_order) {
                   2076:                 push(@order,&unescape($item));
                   2077:             }
                   2078:         } else {
1.1256    raeburn  2079:             &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1.837     raeburn  2080:         }
1.1256    raeburn  2081:         return (\%returnhash,\@order);
1.837     raeburn  2082:     }
                   2083: }
                   2084: 
1.868     raeburn  2085: sub is_domainimage {
                   2086:     my ($url) = @_;
1.1306    raeburn  2087:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1.868     raeburn  2088:         if (&domain($1) ne '') {
                   2089:             return '1';
                   2090:         }
                   2091:     }
                   2092:     return;
                   2093: }
                   2094: 
1.899     raeburn  2095: sub inst_directory_query {
                   2096:     my ($srch) = @_;
                   2097:     my $udom = $srch->{'srchdomain'};
                   2098:     my %results;
                   2099:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  2100:     my $outcome;
1.899     raeburn  2101:     if ($homeserver ne '') {
1.1357    raeburn  2102:         unless ($homeserver eq $perlvar{'lonHostID'}) {
                   2103:             if ($srch->{'srchby'} eq 'email') {
                   2104:                 my $lcrev = &get_server_loncaparev(undef,$homeserver);
                   2105:                 my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2106:                 if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2107:                     (($major == 2) && ($minor < 12))) {
                   2108:                     return;
                   2109:                 }
                   2110:             }
                   2111:         }
1.904     albertel 2112: 	my $queryid=&reply("querysend:instdirsearch:".
                   2113: 			   &escape($srch->{'srchby'}).':'.
                   2114: 			   &escape($srch->{'srchterm'}).':'.
                   2115: 			   &escape($srch->{'srchtype'}),$homeserver);
                   2116: 	my $host=&hostname($homeserver);
                   2117: 	if ($queryid !~/^\Q$host\E\_/) {
1.1343    raeburn  2118: 	    &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
1.904     albertel 2119: 	    return;
                   2120: 	}
                   2121: 	my $response = &get_query_reply($queryid);
                   2122: 	my $maxtries = 5;
                   2123: 	my $tries = 1;
                   2124: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2125: 	    $response = &get_query_reply($queryid);
                   2126: 	    $tries ++;
                   2127: 	}
                   2128: 
                   2129:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  2130:             if ($response eq 'unavailable') {
                   2131:                 $outcome = $response;
                   2132:             } else {
                   2133:                 $outcome = 'ok';
                   2134:                 my @matches = split(/\n/,$response);
                   2135:                 foreach my $match (@matches) {
                   2136:                     my ($key,$value) = split(/=/,$match);
                   2137:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   2138:                 }
1.899     raeburn  2139:             }
                   2140:         }
                   2141:     }
1.909     raeburn  2142:     return ($outcome,%results);
1.899     raeburn  2143: }
                   2144: 
                   2145: sub usersearch {
                   2146:     my ($srch) = @_;
                   2147:     my $dom = $srch->{'srchdomain'};
                   2148:     my %results;
                   2149:     my %libserv = &all_library();
                   2150:     my $query = 'usersearch';
                   2151:     foreach my $tryserver (keys(%libserv)) {
                   2152:         if (&host_domain($tryserver) eq $dom) {
1.1357    raeburn  2153:             unless ($tryserver eq $perlvar{'lonHostID'}) {
                   2154:                 if ($srch->{'srchby'} eq 'email') {
                   2155:                     my $lcrev = &get_server_loncaparev(undef,$tryserver);
                   2156:                     my ($major,$minor) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   2157:                     next if (($major eq '' && $minor eq '') || ($major < 2) ||
                   2158:                              (($major == 2) && ($minor < 12)));
                   2159:                 }
                   2160:             }
1.899     raeburn  2161:             my $host=&hostname($tryserver);
                   2162:             my $queryid=
1.911     raeburn  2163:                 &reply("querysend:".&escape($query).':'.
                   2164:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  2165:                        &escape($srch->{'srchtype'}).':'.
                   2166:                        &escape($srch->{'srchterm'}),$tryserver);
                   2167:             if ($queryid !~/^\Q$host\E\_/) {
                   2168:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  2169:                 next;
1.899     raeburn  2170:             }
                   2171:             my $reply = &get_query_reply($queryid);
                   2172:             my $maxtries = 1;
                   2173:             my $tries = 1;
                   2174:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   2175:                 $reply = &get_query_reply($queryid);
                   2176:                 $tries ++;
                   2177:             }
                   2178:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   2179:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   2180:             } else {
1.911     raeburn  2181:                 my @matches;
                   2182:                 if ($reply =~ /\n/) {
                   2183:                     @matches = split(/\n/,$reply);
                   2184:                 } else {
                   2185:                     @matches = split(/\&/,$reply);
                   2186:                 }
1.899     raeburn  2187:                 foreach my $match (@matches) {
                   2188:                     my ($uname,$udom,%userhash);
1.911     raeburn  2189:                     foreach my $entry (split(/:/,$match)) {
                   2190:                         my ($key,$value) =
                   2191:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  2192:                         $userhash{$key} = $value;
                   2193:                         if ($key eq 'username') {
                   2194:                             $uname = $value;
                   2195:                         } elsif ($key eq 'domain') {
                   2196:                             $udom = $value;
1.911     raeburn  2197:                         }
1.899     raeburn  2198:                     }
                   2199:                     $results{$uname.':'.$udom} = \%userhash;
                   2200:                 }
                   2201:             }
                   2202:         }
                   2203:     }
                   2204:     return %results;
                   2205: }
                   2206: 
1.912     raeburn  2207: sub get_instuser {
                   2208:     my ($udom,$uname,$id) = @_;
                   2209:     my $homeserver = &domain($udom,'primary');
                   2210:     my ($outcome,%results);
                   2211:     if ($homeserver ne '') {
                   2212:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   2213:                            &escape($id).':'.&escape($udom),$homeserver);
                   2214:         my $host=&hostname($homeserver);
                   2215:         if ($queryid !~/^\Q$host\E\_/) {
                   2216:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   2217:             return;
                   2218:         }
                   2219:         my $response = &get_query_reply($queryid);
                   2220:         my $maxtries = 5;
                   2221:         my $tries = 1;
                   2222:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   2223:             $response = &get_query_reply($queryid);
                   2224:             $tries ++;
                   2225:         }
                   2226:         if (!&error($response) && $response ne 'refused') {
                   2227:             if ($response eq 'unavailable') {
                   2228:                 $outcome = $response;
                   2229:             } else {
                   2230:                 $outcome = 'ok';
                   2231:                 my @matches = split(/\n/,$response);
                   2232:                 foreach my $match (@matches) {
                   2233:                     my ($key,$value) = split(/=/,$match);
                   2234:                     $results{&unescape($key)} = &thaw_unescape($value);
                   2235:                 }
                   2236:             }
                   2237:         }
                   2238:     }
                   2239:     my %userinfo;
                   2240:     if (ref($results{$uname}) eq 'HASH') {
                   2241:         %userinfo = %{$results{$uname}};
                   2242:     } 
                   2243:     return ($outcome,%userinfo);
                   2244: }
                   2245: 
1.1290    raeburn  2246: sub get_multiple_instusers {
                   2247:     my ($udom,$users,$caller) = @_;
                   2248:     my ($outcome,$results);
                   2249:     if (ref($users) eq 'HASH') {
                   2250:         my $count = keys(%{$users}); 
                   2251:         my $requested = &freeze_escape($users);
                   2252:         my $homeserver = &domain($udom,'primary');
                   2253:         if ($homeserver ne '') {
                   2254:             my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
                   2255:             my $host=&hostname($homeserver);
                   2256:             if ($queryid !~/^\Q$host\E\_/) {
                   2257:                 &logthis('get_multiple_instusers invalid queryid: '.$queryid.
                   2258:                          ' for host: '.$homeserver.'in domain '.$udom);
                   2259:                 return ($outcome,$results);
                   2260:             }
                   2261:             my $response = &get_query_reply($queryid);
                   2262:             my $maxtries = 5;
                   2263:             if ($count > 100) {
                   2264:                 $maxtries = 1+int($count/20);
                   2265:             }
                   2266:             my $tries = 1;
                   2267:             while (($response=~/^timeout/) && ($tries <= $maxtries)) {
                   2268:                 $response = &get_query_reply($queryid);
                   2269:                 $tries ++;
                   2270:             }
                   2271:             if ($response eq '') {
                   2272:                 $results = {};
                   2273:                 foreach my $key (keys(%{$users})) {
                   2274:                     my ($uname,$id);
                   2275:                     if ($caller eq 'id') {
                   2276:                         $id = $key;
                   2277:                     } else {
                   2278:                         $uname = $key;
                   2279:                     }
                   2280:                     my ($resp,%info) = &get_instuser($udom,$uname,$id);
1.1291    raeburn  2281:                     $outcome = $resp;
1.1290    raeburn  2282:                     if ($resp eq 'ok') {
                   2283:                         %{$results} = (%{$results}, %info);
                   2284:                     } else {
                   2285:                         last;
                   2286:                     }
                   2287:                 }
                   2288:             } elsif(!&error($response) && ($response ne 'refused')) {
                   2289:                 if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
                   2290:                     $outcome = $response;
                   2291:                 } else {
1.1291    raeburn  2292:                     ($outcome,my $userdata) = split(/=/,$response,2);
1.1290    raeburn  2293:                     if ($outcome eq 'ok') {
                   2294:                         $results = &thaw_unescape($userdata); 
                   2295:                     }
                   2296:                 }
                   2297:             }
                   2298:         }
                   2299:     }
                   2300:     return ($outcome,$results);
                   2301: }
                   2302: 
1.912     raeburn  2303: sub inst_rulecheck {
1.923     raeburn  2304:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  2305:     my %returnhash;
                   2306:     if ($udom ne '') {
                   2307:         if (ref($rules) eq 'ARRAY') {
                   2308:             @{$rules} = map {&escape($_);} (@{$rules});
                   2309:             my $rulestr = join(':',@{$rules});
                   2310:             my $homeserver=&domain($udom,'primary');
                   2311:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2312:                 my $response;
                   2313:                 if ($item eq 'username') {                
                   2314:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   2315:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  2316:                                               $homeserver));
1.923     raeburn  2317:                 } elsif ($item eq 'id') {
                   2318:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   2319:                                               ':'.&escape($id).':'.$rulestr,
                   2320:                                               $homeserver));
1.945     raeburn  2321:                 } elsif ($item eq 'selfcreate') {
                   2322:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  2323:                                                &escape($udom).':'.&escape($uname).
                   2324:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  2325:                 }
1.912     raeburn  2326:                 if ($response ne 'refused') {
                   2327:                     my @pairs=split(/\&/,$response);
                   2328:                     foreach my $item (@pairs) {
                   2329:                         my ($key,$value)=split(/=/,$item,2);
                   2330:                         $key = &unescape($key);
                   2331:                         next if ($key =~ /^error: 2 /);
                   2332:                         $returnhash{$key}=&thaw_unescape($value);
                   2333:                     }
                   2334:                 }
                   2335:             }
                   2336:         }
                   2337:     }
                   2338:     return %returnhash;
                   2339: }
                   2340: 
                   2341: sub inst_userrules {
1.923     raeburn  2342:     my ($udom,$check) = @_;
1.912     raeburn  2343:     my (%ruleshash,@ruleorder);
                   2344:     if ($udom ne '') {
                   2345:         my $homeserver=&domain($udom,'primary');
                   2346:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  2347:             my $response;
                   2348:             if ($check eq 'id') {
                   2349:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  2350:                                  $homeserver);
1.943     raeburn  2351:             } elsif ($check eq 'email') {
                   2352:                 $response=&reply('instemailrules:'.&escape($udom),
                   2353:                                  $homeserver);
1.923     raeburn  2354:             } else {
                   2355:                 $response=&reply('instuserrules:'.&escape($udom),
                   2356:                                  $homeserver);
                   2357:             }
1.912     raeburn  2358:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  2359:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  2360:                 ($response ne 'no_such_host')) {
                   2361:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   2362:                 my @pairs=split(/\&/,$hashitems);
                   2363:                 foreach my $item (@pairs) {
                   2364:                     my ($key,$value)=split(/=/,$item,2);
                   2365:                     $key = &unescape($key);
                   2366:                     next if ($key =~ /^error: 2 /);
                   2367:                     $ruleshash{$key}=&thaw_unescape($value);
                   2368:                 }
                   2369:                 my @esc_order = split(/\&/,$orderitems);
                   2370:                 foreach my $item (@esc_order) {
                   2371:                     push(@ruleorder,&unescape($item));
                   2372:                 }
                   2373:             }
                   2374:         }
                   2375:     }
                   2376:     return (\%ruleshash,\@ruleorder);
                   2377: }
                   2378: 
1.976     raeburn  2379: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  2380: 
                   2381: sub get_domain_defaults {
1.1240    raeburn  2382:     my ($domain,$ignore_cache) = @_;
1.1242    raeburn  2383:     return if (($domain eq '') || ($domain eq 'public'));
1.943     raeburn  2384:     my $cachetime = 60*60*24;
1.1240    raeburn  2385:     unless ($ignore_cache) {
                   2386:         my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   2387:         if (defined($cached)) {
                   2388:             if (ref($result) eq 'HASH') {
                   2389:                 return %{$result};
                   2390:             }
1.943     raeburn  2391:         }
                   2392:     }
                   2393:     my %domdefaults;
                   2394:     my %domconfig =
1.989     raeburn  2395:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  2396:                                   'requestcourses','inststatus',
1.1183    raeburn  2397:                                   'coursedefaults','usersessions',
1.1258    raeburn  2398:                                   'requestauthor','selfenrollment',
1.1320    raeburn  2399:                                   'coursecategories','ssl','autoenroll',
1.1332    raeburn  2400:                                   'trust','helpsettings'],$domain);
1.1305    raeburn  2401:     my @coursetypes = ('official','unofficial','community','textbook','placement');
1.943     raeburn  2402:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   2403:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   2404:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   2405:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  2406:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  2407:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  2408:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.1340    raeburn  2409:         $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
                   2410:         $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
                   2411:         $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
1.943     raeburn  2412:     } else {
                   2413:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   2414:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   2415:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   2416:     }
1.976     raeburn  2417:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   2418:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   2419:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   2420:         } else {
                   2421:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1.1229    raeburn  2422:         }
1.1177    raeburn  2423:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  2424:         foreach my $item (@usertools) {
                   2425:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   2426:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   2427:             }
                   2428:         }
1.1229    raeburn  2429:         if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
                   2430:             $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
                   2431:         }
1.976     raeburn  2432:     }
1.985     raeburn  2433:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1305    raeburn  2434:         foreach my $item ('official','unofficial','community','textbook','placement') {
1.985     raeburn  2435:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   2436:         }
                   2437:     }
1.1183    raeburn  2438:     if (ref($domconfig{'requestauthor'}) eq 'HASH') {
                   2439:         $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
                   2440:     }
1.989     raeburn  2441:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
1.1256    raeburn  2442:         foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
1.989     raeburn  2443:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   2444:         }
                   2445:     }
1.1047    raeburn  2446:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1.1230    raeburn  2447:         $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
1.1277    raeburn  2448:         $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
                   2449:         $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
                   2450:         if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
                   2451:             $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
                   2452:         }
1.1254    raeburn  2453:         foreach my $type (@coursetypes) {
                   2454:             if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
                   2455:                 unless ($type eq 'community') {
                   2456:                     $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
                   2457:                 }
                   2458:             }
                   2459:             if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
                   2460:                 $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
                   2461:             }
1.1277    raeburn  2462:             if ($domdefaults{'postsubmit'} eq 'on') {
                   2463:                 if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
                   2464:                     $domdefaults{$type.'postsubtimeout'} = 
                   2465:                         $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type}; 
                   2466:                 }
                   2467:             }
1.1230    raeburn  2468:         }
1.1286    raeburn  2469:         if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
                   2470:             if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
                   2471:                 my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
                   2472:                 if (@clonecodes) {
                   2473:                     $domdefaults{'canclone'} = join('+',@clonecodes);
                   2474:                 }
                   2475:             }
                   2476:         } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
                   2477:             $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
                   2478:         }
1.1356    raeburn  2479:         if ($domconfig{'coursedefaults'}{'texengine'}) {
                   2480:             $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
                   2481:         } 
1.1047    raeburn  2482:     }
1.1073    raeburn  2483:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   2484:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   2485:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   2486:         }
                   2487:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   2488:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   2489:         }
1.1279    raeburn  2490:         if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
                   2491:             $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
                   2492:         }
1.1073    raeburn  2493:     }
1.1254    raeburn  2494:     if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
                   2495:         if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
                   2496:             my @settings = ('types','registered','enroll_dates','access_dates','section',
                   2497:                             'approval','limit');
                   2498:             foreach my $type (@coursetypes) {
                   2499:                 if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
                   2500:                     my @mgrdc = ();
                   2501:                     foreach my $item (@settings) {
                   2502:                         if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
                   2503:                             push(@mgrdc,$item);
                   2504:                         }
                   2505:                     }
                   2506:                     if (@mgrdc) {
                   2507:                         $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
                   2508:                     }
                   2509:                 }
                   2510:             }
                   2511:         }
                   2512:         if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
                   2513:             foreach my $type (@coursetypes) {
                   2514:                 if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
                   2515:                     foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
                   2516:                         $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
                   2517:                     }
                   2518:                 }
                   2519:             }
                   2520:         }
                   2521:     }
1.1258    raeburn  2522:     if (ref($domconfig{'coursecategories'}) eq 'HASH') {
                   2523:         $domdefaults{'catauth'} = 'std';
                   2524:         $domdefaults{'catunauth'} = 'std';
                   2525:         if ($domconfig{'coursecategories'}{'auth'}) { 
                   2526:             $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
                   2527:         }
                   2528:         if ($domconfig{'coursecategories'}{'unauth'}) {
                   2529:             $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
                   2530:         }
                   2531:     }
1.1315    raeburn  2532:     if (ref($domconfig{'ssl'}) eq 'HASH') {
                   2533:         if (ref($domconfig{'ssl'}{'replication'}) eq 'HASH') {
                   2534:             $domdefaults{'replication'} = $domconfig{'ssl'}{'replication'};
                   2535:         }
1.1338    raeburn  2536:         if (ref($domconfig{'ssl'}{'connto'}) eq 'HASH') {
                   2537:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connto'};
                   2538:         }
                   2539:         if (ref($domconfig{'ssl'}{'connfrom'}) eq 'HASH') {
                   2540:             $domdefaults{'connect'} = $domconfig{'ssl'}{'connfrom'};
1.1315    raeburn  2541:         }
                   2542:     }
1.1320    raeburn  2543:     if (ref($domconfig{'trust'}) eq 'HASH') {
                   2544:         my @prefixes = qw(content shared enroll othcoau coaurem domroles catalog reqcrs msg);
                   2545:         foreach my $prefix (@prefixes) {
                   2546:             if (ref($domconfig{'trust'}{$prefix}) eq 'HASH') {
                   2547:                 $domdefaults{'trust'.$prefix} = $domconfig{'trust'}{$prefix};
                   2548:             }
                   2549:         }
                   2550:     }
1.1314    raeburn  2551:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   2552:         $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
                   2553:     }
1.1332    raeburn  2554:     if (ref($domconfig{'helpsettings'}) eq 'HASH') {
                   2555:         $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
                   2556:         if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
                   2557:             $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
                   2558:         }
                   2559:     }
1.1219    raeburn  2560:     &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
1.943     raeburn  2561:     return %domdefaults;
                   2562: }
                   2563: 
1.1311    raeburn  2564: sub course_portal_url {
                   2565:     my ($cnum,$cdom) = @_;
                   2566:     my $chome = &homeserver($cnum,$cdom);
                   2567:     my $hostname = &hostname($chome);
                   2568:     my $protocol = $protocol{$chome};
                   2569:     $protocol = 'http' if ($protocol ne 'https');
                   2570:     my %domdefaults = &get_domain_defaults($cdom);
                   2571:     my $firsturl;
                   2572:     if ($domdefaults{'portal_def'}) {
                   2573:         $firsturl = $domdefaults{'portal_def'};
                   2574:     } else {
                   2575:         $firsturl = $protocol.'://'.$hostname;
                   2576:     }
                   2577:     return $firsturl;
                   2578: }
                   2579: 
1.344     www      2580: # --------------------------------------------------- Assign a key to a student
                   2581: 
                   2582: sub assign_access_key {
1.364     www      2583: #
                   2584: # a valid key looks like uname:udom#comments
                   2585: # comments are being appended
                   2586: #
1.498     www      2587:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2588:     $kdom=
1.620     albertel 2589:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2590:     $knum=
1.620     albertel 2591:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2592:     $cdom=
1.620     albertel 2593:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2594:     $cnum=
1.620     albertel 2595:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2596:     $udom=$env{'user.name'} unless (defined($udom));
                   2597:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2598:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2599:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2600:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2601:                                                   # assigned to this person
                   2602:                                                   # - this should not happen,
1.345     www      2603:                                                   # unless something went wrong
                   2604:                                                   # the first time around
                   2605: # ready to assign
1.364     www      2606:         $logentry=$1.'; '.$logentry;
1.496     www      2607:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2608:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2609: # key now belongs to user
1.346     www      2610: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2611:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2612:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2613:                 return 'ok';
                   2614:             } else {
                   2615:                 return 
                   2616:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2617: 	    }
                   2618:         } else {
                   2619:             return 'error: Could not assign key, try again later.';
                   2620:         }
1.364     www      2621:     } elsif (!$existing{$ckey}) {
1.345     www      2622: # the key does not exist
                   2623: 	return 'error: The key does not exist';
                   2624:     } else {
                   2625: # the key is somebody else's
                   2626: 	return 'error: The key is already in use';
                   2627:     }
1.344     www      2628: }
                   2629: 
1.364     www      2630: # ------------------------------------------ put an additional comment on a key
                   2631: 
                   2632: sub comment_access_key {
                   2633: #
                   2634: # a valid key looks like uname:udom#comments
                   2635: # comments are being appended
                   2636: #
                   2637:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2638:     $cdom=
1.620     albertel 2639:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2640:     $cnum=
1.620     albertel 2641:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2642:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2643:     if ($existing{$ckey}) {
                   2644:         $existing{$ckey}.='; '.$logentry;
                   2645: # ready to assign
1.367     www      2646:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2647:                                                  $cdom,$cnum) eq 'ok') {
                   2648: 	    return 'ok';
                   2649:         } else {
                   2650: 	    return 'error: Count not store comment.';
                   2651:         }
                   2652:     } else {
                   2653: # the key does not exist
                   2654: 	return 'error: The key does not exist';
                   2655:     }
                   2656: }
                   2657: 
1.344     www      2658: # ------------------------------------------------------ Generate a set of keys
                   2659: 
                   2660: sub generate_access_keys {
1.364     www      2661:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2662:     $cdom=
1.620     albertel 2663:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2664:     $cnum=
1.620     albertel 2665:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2666:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2667:     unless (($cdom) && ($cnum)) { return 0; }
                   2668:     if ($number>10000) { return 0; }
                   2669:     sleep(2); # make sure don't get same seed twice
                   2670:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2671:     my $total=0;
                   2672:     for (my $i=1;$i<=$number;$i++) {
                   2673:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2674:                   sprintf("%lx",int(100000*rand)).'-'.
                   2675:                   sprintf("%lx",int(100000*rand));
                   2676:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2677:        $newkey=~s/0/h/g; # and also 0 and O
                   2678:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2679:        if ($existing{$newkey}) {
                   2680:            $i--;
                   2681:        } else {
1.364     www      2682: 	  if (&put('accesskeys',
                   2683:               { $newkey => '# generated '.localtime().
1.620     albertel 2684:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2685:                            '; '.$logentry },
                   2686: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2687:               $total++;
                   2688: 	  }
                   2689:        }
                   2690:     }
1.620     albertel 2691:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2692:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2693:     return $total;
                   2694: }
                   2695: 
                   2696: # ------------------------------------------------------- Validate an accesskey
                   2697: 
                   2698: sub validate_access_key {
                   2699:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2700:     $cdom=
1.620     albertel 2701:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2702:     $cnum=
1.620     albertel 2703:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2704:     $udom=$env{'user.domain'} unless (defined($udom));
                   2705:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2706:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2707:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2708: }
                   2709: 
                   2710: # ------------------------------------- Find the section of student in a course
1.652     albertel 2711: sub devalidate_getsection_cache {
                   2712:     my ($udom,$unam,$courseid)=@_;
                   2713:     my $hashid="$udom:$unam:$courseid";
                   2714:     &devalidate_cache_new('getsection',$hashid);
                   2715: }
1.298     matthew  2716: 
1.815     albertel 2717: sub courseid_to_courseurl {
                   2718:     my ($courseid) = @_;
                   2719:     #already url style courseid
                   2720:     return $courseid if ($courseid =~ m{^/});
                   2721: 
                   2722:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2723: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2724: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2725: 	return "/$cdom/$cnum";
                   2726:     }
                   2727: 
                   2728:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2729:     if (exists($courseinfo{'num'})) {
                   2730: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2731:     }
                   2732: 
                   2733:     return undef;
                   2734: }
                   2735: 
1.298     matthew  2736: sub getsection {
                   2737:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2738:     my $cachetime=1800;
1.551     albertel 2739: 
                   2740:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2741:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2742:     if (defined($cached)) { return $result; }
                   2743: 
1.298     matthew  2744:     my %Pending; 
                   2745:     my %Expired;
                   2746:     #
                   2747:     # Each role can either have not started yet (pending), be active, 
                   2748:     #    or have expired.
                   2749:     #
                   2750:     # If there is an active role, we are done.
                   2751:     #
                   2752:     # If there is more than one role which has not started yet, 
                   2753:     #     choose the one which will start sooner
                   2754:     # If there is one role which has not started yet, return it.
                   2755:     #
                   2756:     # If there is more than one expired role, choose the one which ended last.
                   2757:     # If there is a role which has expired, return it.
                   2758:     #
1.815     albertel 2759:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2760:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2761:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2762:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2763:         my $section=$1;
                   2764:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2765:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2766:         my $now=time;
1.548     albertel 2767:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2768:             $Expired{$end}=$section;
                   2769:             next;
                   2770:         }
1.548     albertel 2771:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2772:             $Pending{$start}=$section;
                   2773:             next;
                   2774:         }
1.599     albertel 2775:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2776:     }
                   2777:     #
                   2778:     # Presumedly there will be few matching roles from the above
                   2779:     # loop and the sorting time will be negligible.
                   2780:     if (scalar(keys(%Pending))) {
                   2781:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2782:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2783:     } 
                   2784:     if (scalar(keys(%Expired))) {
                   2785:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2786:         my $time = pop(@sorted);
1.599     albertel 2787:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2788:     }
1.599     albertel 2789:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2790: }
1.70      www      2791: 
1.599     albertel 2792: sub save_cache {
                   2793:     &purge_remembered();
1.722     albertel 2794:     #&Apache::loncommon::validate_page();
1.620     albertel 2795:     undef(%env);
1.780     albertel 2796:     undef($env_loaded);
1.599     albertel 2797: }
1.452     albertel 2798: 
1.599     albertel 2799: my $to_remember=-1;
                   2800: my %remembered;
                   2801: my %accessed;
                   2802: my $kicks=0;
                   2803: my $hits=0;
1.849     albertel 2804: sub make_key {
                   2805:     my ($name,$id) = @_;
1.872     albertel 2806:     if (length($id) > 65 
                   2807: 	&& length(&escape($id)) > 200) {
                   2808: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2809:     }
1.849     albertel 2810:     return &escape($name.':'.$id);
                   2811: }
                   2812: 
1.599     albertel 2813: sub devalidate_cache_new {
                   2814:     my ($name,$id,$debug) = @_;
                   2815:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.1319    damieng  2816:     my $remembered_id=$name.':'.$id;
1.849     albertel 2817:     $id=&make_key($name,$id);
1.599     albertel 2818:     $memcache->delete($id);
1.1319    damieng  2819:     delete($remembered{$remembered_id});
                   2820:     delete($accessed{$remembered_id});
1.599     albertel 2821: }
                   2822: 
                   2823: sub is_cached_new {
                   2824:     my ($name,$id,$debug) = @_;
1.1319    damieng  2825:     my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) whenever possible
                   2826:     if (exists($remembered{$remembered_id})) {
                   2827: 	if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
                   2828: 	$accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2829: 	$hits++;
1.1319    damieng  2830: 	return ($remembered{$remembered_id},1);
1.599     albertel 2831:     }
1.1319    damieng  2832:     $id=&make_key($name,$id);
1.599     albertel 2833:     my $value = $memcache->get($id);
                   2834:     if (!(defined($value))) {
                   2835: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2836: 	return (undef,undef);
1.416     albertel 2837:     }
1.599     albertel 2838:     if ($value eq '__undef__') {
                   2839: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2840: 	$value=undef;
                   2841:     }
1.1319    damieng  2842:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2843:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2844:     return ($value,1);
                   2845: }
                   2846: 
                   2847: sub do_cache_new {
                   2848:     my ($name,$id,$value,$time,$debug) = @_;
1.1319    damieng  2849:     my $remembered_id=$name.':'.$id;
1.849     albertel 2850:     $id=&make_key($name,$id);
1.599     albertel 2851:     my $setvalue=$value;
                   2852:     if (!defined($setvalue)) {
                   2853: 	$setvalue='__undef__';
                   2854:     }
1.623     albertel 2855:     if (!defined($time) ) {
                   2856: 	$time=600;
                   2857:     }
1.599     albertel 2858:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2859:     my $result = $memcache->set($id,$setvalue,$time);
                   2860:     if (! $result) {
1.872     albertel 2861: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2862: 	$memcache->disconnect_all();
1.872     albertel 2863:     }
1.600     albertel 2864:     # need to make a copy of $value
1.1319    damieng  2865:     &make_room($remembered_id,$value,$debug);
1.599     albertel 2866:     return $value;
                   2867: }
                   2868: 
                   2869: sub make_room {
1.1319    damieng  2870:     my ($remembered_id,$value,$debug)=@_;
1.919     albertel 2871: 
1.1319    damieng  2872:     $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
1.919     albertel 2873:                                     : $value;
1.599     albertel 2874:     if ($to_remember<0) { return; }
1.1319    damieng  2875:     $accessed{$remembered_id}=[&gettimeofday()];
1.599     albertel 2876:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2877:     my $to_kick;
                   2878:     my $max_time=0;
                   2879:     foreach my $other (keys(%accessed)) {
                   2880: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2881: 	    $to_kick=$other;
                   2882: 	    $max_time=&tv_interval($accessed{$other});
                   2883: 	}
                   2884:     }
                   2885:     delete($remembered{$to_kick});
                   2886:     delete($accessed{$to_kick});
                   2887:     $kicks++;
                   2888:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2889:     return;
                   2890: }
                   2891: 
1.599     albertel 2892: sub purge_remembered {
1.604     albertel 2893:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2894:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2895:     undef(%remembered);
                   2896:     undef(%accessed);
1.428     albertel 2897: }
1.70      www      2898: # ------------------------------------- Read an entry from a user's environment
                   2899: 
                   2900: sub userenvironment {
                   2901:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2902:     my $items;
                   2903:     foreach my $item (@what) {
                   2904:         $items.=&escape($item).'&';
                   2905:     }
                   2906:     $items=~s/\&$//;
1.70      www      2907:     my %returnhash=();
1.1009    raeburn  2908:     my $uhome = &homeserver($unam,$udom);
                   2909:     unless ($uhome eq 'no_host') {
                   2910:         my @answer=split(/\&/, 
                   2911:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2912:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2913:             return %returnhash;
                   2914:         }
1.1009    raeburn  2915:         my $i;
                   2916:         for ($i=0;$i<=$#what;$i++) {
                   2917: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2918:         }
1.70      www      2919:     }
                   2920:     return %returnhash;
1.1       albertel 2921: }
                   2922: 
1.617     albertel 2923: # ---------------------------------------------------------- Get a studentphoto
                   2924: sub studentphoto {
                   2925:     my ($udom,$unam,$ext) = @_;
                   2926:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2927:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2928:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2929:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2930:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2931:             } else {
                   2932:                 my ($result,$perm_reqd)=
1.707     albertel 2933: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2934:                 if ($result eq 'ok') {
                   2935:                     if (!($perm_reqd eq 'yes')) {
                   2936:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2937:                     }
                   2938:                 }
                   2939:             }
                   2940:         }
                   2941:     } else {
                   2942:         my ($result,$perm_reqd) = 
1.707     albertel 2943: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2944:         if ($result eq 'ok') {
                   2945:             if (!($perm_reqd eq 'yes')) {
                   2946:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2947:             }
                   2948:         }
                   2949:     }
                   2950:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2951: }
                   2952: 
                   2953: sub retrievestudentphoto {
                   2954:     my ($udom,$unam,$ext,$type) = @_;
                   2955:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2956:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2957:     if ($ret eq 'ok') {
                   2958:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2959:         if ($type eq 'thumbnail') {
                   2960:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2961:         }
                   2962:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2963:         return $tokenurl;
                   2964:     } else {
                   2965:         if ($type eq 'thumbnail') {
                   2966:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2967:         } else { 
                   2968:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2969:         }
1.617     albertel 2970:     }
                   2971: }
                   2972: 
1.263     www      2973: # -------------------------------------------------------------------- New chat
                   2974: 
                   2975: sub chatsend {
1.724     raeburn  2976:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2977:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2978:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2979:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2980:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2981: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2982: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2983: }
                   2984: 
                   2985: # ------------------------------------------ Find current version of a resource
                   2986: 
                   2987: sub getversion {
                   2988:     my $fname=&clutter(shift);
1.1189    raeburn  2989:     unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
1.292     www      2990:     return &currentversion(&filelocation('',$fname));
                   2991: }
                   2992: 
                   2993: sub currentversion {
                   2994:     my $fname=shift;
                   2995:     my $author=$fname;
                   2996:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2997:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2998:     my $home=&homeserver($uname,$udom);
1.292     www      2999:     if ($home eq 'no_host') { 
                   3000:         return -1; 
                   3001:     }
1.1112    www      3002:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      3003:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3004: 	return -1;
                   3005:     }
1.1112    www      3006:     return $answer;
1.263     www      3007: }
                   3008: 
1.1111    www      3009: #
                   3010: # Return special version number of resource if set by override, empty otherwise
                   3011: #
                   3012: sub usedversion {
                   3013:     my $fname=shift;
                   3014:     unless ($fname) { $fname=$env{'request.uri'}; }
                   3015:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   3016:     if ($urlversion) { return $urlversion; }
                   3017:     return '';
                   3018: }
                   3019: 
1.1       albertel 3020: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      3021: 
1.1       albertel 3022: sub subscribe {
                   3023:     my $fname=shift;
1.761     raeburn  3024:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 3025:     $fname=~s/[\n\r]//g;
1.1       albertel 3026:     my $author=$fname;
                   3027:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3028:     my ($udom,$uname)=split(/\//,$author);
                   3029:     my $home=homeserver($uname,$udom);
1.335     albertel 3030:     if ($home eq 'no_host') {
                   3031:         return 'not_found';
1.1       albertel 3032:     }
                   3033:     my $answer=reply("sub:$fname",$home);
1.64      www      3034:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   3035: 	$answer.=' by '.$home;
                   3036:     }
1.1       albertel 3037:     return $answer;
                   3038: }
                   3039:     
1.8       www      3040: # -------------------------------------------------------------- Replicate file
                   3041: 
                   3042: sub repcopy {
                   3043:     my $filename=shift;
1.23      www      3044:     $filename=~s/\/+/\//g;
1.1142    raeburn  3045:     my $londocroot = $perlvar{'lonDocRoot'};
                   3046:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  3047:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  3048:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   3049: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 3050: 	return &repcopy_userfile($filename);
                   3051:     }
1.532     albertel 3052:     $filename=~s/[\n\r]//g;
1.8       www      3053:     my $transname="$filename.in.transfer";
1.828     www      3054: # FIXME: this should flock
1.607     raeburn  3055:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      3056:     my $remoteurl=subscribe($filename);
1.64      www      3057:     if ($remoteurl =~ /^con_lost by/) {
                   3058: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3059:            return 'unavailable';
1.8       www      3060:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 3061: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  3062: 	   return 'not_found';
1.64      www      3063:     } elsif ($remoteurl =~ /^rejected by/) {
                   3064: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  3065:            return 'forbidden';
1.20      www      3066:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  3067:            return 'ok';
1.8       www      3068:     } else {
1.290     www      3069:         my $author=$filename;
                   3070:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   3071:         my ($udom,$uname)=split(/\//,$author);
                   3072:         my $home=homeserver($uname,$udom);
                   3073:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      3074:            my @parts=split(/\//,$filename);
                   3075:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  3076:            if ($path ne "$londocroot/res") {
1.8       www      3077:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  3078: 	       return 'bad_request';
1.8       www      3079:            }
                   3080:            my $count;
                   3081:            for ($count=5;$count<$#parts;$count++) {
                   3082:                $path.="/$parts[$count]";
                   3083:                if ((-e $path)!=1) {
                   3084: 		   mkdir($path,0777);
                   3085:                }
                   3086:            }
                   3087:            my $request=new HTTP::Request('GET',"$remoteurl");
1.1345    raeburn  3088:            my $response;
                   3089:            if ($remoteurl =~ m{/raw/}) {
                   3090:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',0,1);
                   3091:            } else {
                   3092:                $response=&LONCAPA::LWPReq::makerequest($home,$request,$transname,\%perlvar,'',1);
                   3093:            }
1.8       www      3094:            if ($response->is_error()) {
                   3095: 	       unlink($transname);
                   3096:                my $message=$response->status_line;
1.672     albertel 3097:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      3098:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  3099:                return 'unavailable';
1.8       www      3100:            } else {
1.16      www      3101: 	       if ($remoteurl!~/\.meta$/) {
                   3102:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1.1345    raeburn  3103:                   my $mresponse;
                   3104:                   if ($remoteurl =~ m{/raw/}) {
                   3105:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',0,1);
                   3106:                   } else {
                   3107:                       $mresponse = &LONCAPA::LWPReq::makerequest($home,$mrequest,$filename.'.meta',\%perlvar,'',1);
                   3108:                   }
1.16      www      3109:                   if ($mresponse->is_error()) {
                   3110: 		      unlink($filename.'.meta');
                   3111:                       &logthis(
1.672     albertel 3112:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      3113:                   }
                   3114: 	       }
1.8       www      3115:                rename($transname,$filename);
1.607     raeburn  3116:                return 'ok';
1.8       www      3117:            }
1.290     www      3118:        }
1.8       www      3119:     }
1.330     www      3120: }
                   3121: 
                   3122: # ------------------------------------------------ Get server side include body
                   3123: sub ssi_body {
1.381     albertel 3124:     my ($filelink,%form)=@_;
1.606     matthew  3125:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   3126:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   3127:     }
1.953     www      3128:     my $output='';
                   3129:     my $response;
1.980     raeburn  3130:     if ($filelink=~/^https?\:/) {
1.954     raeburn  3131:        ($output,$response)=&externalssi($filelink);
1.953     www      3132:     } else {
1.1004    droeschl 3133:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   3134:        $filelink .= 'inhibitmenu=yes';
1.953     www      3135:        ($output,$response)=&ssi($filelink,%form);
                   3136:     }
1.778     albertel 3137:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 3138:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 3139:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      3140:     if (wantarray) {
                   3141:         return ($output, $response);
                   3142:     } else {
                   3143:         return $output;
                   3144:     }
1.8       www      3145: }
                   3146: 
1.15      www      3147: # --------------------------------------------------------- Server Side Include
                   3148: 
1.782     albertel 3149: sub absolute_url {
                   3150:     my ($host_name) = @_;
                   3151:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   3152:     if ($host_name eq '') {
                   3153: 	$host_name = $ENV{'SERVER_NAME'};
                   3154:     }
                   3155:     return $protocol.$host_name;
                   3156: }
                   3157: 
1.942     foxr     3158: #
                   3159: #   Server side include.
                   3160: # Parameters:
                   3161: #  fn     Possibly encrypted resource name/id.
                   3162: #  form   Hash that describes how the rendering should be done
                   3163: #         and other things.
1.944     foxr     3164: # Returns:
1.950     raeburn  3165: #   Scalar context: The content of the response.
                   3166: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     3167: #     
1.15      www      3168: sub ssi {
                   3169: 
1.944     foxr     3170:     my ($fn,%form)=@_;
1.23      www      3171:     my $request;
1.711     albertel 3172: 
                   3173:     $form{'no_update_last_known'}=1;
1.895     albertel 3174:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      3175:     if (%form) {
1.782     albertel 3176:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1272    droeschl 3177:       $request->content(join('&',map { 
                   3178:             my $name = escape($_);
                   3179:             "$name=" . ( ref($form{$_}) eq 'ARRAY' 
                   3180:             ? join("&$name=", map {escape($_) } @{$form{$_}}) 
                   3181:             : &escape($form{$_}) );    
                   3182:         } keys(%form)));
1.23      www      3183:     } else {
1.782     albertel 3184:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      3185:     }
                   3186: 
1.15      www      3187:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1345    raeburn  3188:     my $lonhost = $perlvar{'lonHostID'};
                   3189:     my $response= &LONCAPA::LWPReq::makerequest($lonhost,$request,'',\%perlvar);
1.1182    foxr     3190: 
1.944     foxr     3191:     if (wantarray) {
1.1345    raeburn  3192: 	return ($response->content, $response);
1.944     foxr     3193:     } else {
1.1345    raeburn  3194: 	return $response->content;
1.942     foxr     3195:     }
1.324     www      3196: }
                   3197: 
                   3198: sub externalssi {
                   3199:     my ($url)=@_;
                   3200:     my $request=new HTTP::Request('GET',$url);
1.1345    raeburn  3201:     my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar);
1.954     raeburn  3202:     if (wantarray) {
                   3203:         return ($response->content, $response);
                   3204:     } else {
                   3205:         return $response->content;
                   3206:     }
1.15      www      3207: }
1.254     www      3208: 
1.1354    raeburn  3209: 
                   3210: # If the local copy of a replicated resource is outdated, trigger a  
                   3211: # connection from the homeserver to flush the delayed queue. If no update 
                   3212: # happens, remove local copies of outdated resource (and corresponding
                   3213: # metadata file).
                   3214: 
1.1352    raeburn  3215: sub remove_stale_resfile {
                   3216:     my ($url) = @_;
1.1354    raeburn  3217:     my $removed;
1.1352    raeburn  3218:     if ($url=~m{^/res/($match_domain)/($match_username)/}) {
                   3219:         my $audom = $1;
                   3220:         my $auname = $2;
1.1353    raeburn  3221:         unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
1.1352    raeburn  3222:             my $homeserver = &homeserver($auname,$audom);
                   3223:             unless (($homeserver eq 'no_host') ||
                   3224:                     (grep { $_ eq $homeserver } &current_machine_ids())) {
                   3225:                 my $fname = &filelocation('',$url);
                   3226:                 if (-e $fname) {
                   3227:                     my $protocol = $protocol{$homeserver};
                   3228:                     $protocol = 'http' if ($protocol ne 'https');
                   3229:                     my $hostname = &hostname($homeserver);
                   3230:                     if ($hostname) {
                   3231:                         my $uri = &declutter($url);
                   3232:                         my $request=new HTTP::Request('HEAD',$protocol.'://'.$hostname.'/raw/'.$uri);
                   3233:                         my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,5,0,1);
                   3234:                         if ($response->is_success()) {
                   3235:                             my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
                   3236:                             my $locmodtime = (stat($fname))[9];
                   3237:                             if ($locmodtime < $remmodtime) {
1.1354    raeburn  3238:                                 my $stale;
                   3239:                                 my $answer = &reply('pong',$homeserver);
                   3240:                                 if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
                   3241:                                     sleep(0.2);
                   3242:                                     $locmodtime = (stat($fname))[9];
                   3243:                                     if ($locmodtime < $remmodtime) {
                   3244:                                         my $posstransfer = $fname.'.in.transfer';
                   3245:                                         if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
                   3246:                                             $removed = 1;
                   3247:                                         } else {
                   3248:                                             $stale = 1;
                   3249:                                         }
                   3250:                                     } else {
                   3251:                                         $removed = 1;
                   3252:                                     }
                   3253:                                 } else {
                   3254:                                     $stale = 1;
                   3255:                                 }
                   3256:                                 if ($stale) {
                   3257:                                     unlink($fname);
                   3258:                                     if ($uri!~/\.meta$/) {
                   3259:                                         unlink($fname.'.meta');
                   3260:                                     }
                   3261:                                     &reply("unsub:$fname",$homeserver);
                   3262:                                     $removed = 1;
1.1352    raeburn  3263:                                 }
                   3264:                             }
                   3265:                         }
                   3266:                     }
                   3267:                 }
                   3268:             }
                   3269:         }
                   3270:     }
1.1354    raeburn  3271:     return $removed;
1.1352    raeburn  3272: }
                   3273: 
1.492     albertel 3274: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   3275: 
                   3276: sub allowuploaded {
                   3277:     my ($srcurl,$url)=@_;
                   3278:     $url=&clutter(&declutter($url));
                   3279:     my $dir=$url;
                   3280:     $dir=~s/\/[^\/]+$//;
                   3281:     my %httpref=();
                   3282:     my $httpurl=&hreflocation('',$url);
                   3283:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  3284:     &Apache::lonnet::appenv(\%httpref);
1.254     www      3285: }
1.477     raeburn  3286: 
1.1193    raeburn  3287: #
                   3288: # Determine if the current user should be able to edit a particular resource,
                   3289: # when viewing in course context.
                   3290: # (a) When viewing resource used to determine if "Edit" item is included in 
                   3291: #     Functions.
                   3292: # (b) When displaying folder contents in course editor, used to determine if
                   3293: #     "Edit" link will be displayed alongside resource.
                   3294: #
1.1196    raeburn  3295: #  input: six args -- filename (decluttered), course number, course domain,
                   3296: #                   url, symb (if registered) and group (if this is a group
                   3297: #                   item -- e.g., bulletin board, group page etc.).
                   3298: #  output: array of five scalars -- 
1.1193    raeburn  3299: #          $cfile -- url for file editing if editable on current server
                   3300: #          $home -- homeserver of resource (i.e., for author if published,
                   3301: #                                           or course if uploaded.).
                   3302: #          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  3303: #          $forceedit -- 1 if icon/link should be to go to edit mode 
                   3304: #          $forceview -- 1 if icon/link should be to go to view mode
1.1193    raeburn  3305: #
                   3306: 
                   3307: sub can_edit_resource {
1.1194    raeburn  3308:     my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
                   3309:     my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
                   3310: #
                   3311: # For aboutme pages user can only edit his/her own.
                   3312: #
1.1199    raeburn  3313:     if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
1.1194    raeburn  3314:         my ($sdom,$sname) = ($1,$2);
                   3315:         if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
                   3316:             $home = $env{'user.home'};
                   3317:             $cfile = $resurl;
                   3318:             if ($env{'form.forceedit'}) {
                   3319:                 $forceview = 1;
                   3320:             } else {
                   3321:                 $forceedit = 1;
                   3322:             }
                   3323:             return ($cfile,$home,$switchserver,$forceedit,$forceview);
                   3324:         } else {
                   3325:             return;
                   3326:         }
                   3327:     }
                   3328: 
                   3329:     if ($env{'request.course.id'}) {
                   3330:         my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
                   3331:         if ($group ne '') {
                   3332: # if this is a group homepage or group bulletin board, check group privs
                   3333:             my $allowed = 0;
1.1197    raeburn  3334:             if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
                   3335:                 if ((&allowed('mdg',$env{'request.course.id'}.
1.1198    raeburn  3336:                               ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
1.1194    raeburn  3337:                         (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
                   3338:                     $allowed = 1;
                   3339:                 }
1.1197    raeburn  3340:             } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
                   3341:                 if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
                   3342:                         (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
1.1194    raeburn  3343:                     $allowed = 1;
                   3344:                 }
                   3345:             }
                   3346:             if ($allowed) {
                   3347:                 $home=&homeserver($cnum,$cdom);
                   3348:                 if ($env{'form.forceedit'}) {
                   3349:                     $forceview = 1;
                   3350:                 } else {
                   3351:                     $forceedit = 1;
                   3352:                 }
                   3353:                 $cfile = $resurl;
                   3354:             } else {
                   3355:                 return;
                   3356:             }
                   3357:         } else {
1.1208    raeburn  3358:             if ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3359:                 unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
                   3360:                     return;
                   3361:                 }
                   3362:             } elsif (!$crsedit) {
1.1194    raeburn  3363: #
                   3364: # No edit allowed where CC has switched to student role.
                   3365: #
                   3366:                 return;
                   3367:             }
                   3368:         }
                   3369:     }
                   3370: 
1.1193    raeburn  3371:     if ($file ne '') {
                   3372:         if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
1.1194    raeburn  3373:             if (&is_course_upload($file,$cnum,$cdom)) {
                   3374:                 $uploaded = 1;
                   3375:                 $incourse = 1;
1.1193    raeburn  3376:                 if ($file =~/\.(htm|html|css|js|txt)$/) {
                   3377:                     $cfile = &hreflocation('',$file);
1.1201    raeburn  3378:                     if ($env{'form.forceedit'}) {
                   3379:                         $forceview = 1;
                   3380:                     } else {
                   3381:                         $forceedit = 1;
                   3382:                     }
1.1194    raeburn  3383:                 }
                   3384:             } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
                   3385:                 $incourse = 1;
                   3386:                 if ($env{'form.forceedit'}) {
                   3387:                     $forceview = 1;
                   3388:                 } else {
                   3389:                     $forceedit = 1;
                   3390:                 }
                   3391:                 $cfile = $resurl;
                   3392:             } elsif (($resurl ne '') && (&is_on_map($resurl))) { 
                   3393:                 if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
                   3394:                     $incourse = 1;
                   3395:                     if ($env{'form.forceedit'}) {
                   3396:                         $forceview = 1;
                   3397:                     } else {
                   3398:                         $forceedit = 1;
                   3399:                     }
                   3400:                     $cfile = $resurl;
1.1199    raeburn  3401:                 } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
1.1194    raeburn  3402:                     $incourse = 1;
                   3403:                     $cfile = $resurl.'/smpedit';
1.1199    raeburn  3404:                 } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
1.1194    raeburn  3405:                     $incourse = 1;
1.1199    raeburn  3406:                     if ($env{'form.forceedit'}) {
                   3407:                         $forceview = 1;
                   3408:                     } else {
                   3409:                         $forceedit = 1;
                   3410:                     }
                   3411:                     $cfile = $resurl;
1.1343    raeburn  3412:                 } elsif ($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3413:                     $incourse = 1;
                   3414:                     if ($env{'form.forceedit'}) {
                   3415:                         $forceview = 1;
                   3416:                     } else {
                   3417:                         $forceedit = 1;
                   3418:                     }
                   3419:                     $cfile = $resurl;
1.1208    raeburn  3420:                 } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3421:                     $incourse = 1;
                   3422:                     if ($env{'form.forceedit'}) {
                   3423:                         $forceview = 1;
                   3424:                     } else {
                   3425:                         $forceedit = 1;
                   3426:                     }
                   3427:                     $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1194    raeburn  3428:                 }
                   3429:             } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
                   3430:                 my $template = '/res/lib/templates/simpleproblem.problem';
                   3431:                 if (&is_on_map($template)) { 
                   3432:                     $incourse = 1;
                   3433:                     $forceview = 1;
                   3434:                     $cfile = $template;
1.1193    raeburn  3435:                 }
1.1199    raeburn  3436:             } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
                   3437:                     $incourse = 1;
                   3438:                     if ($env{'form.forceedit'}) {
                   3439:                         $forceview = 1;
                   3440:                     } else {
                   3441:                         $forceedit = 1;
                   3442:                     }
                   3443:                     $cfile = $resurl;
1.1343    raeburn  3444:             } elsif (($resurl =~ m{^/adm/wrapper/adm/$cdom/$cnum/\d+/ext\.tool$}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
1.1298    raeburn  3445:                 $incourse = 1;
                   3446:                 if ($env{'form.forceedit'}) {
                   3447:                     $forceview = 1;
                   3448:                 } else {
                   3449:                     $forceedit = 1;
                   3450:                 }
                   3451:                 $cfile = $resurl;
1.1199    raeburn  3452:             } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
                   3453:                 $incourse = 1;
                   3454:                 $forceview = 1;
                   3455:                 if ($symb) {
                   3456:                     my ($map,$id,$res)=&decode_symb($symb);
                   3457:                     $env{'request.symb'} = $symb;
                   3458:                     $cfile = &clutter($res);
                   3459:                 } else {
                   3460:                     $cfile = $env{'form.suppurl'};
1.1298    raeburn  3461:                     my $escfile = &unescape($cfile);
1.1343    raeburn  3462:                     if ($escfile =~ m{^/adm/$cdom/$cnum/\d+/ext\.tool$}) {
1.1298    raeburn  3463:                         $cfile = '/adm/wrapper'.$escfile;
                   3464:                     } else {
                   3465:                         $escfile =~ s{^http://}{};
                   3466:                         $cfile = &escape("/adm/wrapper/ext/$escfile");
                   3467:                     }
1.1199    raeburn  3468:                 }
1.1234    raeburn  3469:             } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
                   3470:                 if ($env{'form.forceedit'}) {
                   3471:                     $forceview = 1;
                   3472:                 } else {
                   3473:                     $forceedit = 1;
                   3474:                 }
                   3475:                 $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
1.1193    raeburn  3476:             }
                   3477:         }
1.1194    raeburn  3478:         if ($uploaded || $incourse) {
                   3479:             $home=&homeserver($cnum,$cdom);
1.1207    raeburn  3480:         } elsif ($file !~ m{/$}) {
1.1193    raeburn  3481:             $file=~s{^(priv/$match_domain/$match_username)}{/$1};
                   3482:             $file=~s{^($match_domain/$match_username)}{/priv/$1};
                   3483:             # Check that the user has permission to edit this resource
                   3484:             my $setpriv = 1;
                   3485:             my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
                   3486:             if (defined($cfudom)) {
                   3487:                 $home=&homeserver($cfuname,$cfudom);
                   3488:                 $cfile=$file;
                   3489:             }
                   3490:         }
1.1194    raeburn  3491:         if (($cfile ne '') && (!$incourse || $uploaded) && 
                   3492:             (($home ne '') && ($home ne 'no_host'))) {
1.1193    raeburn  3493:             my @ids=&current_machine_ids();
                   3494:             unless (grep(/^\Q$home\E$/,@ids)) {
                   3495:                 $switchserver=1;
                   3496:             }
                   3497:         }
                   3498:     }
1.1194    raeburn  3499:     return ($cfile,$home,$switchserver,$forceedit,$forceview);
1.1193    raeburn  3500: }
                   3501: 
                   3502: sub is_course_upload {
                   3503:     my ($file,$cnum,$cdom) = @_;
                   3504:     my $uploadpath = &LONCAPA::propath($cdom,$cnum);
                   3505:     $uploadpath =~ s{^\/}{};
1.1201    raeburn  3506:     if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
                   3507:         ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
1.1193    raeburn  3508:         return 1;
                   3509:     }
                   3510:     return;
                   3511: }
                   3512: 
1.1194    raeburn  3513: sub in_course {
1.1195    raeburn  3514:     my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
                   3515:     if ($hideprivileged) {
                   3516:         my $skipuser;
1.1219    raeburn  3517:         my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   3518:         my @possdoms = ($cdom);  
                   3519:         if ($coursehash{'checkforpriv'}) { 
                   3520:             push(@possdoms,split(/,/,$coursehash{'checkforpriv'})); 
                   3521:         }
                   3522:         if (&privileged($uname,$udom,\@possdoms)) {
1.1195    raeburn  3523:             $skipuser = 1;
                   3524:             if ($coursehash{'nothideprivileged'}) {
                   3525:                 foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3526:                     my $user;
                   3527:                     if ($item =~ /:/) {
                   3528:                         $user = $item;
                   3529:                     } else {
                   3530:                         $user = join(':',split(/[\@]/,$item));
                   3531:                     }
                   3532:                     if ($user eq $uname.':'.$udom) {
                   3533:                         undef($skipuser);
                   3534:                         last;
                   3535:                     }
                   3536:                 }
                   3537:             }
                   3538:             if ($skipuser) {
                   3539:                 return 0;
                   3540:             }
                   3541:         }
                   3542:     }
1.1194    raeburn  3543:     $type ||= 'any';
                   3544:     if (!defined($cdom) || !defined($cnum)) {
                   3545:         my $cid  = $env{'request.course.id'};
                   3546:         $cdom = $env{'course.'.$cid.'.domain'};
                   3547:         $cnum = $env{'course.'.$cid.'.num'};
                   3548:     }
                   3549:     my $typesref;
1.1195    raeburn  3550:     if (($type eq 'any') || ($type eq 'all')) {
1.1194    raeburn  3551:         $typesref = ['active','previous','future'];
                   3552:     } elsif ($type eq 'previous' || $type eq 'future') {
                   3553:         $typesref = [$type];
                   3554:     }
                   3555:     my %roles = &get_my_roles($uname,$udom,'userroles',
                   3556:                               $typesref,undef,[$cdom]);
                   3557:     my ($tmp) = keys(%roles);
                   3558:     return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
                   3559:     my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
                   3560:     if (@course_roles > 0) {
                   3561:         return 1;
                   3562:     }
                   3563:     return 0;
                   3564: }
                   3565: 
1.478     albertel 3566: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 3567: # input: action, courseID, current domain, intended
1.637     raeburn  3568: #        path to file, source of file, instruction to parse file for objects,
                   3569: #        ref to hash for embedded objects,
                   3570: #        ref to hash for codebase of java objects.
1.1095    raeburn  3571: #        reference to scalar to accommodate mime type determined
                   3572: #          from File::MMagic if $parser = parse.
1.637     raeburn  3573: #
1.485     raeburn  3574: # output: url to file (if action was uploaddoc), 
                   3575: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  3576: #
1.478     albertel 3577: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   3578: # course.
1.477     raeburn  3579: #
1.478     albertel 3580: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3581: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   3582: #          course's home server.
1.477     raeburn  3583: #
1.478     albertel 3584: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   3585: #          be copied from $source (current location) to 
                   3586: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3587: #         and will then be copied to
                   3588: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   3589: #         course's home server.
1.485     raeburn  3590: #
1.481     raeburn  3591: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 3592: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  3593: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   3594: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   3595: #         in course's home server.
1.637     raeburn  3596: #
1.477     raeburn  3597: 
                   3598: sub process_coursefile {
1.1095    raeburn  3599:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   3600:         $mimetype)=@_;
1.477     raeburn  3601:     my $fetchresult;
1.638     albertel 3602:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  3603:     if ($action eq 'propagate') {
1.638     albertel 3604:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   3605: 			     $home);
1.481     raeburn  3606:     } else {
1.477     raeburn  3607:         my $fpath = '';
                   3608:         my $fname = $file;
1.478     albertel 3609:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  3610:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  3611:         my $filepath = &build_filepath($fpath);
1.481     raeburn  3612:         if ($action eq 'copy') {
                   3613:             if ($source eq '') {
                   3614:                 $fetchresult = 'no source file';
                   3615:                 return $fetchresult;
                   3616:             } else {
                   3617:                 my $destination = $filepath.'/'.$fname;
                   3618:                 rename($source,$destination);
                   3619:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3620:                                  $home);
1.481     raeburn  3621:             }
                   3622:         } elsif ($action eq 'uploaddoc') {
1.1359    raeburn  3623:             open(my $fh,'>',$filepath.'/'.$fname);
1.620     albertel 3624:             print $fh $env{'form.'.$source};
1.481     raeburn  3625:             close($fh);
1.637     raeburn  3626:             if ($parser eq 'parse') {
1.1024    raeburn  3627:                 my $mm = new File::MMagic;
1.1095    raeburn  3628:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   3629:                 if ($type eq 'text/html') {
1.1024    raeburn  3630:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   3631:                     unless ($parse_result eq 'ok') {
                   3632:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   3633:                     }
1.637     raeburn  3634:                 }
1.1095    raeburn  3635:                 if (ref($mimetype)) {
                   3636:                     $$mimetype = $type;
                   3637:                 } 
1.637     raeburn  3638:             }
1.477     raeburn  3639:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3640:                                  $home);
1.481     raeburn  3641:             if ($fetchresult eq 'ok') {
                   3642:                 return '/uploaded/'.$fpath.'/'.$fname;
                   3643:             } else {
                   3644:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3645:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  3646:                 return '/adm/notfound.html';
                   3647:             }
1.477     raeburn  3648:         }
                   3649:     }
1.485     raeburn  3650:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  3651:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 3652:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  3653:     }
                   3654:     return $fetchresult;
                   3655: }
                   3656: 
1.637     raeburn  3657: sub build_filepath {
                   3658:     my ($fpath) = @_;
                   3659:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   3660:     unless ($fpath eq '') {
                   3661:         my @parts=split('/',$fpath);
                   3662:         foreach my $part (@parts) {
                   3663:             $filepath.= '/'.$part;
                   3664:             if ((-e $filepath)!=1) {
                   3665:                 mkdir($filepath,0777);
                   3666:             }
                   3667:         }
                   3668:     }
                   3669:     return $filepath;
                   3670: }
                   3671: 
                   3672: sub store_edited_file {
1.638     albertel 3673:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  3674:     my $file = $primary_url;
                   3675:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   3676:     my $fpath = '';
                   3677:     my $fname = $file;
                   3678:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   3679:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   3680:     my $filepath = &build_filepath($fpath);
1.1359    raeburn  3681:     open(my $fh,'>',$filepath.'/'.$fname);
1.637     raeburn  3682:     print $fh $content;
                   3683:     close($fh);
1.638     albertel 3684:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  3685:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 3686: 			  $home);
1.637     raeburn  3687:     if ($$fetchresult eq 'ok') {
                   3688:         return '/uploaded/'.$fpath.'/'.$fname;
                   3689:     } else {
1.638     albertel 3690:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   3691: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  3692:         return '/adm/notfound.html';
                   3693:     }
                   3694: }
                   3695: 
1.531     albertel 3696: sub clean_filename {
1.831     albertel 3697:     my ($fname,$args)=@_;
1.315     www      3698: # Replace Windows backslashes by forward slashes
1.257     www      3699:     $fname=~s/\\/\//g;
1.831     albertel 3700:     if (!$args->{'keep_path'}) {
                   3701:         # Get rid of everything but the actual filename
                   3702: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   3703:     }
1.315     www      3704: # Replace spaces by underscores
                   3705:     $fname=~s/\s+/\_/g;
                   3706: # Replace all other weird characters by nothing
1.831     albertel 3707:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 3708: # Replace all .\d. sequences with _\d. so they no longer look like version
                   3709: # numbers
                   3710:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 3711:     return $fname;
                   3712: }
1.1051    raeburn  3713: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   3714: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   3715: # image with the same aspect ratio as the original, but with dimensions which do 
                   3716: # not exceed $resizewidth and $resizeheight.
                   3717:  
1.984     neumanie 3718: sub resizeImage {
1.1051    raeburn  3719:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   3720:     my $ima = Image::Magick->new;
                   3721:     my $resized;
                   3722:     if (-e $img_path) {
                   3723:         $ima->Read($img_path);
                   3724:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   3725:             my $width = $ima->Get('width');
                   3726:             my $height = $ima->Get('height');
                   3727:             if ($width > $resizewidth) {
                   3728: 	        my $factor = $width/$resizewidth;
                   3729:                 my $newheight = $height/$factor;
                   3730:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   3731:                 $resized = 1;
                   3732:             }
                   3733:         }
                   3734:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   3735:             my $width = $ima->Get('width');
                   3736:             my $height = $ima->Get('height');
                   3737:             if ($height > $resizeheight) {
                   3738:                 my $factor = $height/$resizeheight;
                   3739:                 my $newwidth = $width/$factor;
                   3740:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   3741:                 $resized = 1;
                   3742:             }
                   3743:         }
                   3744:         if ($resized) {
                   3745:             $ima->Write($img_path);
                   3746:         }
                   3747:     }
                   3748:     return;
1.977     amueller 3749: }
                   3750: 
1.608     albertel 3751: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 3752: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  3753: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  3754: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   3755: #                                    canceloverwrite, or ''. 
                   3756: #                   if 'coursedoc': upload to the current course
                   3757: #                   if 'existingfile': write file to tmp/overwrites directory 
                   3758: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   3759: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 3760: #        $subdir - directory in userfile to store the file into
1.858     raeburn  3761: #        $parser - instruction to parse file for objects ($parser = parse)    
                   3762: #        $allfiles - reference to hash for embedded objects
                   3763: #        $codebase - reference to hash for codebase of java objects
                   3764: #        $desuname - username for permanent storage of uploaded file
                   3765: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  3766: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   3767: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  3768: #        $resizewidth - width (pixels) to which to resize uploaded image
                   3769: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  3770: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  3771: #                    from File::MMagic.
1.858     raeburn  3772: # 
1.686     albertel 3773: # output: url of file in userspace, or error: <message> 
                   3774: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 3775: 
1.531     albertel 3776: sub userfileupload {
1.1090    raeburn  3777:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  3778:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 3779:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 3780:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 3781:     $fname=&clean_filename($fname);
1.1090    raeburn  3782:     # See if there is anything left
1.257     www      3783:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  3784:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   3785:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   3786:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   3787:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  3788:         my $now = time;
1.1090    raeburn  3789:         my $filepath;
1.1095    raeburn  3790:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  3791:              $filepath = 'tmp/helprequests/'.$now;
                   3792:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   3793:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   3794:                          '_'.$env{'user.domain'}.'/pending';
                   3795:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   3796:             my ($docuname,$docudom);
1.1350    raeburn  3797:             if ($destudom =~ /^$match_domain$/) {
1.1090    raeburn  3798:                 $docudom = $destudom;
                   3799:             } else {
                   3800:                 $docudom = $env{'user.domain'};
                   3801:             }
1.1350    raeburn  3802:             if ($destuname =~ /^$match_username$/) {
1.1090    raeburn  3803:                 $docuname = $destuname;
                   3804:             } else {
                   3805:                 $docuname = $env{'user.name'};
                   3806:             }
                   3807:             if (exists($env{'form.group'})) {
                   3808:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3809:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3810:             }
                   3811:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   3812:             if ($context eq 'canceloverwrite') {
                   3813:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   3814:                 if (-e  $tempfile) {
                   3815:                     my @info = stat($tempfile);
                   3816:                     if ($info[9] eq $env{'form.timestamp'}) {
                   3817:                         unlink($tempfile);
                   3818:                     }
                   3819:                 }
                   3820:                 return;
1.523     raeburn  3821:             }
                   3822:         }
1.1090    raeburn  3823:         # Create the directory if not present
1.741     raeburn  3824:         my @parts=split(/\//,$filepath);
                   3825:         my $fullpath = $perlvar{'lonDaemons'};
                   3826:         for (my $i=0;$i<@parts;$i++) {
                   3827:             $fullpath .= '/'.$parts[$i];
                   3828:             if ((-e $fullpath)!=1) {
                   3829:                 mkdir($fullpath,0777);
                   3830:             }
                   3831:         }
1.1359    raeburn  3832:         open(my $fh,'>',$fullpath.'/'.$fname);
1.741     raeburn  3833:         print $fh $env{'form.'.$formname};
                   3834:         close($fh);
1.1090    raeburn  3835:         if ($context eq 'existingfile') {
                   3836:             my @info = stat($fullpath.'/'.$fname);
                   3837:             return ($fullpath.'/'.$fname,$info[9]);
                   3838:         } else {
                   3839:             return $fullpath.'/'.$fname;
                   3840:         }
1.523     raeburn  3841:     }
1.995     raeburn  3842:     if ($subdir eq 'scantron') {
                   3843:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  3844:     } else {
1.995     raeburn  3845:         $fname="$subdir/$fname";
                   3846:     }
1.1090    raeburn  3847:     if ($context eq 'coursedoc') {
1.638     albertel 3848: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3849: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  3850:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 3851:             return &finishuserfileupload($docuname,$docudom,
                   3852: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  3853: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  3854:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  3855:         } else {
1.1218    raeburn  3856:             if ($env{'form.folder'}) {
                   3857:                 $fname=$env{'form.folder'}.'/'.$fname;
                   3858:             }
1.638     albertel 3859:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   3860: 				       $fname,$formname,$parser,
1.1095    raeburn  3861: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  3862:         }
1.719     banghart 3863:     } elsif (defined($destuname)) {
                   3864:         my $docuname=$destuname;
                   3865:         my $docudom=$destudom;
1.860     raeburn  3866: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3867: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3868:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3869:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3870:     } else {
1.638     albertel 3871:         my $docuname=$env{'user.name'};
                   3872:         my $docudom=$env{'user.domain'};
1.1220    raeburn  3873:         if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
1.714     raeburn  3874:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   3875:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   3876:         }
1.860     raeburn  3877: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   3878: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  3879:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  3880:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      3881:     }
1.271     www      3882: }
                   3883: 
                   3884: sub finishuserfileupload {
1.860     raeburn  3885:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  3886:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  3887:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      3888:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 3889:   
1.860     raeburn  3890:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 3891:     $file=$fname;
                   3892:     if ($fname=~m|/|) {
                   3893:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   3894: 	$path.=$fnamepath.'/';
                   3895:     }
1.259     www      3896:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      3897:     my $count;
                   3898:     for ($count=4;$count<=$#parts;$count++) {
                   3899:         $filepath.="/$parts[$count]";
                   3900:         if ((-e $filepath)!=1) {
                   3901: 	    mkdir($filepath,0777);
                   3902:         }
                   3903:     }
1.984     neumanie 3904: 
1.258     www      3905: # Save the file
                   3906:     {
1.1359    raeburn  3907: 	if (!open(FH,'>',$filepath.'/'.$file)) {
1.701     albertel 3908: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   3909: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   3910: 	    return '/adm/notfound.html';
                   3911: 	}
1.1090    raeburn  3912:         if ($context eq 'overwrite') {
1.1117    foxr     3913:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  3914:             my $target = $filepath.'/'.$file;
                   3915:             if (-e $source) {
                   3916:                 my @info = stat($source);
                   3917:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   3918:                     unless (&File::Copy::move($source,$target)) {
                   3919:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   3920:                         return "Moving from $source failed";
                   3921:                     }
                   3922:                 } else {
                   3923:                     return "Temporary file: $source had unexpected date/time for last modification";
                   3924:                 }
                   3925:             } else {
                   3926:                 return "Temporary file: $source missing";
                   3927:             }
                   3928:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 3929: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   3930: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   3931: 	    return '/adm/notfound.html';
                   3932: 	}
1.570     albertel 3933: 	close(FH);
1.1051    raeburn  3934:         if ($resizewidth && $resizeheight) {
                   3935:             my $mm = new File::MMagic;
                   3936:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   3937:             if ($mime_type =~ m{^image/}) {
                   3938: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   3939:             }  
1.977     amueller 3940: 	}
1.258     www      3941:     }
1.1152    raeburn  3942:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   3943:         if (ref($mimetype)) {
                   3944:             if ($$mimetype eq '') {
                   3945:                 my $mm = new File::MMagic;
                   3946:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3947:                 $$mimetype = $type;
                   3948:             }
                   3949:         }
                   3950:     }
1.637     raeburn  3951:     if ($parser eq 'parse') {
1.1152    raeburn  3952:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3953:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3954:                                                        $allfiles,$codebase);
                   3955:             unless ($parse_result eq 'ok') {
                   3956:                 &logthis('Failed to parse '.$filepath.$file.
                   3957: 	   	         ' for embedded media: '.$parse_result); 
                   3958:             }
1.637     raeburn  3959:         }
                   3960:     }
1.860     raeburn  3961:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3962:         my $input = $filepath.'/'.$file;
                   3963:         my $output = $filepath.'/'.'tn-'.$file;
                   3964:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
1.1359    raeburn  3965:         my @args = ('convert','-sample',$thumbsize,$input,$output);
                   3966:         system({$args[0]} @args);
1.860     raeburn  3967:         if (-e $filepath.'/'.'tn-'.$file) {
                   3968:             $fetchthumb  = 1; 
                   3969:         }
                   3970:     }
1.858     raeburn  3971:  
1.259     www      3972: # Notify homeserver to grep it
                   3973: #
1.984     neumanie 3974:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3975:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3976:     if ($fetchresult eq 'ok') {
1.860     raeburn  3977:         if ($fetchthumb) {
                   3978:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3979:             if ($thumbresult ne 'ok') {
                   3980:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3981:                          $docuhome.': '.$thumbresult);
                   3982:             }
                   3983:         }
1.259     www      3984: #
1.258     www      3985: # Return the URL to it
1.494     albertel 3986:         return '/uploaded/'.$path.$file;
1.263     www      3987:     } else {
1.494     albertel 3988:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3989: 		 ': '.$fetchresult);
1.263     www      3990:         return '/adm/notfound.html';
1.858     raeburn  3991:     }
1.493     albertel 3992: }
                   3993: 
1.637     raeburn  3994: sub extract_embedded_items {
1.961     raeburn  3995:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3996:     my @state = ();
1.1164    raeburn  3997:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3998:     my %javafiles = (
                   3999:                       codebase => '',
                   4000:                       code => '',
                   4001:                       archive => ''
                   4002:                     );
                   4003:     my %mediafiles = (
                   4004:                       src => '',
                   4005:                       movie => '',
                   4006:                      );
1.648     raeburn  4007:     my $p;
                   4008:     if ($content) {
                   4009:         $p = HTML::LCParser->new($content);
                   4010:     } else {
1.961     raeburn  4011:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  4012:     }
1.641     albertel 4013:     while (my $t=$p->get_token()) {
1.640     albertel 4014: 	if ($t->[0] eq 'S') {
                   4015: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 4016: 	    push(@state, $tagname);
1.648     raeburn  4017:             if (lc($tagname) eq 'allow') {
                   4018:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   4019:             }
1.640     albertel 4020: 	    if (lc($tagname) eq 'img') {
                   4021: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   4022: 	    }
1.886     albertel 4023: 	    if (lc($tagname) eq 'a') {
1.1222    raeburn  4024:                 unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
1.1221    raeburn  4025:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4026:                 }
1.886     albertel 4027: 	    }
1.645     raeburn  4028:             if (lc($tagname) eq 'script') {
1.1164    raeburn  4029:                 my $src;
1.645     raeburn  4030:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   4031:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   4032:                 } else {
1.1164    raeburn  4033:                     if ($attr->{'src'} ne '') {
                   4034:                         $src = $attr->{'src'};
                   4035:                         &add_filetype($allfiles,$src,'src');
                   4036:                     }
                   4037:                 }
                   4038:                 my $text = $p->get_trimmed_text();
                   4039:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   4040:                     my @swfargs = split(/,/,$1);
                   4041:                     foreach my $item (@swfargs) {
                   4042:                         $item =~ s/["']//g;
                   4043:                         $item =~ s/^\s+//;
                   4044:                         $item =~ s/\s+$//;
                   4045:                     }
                   4046:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   4047:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   4048:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   4049:                         } else {
                   4050:                             $related{$swfargs[0]} = [$swfargs[2]];
                   4051:                         }
                   4052:                     }
1.645     raeburn  4053:                 }
                   4054:             }
                   4055:             if (lc($tagname) eq 'link') {
                   4056:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   4057:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   4058:                 }
                   4059:             }
1.640     albertel 4060: 	    if (lc($tagname) eq 'object' ||
                   4061: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   4062: 		foreach my $item (keys(%javafiles)) {
                   4063: 		    $javafiles{$item} = '';
                   4064: 		}
1.1164    raeburn  4065:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   4066:                     $lastids{lc($tagname)} = $attr->{'id'};
                   4067:                 }
1.640     albertel 4068: 	    }
                   4069: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   4070: 		my $name = lc($attr->{'name'});
                   4071: 		foreach my $item (keys(%javafiles)) {
                   4072: 		    if ($name eq $item) {
                   4073: 			$javafiles{$item} = $attr->{'value'};
                   4074: 			last;
                   4075: 		    }
                   4076: 		}
1.1164    raeburn  4077:                 my $pathfrom;
1.640     albertel 4078: 		foreach my $item (keys(%mediafiles)) {
                   4079: 		    if ($name eq $item) {
1.1164    raeburn  4080:                         $pathfrom = $attr->{'value'};
                   4081:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   4082: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 4083: 			last;
                   4084: 		    }
                   4085: 		}
1.1164    raeburn  4086:                 if ($name eq 'flashvars') {
                   4087:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   4088:                 }
                   4089:                 if ($pathfrom ne '') {
                   4090:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   4091:                                          $pathfrom);
                   4092:                 }
1.640     albertel 4093: 	    }
                   4094: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   4095: 		foreach my $item (keys(%javafiles)) {
                   4096: 		    if ($attr->{$item}) {
                   4097: 			$javafiles{$item} = $attr->{$item};
                   4098: 			last;
                   4099: 		    }
                   4100: 		}
                   4101: 		foreach my $item (keys(%mediafiles)) {
                   4102: 		    if ($attr->{$item}) {
                   4103: 			&add_filetype($allfiles,$attr->{$item},$item);
                   4104: 			last;
                   4105: 		    }
                   4106: 		}
1.1164    raeburn  4107:                 if (lc($tagname) eq 'embed') {
                   4108:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   4109:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   4110:                                              $attr->{'src'});
                   4111:                     }
                   4112:                 }
1.640     albertel 4113: 	    }
1.1243    raeburn  4114:             if (lc($tagname) eq 'iframe') {
                   4115:                 my $src = $attr->{'src'} ;
                   4116:                 if (($src ne '') && ($src !~ m{^(/|https?://)})) {
                   4117:                     &add_filetype($allfiles,$src,'src');
                   4118:                 } elsif ($src =~ m{^/}) {
                   4119:                     if ($env{'request.course.id'}) {
                   4120:                         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4121:                         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   4122:                         my $url = &hreflocation('',$fullpath);
                   4123:                         if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
                   4124:                             my $relpath = $1;
                   4125:                             if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
                   4126:                                 &add_filetype($allfiles,$1,'src');
                   4127:                             }
                   4128:                         }
                   4129:                     }
                   4130:                 }
                   4131:             }
1.1164    raeburn  4132:             if ($t->[4] =~ m{/>$}) {
1.1243    raeburn  4133:                 pop(@state);
1.1164    raeburn  4134:             }
1.640     albertel 4135: 	} elsif ($t->[0] eq 'E') {
                   4136: 	    my ($tagname) = ($t->[1]);
                   4137: 	    if ($javafiles{'codebase'} ne '') {
                   4138: 		$javafiles{'codebase'} .= '/';
                   4139: 	    }  
                   4140: 	    if (lc($tagname) eq 'applet' ||
                   4141: 		lc($tagname) eq 'object' ||
                   4142: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   4143: 		) {
                   4144: 		foreach my $item (keys(%javafiles)) {
                   4145: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   4146: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   4147: 			&add_filetype($allfiles,$file,$item);
                   4148: 		    }
                   4149: 		}
                   4150: 	    } 
                   4151: 	    pop @state;
                   4152: 	}
                   4153:     }
1.1164    raeburn  4154:     foreach my $id (sort(keys(%flashvars))) {
                   4155:         if ($shockwave{$id} ne '') {
                   4156:             my @pairs = split(/\&/,$flashvars{$id});
                   4157:             foreach my $pair (@pairs) {
                   4158:                 my ($key,$value) = split(/\=/,$pair);
                   4159:                 if ($key eq 'thumb') {
                   4160:                     &add_filetype($allfiles,$value,$key);
                   4161:                 } elsif ($key eq 'content') {
                   4162:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   4163:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   4164:                     if ($ext ne '') {
                   4165:                         &add_filetype($allfiles,$path.$value,$ext);
                   4166:                     }
                   4167:                 }
                   4168:             }
                   4169:         }
                   4170:     }
1.637     raeburn  4171:     return 'ok';
                   4172: }
                   4173: 
1.639     albertel 4174: sub add_filetype {
                   4175:     my ($allfiles,$file,$type)=@_;
                   4176:     if (exists($allfiles->{$file})) {
                   4177: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   4178: 	    push(@{$allfiles->{$file}}, &escape($type));
                   4179: 	}
                   4180:     } else {
                   4181: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  4182:     }
                   4183: }
                   4184: 
1.1164    raeburn  4185: sub embedded_dependency {
                   4186:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   4187:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   4188:         if (($identifier ne '') &&
                   4189:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   4190:             ($pathfrom ne '')) {
                   4191:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   4192:             foreach my $dep (@{$related->{$identifier}}) {
                   4193:                 &add_filetype($allfiles,$path.$dep,'object');
                   4194:             }
                   4195:         }
                   4196:     }
                   4197:     return;
                   4198: }
                   4199: 
1.493     albertel 4200: sub removeuploadedurl {
1.984     neumanie 4201:     my ($url)=@_;	
                   4202:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 4203:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 4204: }
                   4205: 
                   4206: sub removeuserfile {
                   4207:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 4208:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  4209:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 4210:     if ($result eq 'ok') {	
1.798     raeburn  4211:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   4212:             my $metafile = $fname.'.meta';
                   4213:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 4214: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 4215:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  4216:             my $sqlresult = 
1.823     albertel 4217:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4218:                                         'portfolio_metadata',$group,
                   4219:                                         'delete');
1.798     raeburn  4220:         }
                   4221:     }
                   4222:     return $result;
1.257     www      4223: }
1.15      www      4224: 
1.530     albertel 4225: sub mkdiruserfile {
                   4226:     my ($docuname,$docudom,$dir)=@_;
                   4227:     my $home=&homeserver($docuname,$docudom);
                   4228:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   4229: }
                   4230: 
1.531     albertel 4231: sub renameuserfile {
                   4232:     my ($docuname,$docudom,$old,$new)=@_;
                   4233:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  4234:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   4235:                         &escape("$old").':'.&escape("$new"),$home);
                   4236:     if ($result eq 'ok') {
                   4237:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   4238:             my $oldmeta = $old.'.meta';
                   4239:             my $newmeta = $new.'.meta';
                   4240:             my $metaresult = 
                   4241:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 4242: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   4243:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  4244:             my $sqlresult = 
1.823     albertel 4245:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  4246:                                         'portfolio_metadata',$group,
                   4247:                                         'delete');
1.798     raeburn  4248:         }
                   4249:     }
                   4250:     return $result;
1.531     albertel 4251: }
                   4252: 
1.14      www      4253: # ------------------------------------------------------------------------- Log
                   4254: 
                   4255: sub log {
                   4256:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      4257:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      4258: }
                   4259: 
                   4260: # ------------------------------------------------------------------ Course Log
1.352     www      4261: #
                   4262: # This routine flushes several buffers of non-mission-critical nature
                   4263: #
1.157     www      4264: 
                   4265: sub flushcourselogs {
1.352     www      4266:     &logthis('Flushing log buffers');
                   4267: #
                   4268: # course logs
                   4269: # This is a log of all transactions in a course, which can be used
                   4270: # for data mining purposes
                   4271: #
                   4272: # It also collects the courseid database, which lists last transaction
                   4273: # times and course titles for all courseids
                   4274: #
                   4275:     my %courseidbuffer=();
1.921     raeburn  4276:     foreach my $crsid (keys(%courselogs)) {
1.352     www      4277:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      4278: 		          &escape($courselogs{$crsid}),
                   4279: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      4280: 	    delete $courselogs{$crsid};
                   4281:         } else {
                   4282:             &logthis('Failed to flush log buffer for '.$crsid);
                   4283:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 4284:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      4285:                         " exceeded maximum size, deleting.</font>");
                   4286:                delete $courselogs{$crsid};
                   4287:             }
1.352     www      4288:         }
1.920     raeburn  4289:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  4290:             'description' => $coursedescrbuf{$crsid},
                   4291:             'inst_code'    => $courseinstcodebuf{$crsid},
                   4292:             'type'        => $coursetypebuf{$crsid},
                   4293:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  4294:         };
1.191     harris41 4295:     }
1.352     www      4296: #
                   4297: # Write course id database (reverse lookup) to homeserver of courses 
                   4298: # Is used in pickcourse
                   4299: #
1.840     albertel 4300:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  4301:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  4302:                                     $courseidbuffer{$crs_home},
                   4303:                                     $crs_home,'timeonly');
1.352     www      4304:     }
                   4305: #
                   4306: # File accesses
                   4307: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   4308: #
1.449     matthew  4309:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  4310:         if ($entry =~ /___count$/) {
                   4311:             my ($dom,$name);
1.807     albertel 4312:             ($dom,$name,undef)=
1.811     albertel 4313: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  4314:             if (! defined($dom) || $dom eq '' || 
                   4315:                 ! defined($name) || $name eq '') {
1.620     albertel 4316:                 my $cid = $env{'request.course.id'};
                   4317:                 $dom  = $env{'request.'.$cid.'.domain'};
                   4318:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  4319:             }
1.450     matthew  4320:             my $value = $accesshash{$entry};
                   4321:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   4322:             my %temphash=($url => $value);
1.449     matthew  4323:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   4324:             if ($result eq 'ok') {
                   4325:                 delete $accesshash{$entry};
                   4326:             }
                   4327:         } else {
1.811     albertel 4328:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      4329:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  4330:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  4331:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   4332:                 delete $accesshash{$entry};
                   4333:             }
1.185     www      4334:         }
1.191     harris41 4335:     }
1.352     www      4336: #
                   4337: # Roles
                   4338: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   4339: #
1.800     albertel 4340:     foreach my $entry (keys(%userrolehash)) {
1.351     www      4341:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      4342: 	    split(/\:/,$entry);
                   4343:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      4344:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      4345:                 $rudom,$runame) eq 'ok') {
                   4346: 	    delete $userrolehash{$entry};
                   4347:         }
                   4348:     }
1.662     raeburn  4349: #
1.1334    raeburn  4350: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
1.662     raeburn  4351: #
                   4352:     my %domrolebuffer = ();
1.1000    raeburn  4353:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 4354:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  4355:         if ($domrolebuffer{$rudom}) {
                   4356:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   4357:                       '='.&escape($domainrolehash{$entry});
                   4358:         } else {
                   4359:             $domrolebuffer{$rudom}.=&escape($entry).
                   4360:                       '='.&escape($domainrolehash{$entry});
                   4361:         }
                   4362:         delete $domainrolehash{$entry};
                   4363:     }
                   4364:     foreach my $dom (keys(%domrolebuffer)) {
1.1324    raeburn  4365: 	my %servers;
                   4366: 	if (defined(&domain($dom,'primary'))) {
                   4367: 	    my $primary=&domain($dom,'primary');
                   4368: 	    my $hostname=&hostname($primary);
                   4369: 	    $servers{$primary} = $hostname;
                   4370: 	} else { 
                   4371: 	    %servers = &get_servers($dom,'library');
                   4372: 	}
1.841     albertel 4373: 	foreach my $tryserver (keys(%servers)) {
1.1324    raeburn  4374: 	    if (&reply('domroleput:'.$dom.':'.
                   4375: 		       $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   4376: 		last;
                   4377: 	    } else {  
1.841     albertel 4378: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   4379: 	    }
1.662     raeburn  4380:         }
                   4381:     }
1.186     www      4382:     $dumpcount++;
1.157     www      4383: }
                   4384: 
                   4385: sub courselog {
                   4386:     my $what=shift;
1.158     www      4387:     $what=time.':'.$what;
1.620     albertel 4388:     unless ($env{'request.course.id'}) { return ''; }
                   4389:     $coursedombuf{$env{'request.course.id'}}=
                   4390:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   4391:     $coursenumbuf{$env{'request.course.id'}}=
                   4392:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   4393:     $coursehombuf{$env{'request.course.id'}}=
                   4394:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   4395:     $coursedescrbuf{$env{'request.course.id'}}=
                   4396:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   4397:     $courseinstcodebuf{$env{'request.course.id'}}=
                   4398:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   4399:     $courseownerbuf{$env{'request.course.id'}}=
                   4400:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  4401:     $coursetypebuf{$env{'request.course.id'}}=
                   4402:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 4403:     if (defined $courselogs{$env{'request.course.id'}}) {
                   4404: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      4405:     } else {
1.620     albertel 4406: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      4407:     }
1.620     albertel 4408:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      4409: 	&flushcourselogs();
                   4410:     }
1.158     www      4411: }
                   4412: 
                   4413: sub courseacclog {
                   4414:     my $fnsymb=shift;
1.620     albertel 4415:     unless ($env{'request.course.id'}) { return ''; }
                   4416:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      4417:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      4418:         $what.=':POST';
1.583     matthew  4419:         # FIXME: Probably ought to escape things....
1.800     albertel 4420: 	foreach my $key (keys(%env)) {
                   4421:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  4422:                 my $formitem = $1;
                   4423:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   4424:                     $what.=':'.$formitem.'='.$env{$key};
                   4425:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   4426:                     $what.=':'.$formitem.'='.$env{$key};
                   4427:                 }
1.158     www      4428:             }
1.191     harris41 4429:         }
1.583     matthew  4430:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   4431:         # FIXME: We should not be depending on a form parameter that someone
                   4432:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 4433:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  4434:             $what.= ':POST';
                   4435:             # FIXME: Probably ought to escape things....
                   4436:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   4437:                                  'crsdiscuss') {
1.620     albertel 4438:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  4439:             }
                   4440:         }
1.158     www      4441:     }
                   4442:     &courselog($what);
1.149     www      4443: }
                   4444: 
1.185     www      4445: sub countacc {
                   4446:     my $url=&declutter(shift);
1.458     matthew  4447:     return if (! defined($url) || $url eq '');
1.620     albertel 4448:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      4449: #
                   4450: # Mark that this url was used in this course
                   4451: #
1.620     albertel 4452:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      4453: #
                   4454: # Increase the access count for this resource in this child process
                   4455: #
1.281     www      4456:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  4457:     $accesshash{$key}++;
1.185     www      4458: }
1.349     www      4459: 
1.361     www      4460: sub linklog {
                   4461:     my ($from,$to)=@_;
                   4462:     $from=&declutter($from);
                   4463:     $to=&declutter($to);
                   4464:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   4465:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   4466: }
1.1160    www      4467: 
                   4468: sub statslog {
                   4469:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   4470:     if ($users<2) { return; }
                   4471:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   4472:             'course'       => $env{'request.course.id'},
                   4473:             'sections'     => '"all"',
                   4474:             'num_students' => $users,
                   4475:             'part'         => $part,
                   4476:             'symb'         => $symb,
                   4477:             'mean_tries'   => $av_attempts,
                   4478:             'deg_of_diff'  => $degdiff});
                   4479:     foreach my $key (keys(%dynstore)) {
                   4480:         $accesshash{$key}=$dynstore{$key};
                   4481:     }
                   4482: }
1.361     www      4483:   
1.349     www      4484: sub userrolelog {
                   4485:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 4486:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      4487:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4488:        $userrolehash
                   4489:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      4490:                     =$tend.':'.$tstart;
1.662     raeburn  4491:     }
1.1169    droeschl 4492:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 4493:        $userrolehash
                   4494:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   4495:                     =$tend.':'.$tstart;
                   4496:     }
1.1334    raeburn  4497:     if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
1.662     raeburn  4498:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   4499:        $domainrolehash
                   4500:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   4501:                     = $tend.':'.$tstart;
                   4502:     }
1.351     www      4503: }
                   4504: 
1.957     raeburn  4505: sub courserolelog {
                   4506:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
1.1184    raeburn  4507:     if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   4508:         my $cdom = $1;
                   4509:         my $cnum = $2;
                   4510:         my $sec = $3;
                   4511:         my $namespace = 'rolelog';
                   4512:         my %storehash = (
                   4513:                            role    => $trole,
                   4514:                            start   => $tstart,
                   4515:                            end     => $tend,
                   4516:                            selfenroll => $selfenroll,
                   4517:                            context    => $context,
                   4518:                         );
                   4519:         if ($trole eq 'gr') {
                   4520:             $namespace = 'groupslog';
                   4521:             $storehash{'group'} = $sec;
                   4522:         } else {
                   4523:             $storehash{'section'} = $sec;
                   4524:         }
1.1188    raeburn  4525:         &write_log('course',$namespace,\%storehash,$delflag,$username,
                   4526:                    $domain,$cnum,$cdom);
1.1184    raeburn  4527:         if (($trole ne 'st') || ($sec ne '')) {
                   4528:             &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
1.957     raeburn  4529:         }
                   4530:     }
                   4531:     return;
                   4532: }
                   4533: 
1.1184    raeburn  4534: sub domainrolelog {
                   4535:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4536:     if ($area =~ m{^/($match_domain)/$}) {
                   4537:         my $cdom = $1;
                   4538:         my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
                   4539:         my $namespace = 'rolelog';
                   4540:         my %storehash = (
                   4541:                            role    => $trole,
                   4542:                            start   => $tstart,
                   4543:                            end     => $tend,
                   4544:                            context => $context,
                   4545:                         );
1.1188    raeburn  4546:         &write_log('domain',$namespace,\%storehash,$delflag,$username,
                   4547:                    $domain,$domconfiguser,$cdom);
1.1184    raeburn  4548:     }
                   4549:     return;
                   4550: 
                   4551: }
                   4552: 
                   4553: sub coauthorrolelog {
                   4554:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
                   4555:     if ($area =~ m{^/($match_domain)/($match_username)$}) {
                   4556:         my $audom = $1;
                   4557:         my $auname = $2;
                   4558:         my $namespace = 'rolelog';
                   4559:         my %storehash = (
                   4560:                            role    => $trole,
                   4561:                            start   => $tstart,
                   4562:                            end     => $tend,
                   4563:                            context => $context,
                   4564:                         );
1.1188    raeburn  4565:         &write_log('author',$namespace,\%storehash,$delflag,$username,
                   4566:                    $domain,$auname,$audom);
1.1184    raeburn  4567:     }
                   4568:     return;
                   4569: }
                   4570: 
1.351     www      4571: sub get_course_adv_roles {
1.948     raeburn  4572:     my ($cid,$codes) = @_;
1.620     albertel 4573:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      4574:     my %coursehash=&coursedescription($cid);
1.988     raeburn  4575:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      4576:     my %nothide=();
1.800     albertel 4577:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  4578:         if ($user !~ /:/) {
                   4579: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   4580:         } else {
                   4581:             $nothide{$user}=1;
                   4582:         }
1.470     www      4583:     }
1.1219    raeburn  4584:     my @possdoms = ($coursehash{'domain'});
                   4585:     if ($coursehash{'checkforpriv'}) {
                   4586:         push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   4587:     }
1.351     www      4588:     my %returnhash=();
                   4589:     my %dumphash=
                   4590:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   4591:     my $now=time;
1.997     raeburn  4592:     my %privileged;
1.1000    raeburn  4593:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 4594: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      4595:         if (($tstart) && ($tstart<0)) { next; }
                   4596:         if (($tend) && ($tend<$now)) { next; }
                   4597:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 4598:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 4599: 	if ($username eq '' || $domain eq '') { next; }
1.1219    raeburn  4600:         if ((&privileged($username,$domain,\@possdoms)) &&
1.997     raeburn  4601:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 4602: 	if ($role eq 'cr') { next; }
1.948     raeburn  4603:         if ($codes) {
                   4604:             if ($section) { $role .= ':'.$section; }
                   4605:             if ($returnhash{$role}) {
                   4606:                 $returnhash{$role}.=','.$username.':'.$domain;
                   4607:             } else {
                   4608:                 $returnhash{$role}=$username.':'.$domain;
                   4609:             }
1.351     www      4610:         } else {
1.988     raeburn  4611:             my $key=&plaintext($role,$crstype);
1.973     bisitz   4612:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  4613:             if ($returnhash{$key}) {
                   4614: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   4615:             } else {
                   4616:                 $returnhash{$key}=$username.':'.$domain;
                   4617:             }
1.351     www      4618:         }
1.948     raeburn  4619:     }
1.400     www      4620:     return %returnhash;
                   4621: }
                   4622: 
                   4623: sub get_my_roles {
1.937     raeburn  4624:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 4625:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   4626:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  4627:     my (%dumphash,%nothide);
1.1086    raeburn  4628:     if ($context eq 'userroles') {
1.1166    raeburn  4629:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  4630:     } else {
1.1219    raeburn  4631:         %dumphash = &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  4632:         if ($hidepriv) {
                   4633:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   4634:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   4635:                 if ($user !~ /:/) {
                   4636:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   4637:                 } else {
                   4638:                     $nothide{$user} = 1;
                   4639:                 }
                   4640:             }
                   4641:         }
1.858     raeburn  4642:     }
1.400     www      4643:     my %returnhash=();
                   4644:     my $now=time;
1.999     raeburn  4645:     my %privileged;
1.800     albertel 4646:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  4647:         my ($role,$tend,$tstart);
                   4648:         if ($context eq 'userroles') {
1.1149    raeburn  4649:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  4650: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   4651:         } else {
                   4652:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   4653:         }
1.400     www      4654:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  4655:         my $status = 'active';
1.939     raeburn  4656:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  4657:             $status = 'previous';
                   4658:         } 
                   4659:         if (($tstart) && ($now<$tstart)) {
                   4660:             $status = 'future';
                   4661:         }
                   4662:         if (ref($types) eq 'ARRAY') {
                   4663:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   4664:                 next;
                   4665:             } 
                   4666:         } else {
                   4667:             if ($status ne 'active') {
                   4668:                 next;
                   4669:             }
                   4670:         }
1.867     raeburn  4671:         my ($rolecode,$username,$domain,$section,$area);
                   4672:         if ($context eq 'userroles') {
1.1186    raeburn  4673:             ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
1.867     raeburn  4674:             (undef,$domain,$username,$section) = split(/\//,$area);
                   4675:         } else {
                   4676:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   4677:         }
1.832     raeburn  4678:         if (ref($roledoms) eq 'ARRAY') {
                   4679:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   4680:                 next;
                   4681:             }
                   4682:         }
                   4683:         if (ref($roles) eq 'ARRAY') {
                   4684:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  4685:                 if ($role =~ /^cr\//) {
                   4686:                     if (!grep(/^cr$/,@{$roles})) {
                   4687:                         next;
                   4688:                     }
1.1104    raeburn  4689:                 } elsif ($role =~ /^gr\//) {
                   4690:                     if (!grep(/^gr$/,@{$roles})) {
                   4691:                         next;
                   4692:                     }
1.922     raeburn  4693:                 } else {
                   4694:                     next;
                   4695:                 }
1.832     raeburn  4696:             }
1.867     raeburn  4697:         }
1.937     raeburn  4698:         if ($hidepriv) {
1.1219    raeburn  4699:             my @privroles = ('dc','su');
1.999     raeburn  4700:             if ($context eq 'userroles') {
1.1219    raeburn  4701:                 next if (grep(/^\Q$role\E$/,@privroles));
1.999     raeburn  4702:             } else {
1.1219    raeburn  4703:                 my $possdoms = [$domain];
                   4704:                 if (ref($roledoms) eq 'ARRAY') {
                   4705:                    push(@{$possdoms},@{$roledoms}); 
1.999     raeburn  4706:                 }
1.1219    raeburn  4707:                 if (&privileged($username,$domain,$possdoms,\@privroles)) {
1.999     raeburn  4708:                     if (!$nothide{$username.':'.$domain}) {
                   4709:                         next;
                   4710:                     }
                   4711:                 }
1.937     raeburn  4712:             }
                   4713:         }
1.933     raeburn  4714:         if ($withsec) {
                   4715:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   4716:                 $tstart.':'.$tend;
                   4717:         } else {
                   4718:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   4719:         }
1.832     raeburn  4720:     }
1.373     www      4721:     return %returnhash;
1.399     www      4722: }
                   4723: 
1.1333    raeburn  4724: sub get_all_adhocroles {
                   4725:     my ($dom) = @_;
                   4726:     my @roles_by_num = ();
                   4727:     my %domdefaults = &get_domain_defaults($dom);
                   4728:     my (%description,%access_in_dom,%access_info);
                   4729:     if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
                   4730:         my $count = 0;
                   4731:         my %domcurrent = %{$domdefaults{'adhocroles'}};
                   4732:         my %ordered;
                   4733:         foreach my $role (sort(keys(%domcurrent))) {
                   4734:             my ($order,$desc,$access_in_dom);
                   4735:             if (ref($domcurrent{$role}) eq 'HASH') {
                   4736:                 $order = $domcurrent{$role}{'order'};
                   4737:                 $desc = $domcurrent{$role}{'desc'};
                   4738:                 $access_in_dom{$role} = $domcurrent{$role}{'access'};
                   4739:                 $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
                   4740:             }
                   4741:             if ($order eq '') {
                   4742:                 $order = $count;
                   4743:             }
                   4744:             $ordered{$order} = $role;
                   4745:             if ($desc ne '') {
                   4746:                 $description{$role} = $desc;
                   4747:             } else {
                   4748:                 $description{$role}= $role;
                   4749:             }
                   4750:             $count++;
                   4751:         }
                   4752:         foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
                   4753:             push(@roles_by_num,$ordered{$item});
                   4754:         }
                   4755:     }
                   4756:     return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
                   4757: }
                   4758: 
1.1332    raeburn  4759: sub get_my_adhocroles {
1.1333    raeburn  4760:     my ($cid,$checkreg) = @_;
                   4761:     my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
                   4762:     if ($env{'request.course.id'} eq $cid) {
                   4763:         $cdom = $env{'course.'.$cid.'.domain'};
                   4764:         $cnum = $env{'course.'.$cid.'.num'};
                   4765:         $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
                   4766:     } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
                   4767:         $cdom = $1;
                   4768:         $cnum = $2;
                   4769:         %info = &Apache::lonnet::get('environment',['internal.coursecode'],
                   4770:                                      $cdom,$cnum);
                   4771:     }
                   4772:     if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
                   4773:         my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   4774:         my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
                   4775:         if ($rosterhash{$user} ne '') {
                   4776:             my $type = (split(/:/,$rosterhash{$user}))[5];
                   4777:             return ([],{}) if ($type eq 'auto');
                   4778:         }
                   4779:     }
                   4780:     if (($cdom ne '') && ($cnum ne ''))  {
1.1334    raeburn  4781:         if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
1.1332    raeburn  4782:             my $then=$env{'user.login.time'};
                   4783:             my $update=$env{'user.update.time'};
1.1335    raeburn  4784:             if (!$update) {
                   4785:                 $update = $then;
                   4786:             }
                   4787:             my @liveroles;
1.1334    raeburn  4788:             foreach my $role ('dh','da') {
                   4789:                 if ($env{"user.role.$role./$cdom/"}) {
1.1335    raeburn  4790:                     my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
1.1334    raeburn  4791:                     my $limit = $update;
                   4792:                     if ($env{'request.role'} eq "$role./$cdom/") {
                   4793:                         $limit = $then;
                   4794:                     }
1.1335    raeburn  4795:                     my $activerole = 1;
                   4796:                     if ($tstart && $tstart>$limit) { $activerole = 0; }
                   4797:                     if ($tend   && $tend  <$limit) { $activerole = 0; }
                   4798:                     if ($activerole) {
                   4799:                         push(@liveroles,$role);
                   4800:                     }
1.1334    raeburn  4801:                 }
1.1332    raeburn  4802:             }
1.1335    raeburn  4803:             if (@liveroles) {
1.1332    raeburn  4804:                 if (&homeserver($cnum,$cdom) ne 'no_host') {
1.1333    raeburn  4805:                     my ($accessref,$accessinfo,%access_in_dom);
                   4806:                     ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
                   4807:                     if (ref($roles_by_num) eq 'ARRAY') {
                   4808:                         if (@{$roles_by_num}) {
1.1332    raeburn  4809:                             my %settings;
                   4810:                             if ($env{'request.course.id'} eq $cid) {
                   4811:                                 foreach my $envkey (keys(%env)) {
                   4812:                                     if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
                   4813:                                         $settings{$1} = $env{$envkey};
                   4814:                                     }
                   4815:                                 }
                   4816:                             } else {
                   4817:                                 %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
                   4818:                             }
                   4819:                             my %setincrs;
                   4820:                             if ($settings{'internal.adhocaccess'}) {
                   4821:                                 map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
                   4822:                             }
                   4823:                             my @statuses;
                   4824:                             if ($env{'environment.inststatus'}) {
                   4825:                                 @statuses = split(/,/,$env{'environment.inststatus'});
                   4826:                             }
                   4827:                             my $user = $env{'user.name'}.':'.$env{'user.domain'};
1.1333    raeburn  4828:                             if (ref($accessref) eq 'HASH') {
                   4829:                                 %access_in_dom = %{$accessref};
                   4830:                             }
                   4831:                             foreach my $role (@{$roles_by_num}) {
1.1332    raeburn  4832:                                 my ($curraccess,@okstatus,@personnel);
                   4833:                                 if ($setincrs{$role}) {
                   4834:                                     ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
                   4835:                                     if ($curraccess eq 'status') {
                   4836:                                         @okstatus = split(/\&/,$rest);
                   4837:                                     } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4838:                                         @personnel = split(/\&/,$rest);
                   4839:                                     }
                   4840:                                 } else {
                   4841:                                     $curraccess = $access_in_dom{$role};
1.1333    raeburn  4842:                                     if (ref($accessinfo) eq 'HASH') {
                   4843:                                         if ($curraccess eq 'status') {
                   4844:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4845:                                                 @okstatus = @{$accessinfo->{$role}};
                   4846:                                             }
                   4847:                                         } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4848:                                             if (ref($accessinfo->{$role}) eq 'ARRAY') {
                   4849:                                                 @personnel = @{$accessinfo->{$role}};
                   4850:                                             }
1.1332    raeburn  4851:                                         }
                   4852:                                     }
                   4853:                                 }
                   4854:                                 if ($curraccess eq 'none') {
                   4855:                                     next;
                   4856:                                 } elsif ($curraccess eq 'all') {
                   4857:                                     push(@possroles,$role);
1.1336    raeburn  4858:                                 } elsif ($curraccess eq 'dh') {
1.1335    raeburn  4859:                                     if (grep(/^dh$/,@liveroles)) {
                   4860:                                         push(@possroles,$role);
                   4861:                                     } else {
                   4862:                                         next;
                   4863:                                     }
1.1336    raeburn  4864:                                 } elsif ($curraccess eq 'da') {
1.1335    raeburn  4865:                                     if (grep(/^da$/,@liveroles)) {
                   4866:                                         push(@possroles,$role);
                   4867:                                     } else {
                   4868:                                         next;
                   4869:                                     }
1.1332    raeburn  4870:                                 } elsif ($curraccess eq 'status') {
                   4871:                                     if (@okstatus) {
                   4872:                                         if (!@statuses) {
                   4873:                                             if (grep(/^default$/,@okstatus)) {
                   4874:                                                 push(@possroles,$role);
                   4875:                                             }
                   4876:                                         } else {
                   4877:                                             foreach my $status (@okstatus) {
                   4878:                                                 if (grep(/^\Q$status\E$/,@statuses)) {
                   4879:                                                     push(@possroles,$role);
                   4880:                                                     last;
                   4881:                                                 }
                   4882:                                             }
                   4883:                                         }
                   4884:                                     }
                   4885:                                 } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
                   4886:                                     if (grep(/^\Q$user\E$/,@personnel)) {
                   4887:                                         if ($curraccess eq 'exc') {
                   4888:                                             push(@possroles,$role);
                   4889:                                         }
                   4890:                                     } elsif ($curraccess eq 'inc') {
                   4891:                                         push(@possroles,$role);
                   4892:                                     }
                   4893:                                 }
                   4894:                             }
                   4895:                         }
                   4896:                     }
                   4897:                 }
                   4898:             }
                   4899:         }
                   4900:     }
1.1333    raeburn  4901:     unless (ref($description) eq 'HASH') {
                   4902:         if (ref($roles_by_num) eq 'ARRAY') {
                   4903:             my %desc;
                   4904:             map { $desc{$_} = $_; } (@{$roles_by_num});
                   4905:             $description = \%desc;
                   4906:         } else {
                   4907:             $description = {};
                   4908:         }
                   4909:     }
                   4910:     return (\@possroles,$description);
1.1332    raeburn  4911: }
                   4912: 
1.399     www      4913: # ----------------------------------------------------- Frontpage Announcements
                   4914: #
                   4915: #
                   4916: 
                   4917: sub postannounce {
                   4918:     my ($server,$text)=@_;
1.844     albertel 4919:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      4920:     unless ($text=~/\w/) { $text=''; }
                   4921:     return &reply('setannounce:'.&escape($text),$server);
                   4922: }
                   4923: 
                   4924: sub getannounce {
1.448     albertel 4925: 
1.1359    raeburn  4926:     if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      4927: 	my $announcement='';
1.800     albertel 4928: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 4929: 	close($fh);
1.399     www      4930: 	if ($announcement=~/\w/) { 
                   4931: 	    return 
                   4932:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 4933:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      4934: 	} else {
                   4935: 	    return '';
                   4936: 	}
                   4937:     } else {
                   4938: 	return '';
                   4939:     }
1.351     www      4940: }
1.353     www      4941: 
                   4942: # ---------------------------------------------------------- Course ID routines
                   4943: # Deal with domain's nohist_courseid.db files
                   4944: #
                   4945: 
                   4946: sub courseidput {
1.921     raeburn  4947:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  4948:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  4949:     my $outcome;
                   4950:     if ($caller eq 'timeonly') {
                   4951:         my $cids = '';
                   4952:         foreach my $item (keys(%$storehash)) {
                   4953:             $cids.=&escape($item).'&';
                   4954:         }
                   4955:         $cids=~s/\&$//;
                   4956:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   4957:                           $coursehome);       
                   4958:     } else {
                   4959:         my $items = '';
                   4960:         foreach my $item (keys(%$storehash)) {
                   4961:             $items.= &escape($item).'='.
                   4962:                      &freeze_escape($$storehash{$item}).'&';
                   4963:         }
                   4964:         $items=~s/\&$//;
                   4965:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   4966:                           $coursehome);
1.918     raeburn  4967:     }
                   4968:     if ($outcome eq 'unknown_cmd') {
                   4969:         my $what;
                   4970:         foreach my $cid (keys(%$storehash)) {
                   4971:             $what .= &escape($cid).'=';
1.921     raeburn  4972:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  4973:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  4974:             }
                   4975:             $what =~ s/\:$/&/;
                   4976:         }
                   4977:         $what =~ s/\&$//;  
                   4978:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   4979:     } else {
                   4980:         return $outcome;
                   4981:     }
1.353     www      4982: }
                   4983: 
                   4984: sub courseiddump {
1.921     raeburn  4985:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  4986:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  4987:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1247    raeburn  4988:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
1.1287    raeburn  4989:         $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
1.918     raeburn  4990:     my $as_hash = 1;
                   4991:     my %returnhash;
                   4992:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 4993:     my %libserv = &all_library();
                   4994:     foreach my $tryserver (keys(%libserv)) {
                   4995:         if ( (  $hostidflag == 1 
                   4996: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   4997: 	     || (!defined($hostidflag)) ) {
                   4998: 
1.918     raeburn  4999: 	    if (($domfilter eq '') ||
                   5000: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 5001:                 my $rep;
                   5002:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   5003:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   5004:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   5005:                                 &escape($descfilter), &escape($instcodefilter), 
                   5006:                                 &escape($ownerfilter), &escape($coursefilter),
                   5007:                                 &escape($typefilter), &escape($regexp_ok), 
                   5008:                                 $as_hash, &escape($selfenrollonly), 
                   5009:                                 &escape($catfilter), $showhidden, $caller, 
                   5010:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   5011:                                 &escape($createdbefore), &escape($createdafter), 
1.1287    raeburn  5012:                                 &escape($creationcontext),$domcloner,$hasuniquecode,
                   5013:                                 $reqcrsdom,&escape($reqinstcode))));
1.1180    droeschl 5014:                 } else {
                   5015:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   5016:                              $sincefilter.':'.&escape($descfilter).':'.
                   5017:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   5018:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   5019:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   5020:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   5021:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   5022:                              &escape($cc_clone).':'.$cloneonly.':'.
                   5023:                              &escape($createdbefore).':'.&escape($createdafter).':'.
1.1287    raeburn  5024:                              &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
                   5025:                              ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
1.1180    droeschl 5026:                 }
                   5027:                      
1.918     raeburn  5028:                 my @pairs=split(/\&/,$rep);
                   5029:                 foreach my $item (@pairs) {
                   5030:                     my ($key,$value)=split(/\=/,$item,2);
                   5031:                     $key = &unescape($key);
                   5032:                     next if ($key =~ /^error: 2 /);
                   5033:                     my $result = &thaw_unescape($value);
                   5034:                     if (ref($result) eq 'HASH') {
                   5035:                         $returnhash{$key}=$result;
                   5036:                     } else {
1.921     raeburn  5037:                         my @responses = split(/:/,$value);
                   5038:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  5039:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  5040:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  5041:                         }
1.1008    raeburn  5042:                     }
1.353     www      5043:                 }
                   5044:             }
                   5045:         }
                   5046:     }
                   5047:     return %returnhash;
                   5048: }
                   5049: 
1.1055    raeburn  5050: sub courselastaccess {
                   5051:     my ($cdom,$cnum,$hostidref) = @_;
                   5052:     my %returnhash;
                   5053:     if ($cdom && $cnum) {
                   5054:         my $chome = &homeserver($cnum,$cdom);
                   5055:         if ($chome ne 'no_host') {
                   5056:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   5057:             &extract_lastaccess(\%returnhash,$rep);
                   5058:         }
                   5059:     } else {
                   5060:         if (!$cdom) { $cdom=''; }
                   5061:         my %libserv = &all_library();
                   5062:         foreach my $tryserver (keys(%libserv)) {
                   5063:             if (ref($hostidref) eq 'ARRAY') {
                   5064:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   5065:             } 
                   5066:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   5067:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   5068:                 &extract_lastaccess(\%returnhash,$rep);
                   5069:             }
                   5070:         }
                   5071:     }
                   5072:     return %returnhash;
                   5073: }
                   5074: 
                   5075: sub extract_lastaccess {
                   5076:     my ($returnhash,$rep) = @_;
                   5077:     if (ref($returnhash) eq 'HASH') {
                   5078:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   5079:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   5080:                  $rep eq '') {
                   5081:             my @pairs=split(/\&/,$rep);
                   5082:             foreach my $item (@pairs) {
                   5083:                 my ($key,$value)=split(/\=/,$item,2);
                   5084:                 $key = &unescape($key);
                   5085:                 next if ($key =~ /^error: 2 /);
                   5086:                 $returnhash->{$key} = &thaw_unescape($value);
                   5087:             }
                   5088:         }
                   5089:     }
                   5090:     return;
                   5091: }
                   5092: 
1.658     raeburn  5093: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  5094: 
                   5095: sub dcmailput {
1.685     raeburn  5096:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  5097:     my $status = &Apache::lonnet::critical(
1.740     www      5098:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   5099:        &escape($message),$server);
1.662     raeburn  5100:     return $status;
                   5101: }
                   5102: 
1.658     raeburn  5103: sub dcmaildump {
                   5104:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  5105:     my %returnhash=();
1.846     albertel 5106: 
                   5107:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  5108:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   5109:                                                          &escape($enddate).':';
                   5110: 	my @esc_senders=map { &escape($_)} @$senders;
                   5111: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 5112: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 5113:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  5114:             if (($key) && ($value)) {
                   5115:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  5116:             }
                   5117:         }
                   5118:     }
                   5119:     return %returnhash;
                   5120: }
1.662     raeburn  5121: # ---------------------------------------------------------- Domain roles
                   5122: 
                   5123: sub get_domain_roles {
                   5124:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  5125:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  5126:         $startdate = '.';
                   5127:     }
1.1018    raeburn  5128:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  5129:         $enddate = '.';
                   5130:     }
1.922     raeburn  5131:     my $rolelist;
                   5132:     if (ref($roles) eq 'ARRAY') {
1.1219    raeburn  5133:         $rolelist = join('&',@{$roles});
1.922     raeburn  5134:     }
1.662     raeburn  5135:     my %personnel = ();
1.841     albertel 5136: 
                   5137:     my %servers = &get_servers($dom,'library');
                   5138:     foreach my $tryserver (keys(%servers)) {
                   5139: 	%{$personnel{$tryserver}}=();
                   5140: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   5141: 					    &escape($startdate).':'.
                   5142: 					    &escape($enddate).':'.
                   5143: 					    &escape($rolelist), $tryserver))) {
                   5144: 	    my ($key,$value) = split(/\=/,$line,2);
                   5145: 	    if (($key) && ($value)) {
                   5146: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   5147: 	    }
                   5148: 	}
1.662     raeburn  5149:     }
                   5150:     return %personnel;
                   5151: }
1.658     raeburn  5152: 
1.1332    raeburn  5153: sub get_active_domroles {
                   5154:     my ($dom,$roles) = @_;
                   5155:     return () unless (ref($roles) eq 'ARRAY');
                   5156:     my $now = time;
                   5157:     my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
                   5158:     my %domroles;
                   5159:     foreach my $server (keys(%dompersonnel)) {
                   5160:         foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
                   5161:             my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
                   5162:             $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
                   5163:         }
                   5164:     }
                   5165:     return %domroles;
                   5166: }
                   5167: 
1.1057    www      5168: # ----------------------------------------------------------- Interval timing 
1.149     www      5169: 
1.1153    www      5170: {
                   5171: # Caches needed for speedup of navmaps
                   5172: # We don't want to cache this for very long at all (5 seconds at most)
                   5173: # 
                   5174: # The user for whom we cache
                   5175: my $cachedkey='';
                   5176: # The cached times for this user
                   5177: my %cachedtimes=();
                   5178: # When this was last done
1.1282    raeburn  5179: my $cachedtime='';
1.1153    www      5180: 
                   5181: sub load_all_first_access {
1.1308    raeburn  5182:     my ($uname,$udom,$ignorecache)=@_;
1.1156    www      5183:     if (($cachedkey eq $uname.':'.$udom) &&
1.1308    raeburn  5184:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
                   5185:         (!$ignorecache)) {
1.1154    raeburn  5186:         return;
                   5187:     }
                   5188:     $cachedtime=time;
                   5189:     $cachedkey=$uname.':'.$udom;
                   5190:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      5191: }
                   5192: 
1.504     albertel 5193: sub get_first_access {
1.1308    raeburn  5194:     my ($type,$argsymb,$argmap,$ignorecache)=@_;
1.790     albertel 5195:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5196:     if ($argsymb) { $symb=$argsymb; }
                   5197:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  5198:     if ($argmap) { $map = $argmap; }
1.926     albertel 5199:     if ($type eq 'course') {
                   5200: 	$res='course';
                   5201:     } elsif ($type eq 'map') {
1.588     albertel 5202: 	$res=&symbread($map);
                   5203:     } else {
                   5204: 	$res=$symb;
                   5205:     }
1.1308    raeburn  5206:     &load_all_first_access($uname,$udom,$ignorecache);
1.1153    www      5207:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 5208: }
                   5209: 
                   5210: sub set_first_access {
1.1162    raeburn  5211:     my ($type,$interval)=@_;
1.790     albertel 5212:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 5213:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 5214:     if ($type eq 'course') {
                   5215: 	$res='course';
                   5216:     } elsif ($type eq 'map') {
1.588     albertel 5217: 	$res=&symbread($map);
                   5218:     } else {
                   5219: 	$res=$symb;
                   5220:     }
1.1153    www      5221:     $cachedkey='';
1.1162    raeburn  5222:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 5223:     if (!$firstaccess) {
1.1162    raeburn  5224:         my $start = time;
                   5225: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   5226:                           $udom,$uname);
                   5227:         if ($putres eq 'ok') {
                   5228:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   5229:                  $udom,$uname); 
                   5230:             &appenv(
                   5231:                      {
                   5232:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   5233:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   5234:                      }
                   5235:                   );
1.1365    raeburn  5236:             if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
                   5237:                 $cachedtimes{"$courseid\0$res"} = $start;
                   5238:             }
1.1162    raeburn  5239:         }
                   5240:         return $putres;
1.505     albertel 5241:     }
                   5242:     return 'already_set';
1.504     albertel 5243: }
1.1153    www      5244: }
1.1282    raeburn  5245: 
1.110     www      5246: # --------------------------------------------- Set Expire Date for Spreadsheet
                   5247: 
                   5248: sub expirespread {
                   5249:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 5250:     my $cid=$env{'request.course.id'}; 
1.110     www      5251:     if ($cid) {
                   5252:        my $now=time;
                   5253:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 5254:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   5255:                             $env{'course.'.$cid.'.num'}.
1.110     www      5256: 	        	    ':nohist_expirationdates:'.
                   5257:                             &escape($key).'='.$now,
1.620     albertel 5258:                             $env{'course.'.$cid.'.home'})
1.110     www      5259:     }
                   5260:     return 'ok';
1.14      www      5261: }
                   5262: 
1.109     www      5263: # ----------------------------------------------------- Devalidate Spreadsheets
                   5264: 
                   5265: sub devalidate {
1.325     www      5266:     my ($symb,$uname,$udom)=@_;
1.620     albertel 5267:     my $cid=$env{'request.course.id'}; 
1.109     www      5268:     if ($cid) {
1.391     matthew  5269:         # delete the stored spreadsheets for
                   5270:         # - the student level sheet of this user in course's homespace
                   5271:         # - the assessment level sheet for this resource 
                   5272:         #   for this user in user's homespace
1.553     albertel 5273: 	# - current conditional state info
1.325     www      5274: 	my $key=$uname.':'.$udom.':';
1.109     www      5275:         my $status=
1.299     matthew  5276: 	    &del('nohist_calculatedsheets',
1.391     matthew  5277: 		 [$key.'studentcalc:'],
1.620     albertel 5278: 		 $env{'course.'.$cid.'.domain'},
                   5279: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 5280: 		.' '.
                   5281: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  5282: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      5283:         unless ($status eq 'ok ok') {
                   5284:            &logthis('Could not devalidate spreadsheet '.
1.325     www      5285:                     $uname.' at '.$udom.' for '.
1.109     www      5286: 		    $symb.': '.$status);
1.133     albertel 5287:         }
1.553     albertel 5288: 	&delenv('user.state.'.$cid);
1.109     www      5289:     }
                   5290: }
                   5291: 
1.265     albertel 5292: sub get_scalar {
                   5293:     my ($string,$end) = @_;
                   5294:     my $value;
                   5295:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   5296: 	$value = $1;
                   5297:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   5298: 	$value = $1;
                   5299:     }
                   5300:     return &unescape($value);
                   5301: }
                   5302: 
                   5303: sub array2str {
                   5304:   my (@array) = @_;
                   5305:   my $result=&arrayref2str(\@array);
                   5306:   $result=~s/^__ARRAY_REF__//;
                   5307:   $result=~s/__END_ARRAY_REF__$//;
                   5308:   return $result;
                   5309: }
                   5310: 
1.204     albertel 5311: sub arrayref2str {
                   5312:   my ($arrayref) = @_;
1.265     albertel 5313:   my $result='__ARRAY_REF__';
1.204     albertel 5314:   foreach my $elem (@$arrayref) {
1.265     albertel 5315:     if(ref($elem) eq 'ARRAY') {
                   5316:       $result.=&arrayref2str($elem).'&';
                   5317:     } elsif(ref($elem) eq 'HASH') {
                   5318:       $result.=&hashref2str($elem).'&';
                   5319:     } elsif(ref($elem)) {
                   5320:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 5321:     } else {
                   5322:       $result.=&escape($elem).'&';
                   5323:     }
                   5324:   }
                   5325:   $result=~s/\&$//;
1.265     albertel 5326:   $result .= '__END_ARRAY_REF__';
1.204     albertel 5327:   return $result;
                   5328: }
                   5329: 
1.168     albertel 5330: sub hash2str {
1.204     albertel 5331:   my (%hash) = @_;
                   5332:   my $result=&hashref2str(\%hash);
1.265     albertel 5333:   $result=~s/^__HASH_REF__//;
                   5334:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 5335:   return $result;
                   5336: }
                   5337: 
                   5338: sub hashref2str {
                   5339:   my ($hashref)=@_;
1.265     albertel 5340:   my $result='__HASH_REF__';
1.800     albertel 5341:   foreach my $key (sort(keys(%$hashref))) {
                   5342:     if (ref($key) eq 'ARRAY') {
                   5343:       $result.=&arrayref2str($key).'=';
                   5344:     } elsif (ref($key) eq 'HASH') {
                   5345:       $result.=&hashref2str($key).'=';
                   5346:     } elsif (ref($key)) {
1.265     albertel 5347:       $result.='=';
1.800     albertel 5348:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 5349:     } else {
1.1132    raeburn  5350: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 5351:     }
                   5352: 
1.800     albertel 5353:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   5354:       $result.=&arrayref2str($hashref->{$key}).'&';
                   5355:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   5356:       $result.=&hashref2str($hashref->{$key}).'&';
                   5357:     } elsif(ref($hashref->{$key})) {
1.265     albertel 5358:        $result.='&';
1.800     albertel 5359:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 5360:     } else {
1.800     albertel 5361:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 5362:     }
                   5363:   }
1.168     albertel 5364:   $result=~s/\&$//;
1.265     albertel 5365:   $result .= '__END_HASH_REF__';
1.168     albertel 5366:   return $result;
                   5367: }
                   5368: 
                   5369: sub str2hash {
1.265     albertel 5370:     my ($string)=@_;
                   5371:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   5372:     return %$hash;
                   5373: }
                   5374: 
                   5375: sub str2hashref {
1.168     albertel 5376:   my ($string) = @_;
1.265     albertel 5377: 
                   5378:   my %hash;
                   5379: 
                   5380:   if($string !~ /^__HASH_REF__/) {
                   5381:       if (! ($string eq '' || !defined($string))) {
                   5382: 	  $hash{'error'}='Not hash reference';
                   5383:       }
                   5384:       return (\%hash, $string);
                   5385:   }
                   5386: 
                   5387:   $string =~ s/^__HASH_REF__//;
                   5388: 
                   5389:   while($string !~ /^__END_HASH_REF__/) {
                   5390:       #key
                   5391:       my $key='';
                   5392:       if($string =~ /^__HASH_REF__/) {
                   5393:           ($key, $string)=&str2hashref($string);
                   5394:           if(defined($key->{'error'})) {
                   5395:               $hash{'error'}='Bad data';
                   5396:               return (\%hash, $string);
                   5397:           }
                   5398:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5399:           ($key, $string)=&str2arrayref($string);
                   5400:           if($key->[0] eq 'Array reference error') {
                   5401:               $hash{'error'}='Bad data';
                   5402:               return (\%hash, $string);
                   5403:           }
                   5404:       } else {
                   5405:           $string =~ s/^(.*?)=//;
1.267     albertel 5406: 	  $key=&unescape($1);
1.265     albertel 5407:       }
                   5408:       $string =~ s/^=//;
                   5409: 
                   5410:       #value
                   5411:       my $value='';
                   5412:       if($string =~ /^__HASH_REF__/) {
                   5413:           ($value, $string)=&str2hashref($string);
                   5414:           if(defined($value->{'error'})) {
                   5415:               $hash{'error'}='Bad data';
                   5416:               return (\%hash, $string);
                   5417:           }
                   5418:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5419:           ($value, $string)=&str2arrayref($string);
                   5420:           if($value->[0] eq 'Array reference error') {
                   5421:               $hash{'error'}='Bad data';
                   5422:               return (\%hash, $string);
                   5423:           }
                   5424:       } else {
                   5425: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   5426:       }
                   5427:       $string =~ s/^&//;
                   5428: 
                   5429:       $hash{$key}=$value;
1.204     albertel 5430:   }
1.265     albertel 5431: 
                   5432:   $string =~ s/^__END_HASH_REF__//;
                   5433: 
                   5434:   return (\%hash, $string);
1.204     albertel 5435: }
                   5436: 
                   5437: sub str2array {
1.265     albertel 5438:     my ($string)=@_;
                   5439:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   5440:     return @$array;
                   5441: }
                   5442: 
                   5443: sub str2arrayref {
1.204     albertel 5444:   my ($string) = @_;
1.265     albertel 5445:   my @array;
                   5446: 
                   5447:   if($string !~ /^__ARRAY_REF__/) {
                   5448:       if (! ($string eq '' || !defined($string))) {
                   5449: 	  $array[0]='Array reference error';
                   5450:       }
                   5451:       return (\@array, $string);
                   5452:   }
                   5453: 
                   5454:   $string =~ s/^__ARRAY_REF__//;
                   5455: 
                   5456:   while($string !~ /^__END_ARRAY_REF__/) {
                   5457:       my $value='';
                   5458:       if($string =~ /^__HASH_REF__/) {
                   5459:           ($value, $string)=&str2hashref($string);
                   5460:           if(defined($value->{'error'})) {
                   5461:               $array[0] ='Array reference error';
                   5462:               return (\@array, $string);
                   5463:           }
                   5464:       } elsif($string =~ /^__ARRAY_REF__/) {
                   5465:           ($value, $string)=&str2arrayref($string);
                   5466:           if($value->[0] eq 'Array reference error') {
                   5467:               $array[0] ='Array reference error';
                   5468:               return (\@array, $string);
                   5469:           }
                   5470:       } else {
                   5471: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   5472:       }
                   5473:       $string =~ s/^&//;
                   5474: 
                   5475:       push(@array, $value);
1.191     harris41 5476:   }
1.265     albertel 5477: 
                   5478:   $string =~ s/^__END_ARRAY_REF__//;
                   5479: 
                   5480:   return (\@array, $string);
1.168     albertel 5481: }
                   5482: 
1.167     albertel 5483: # -------------------------------------------------------------------Temp Store
                   5484: 
1.168     albertel 5485: sub tmpreset {
                   5486:   my ($symb,$namespace,$domain,$stuname) = @_;
                   5487:   if (!$symb) {
                   5488:     $symb=&symbread();
1.620     albertel 5489:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5490:   }
                   5491:   $symb=escape($symb);
                   5492: 
1.620     albertel 5493:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 5494:   $namespace=~s/\//\_/g;
                   5495:   $namespace=~s/\W//g;
                   5496: 
1.620     albertel 5497:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5498:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5499:   if ($domain eq 'public' && $stuname eq 'public') {
                   5500:       $stuname=$ENV{'REMOTE_ADDR'};
                   5501:   }
1.1117    foxr     5502:   my $path=LONCAPA::tempdir();
1.168     albertel 5503:   my %hash;
                   5504:   if (tie(%hash,'GDBM_File',
                   5505: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5506: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  5507:     foreach my $key (keys(%hash)) {
1.180     albertel 5508:       if ($key=~ /:$symb/) {
1.168     albertel 5509: 	delete($hash{$key});
                   5510:       }
                   5511:     }
                   5512:   }
                   5513: }
                   5514: 
1.167     albertel 5515: sub tmpstore {
1.168     albertel 5516:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   5517: 
                   5518:   if (!$symb) {
                   5519:     $symb=&symbread();
1.620     albertel 5520:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5521:   }
                   5522:   $symb=escape($symb);
                   5523: 
                   5524:   if (!$namespace) {
                   5525:     # I don't think we would ever want to store this for a course.
                   5526:     # it seems this will only be used if we don't have a course.
1.620     albertel 5527:     #$namespace=$env{'request.course.id'};
1.168     albertel 5528:     #if (!$namespace) {
1.620     albertel 5529:       $namespace=$env{'request.state'};
1.168     albertel 5530:     #}
                   5531:   }
                   5532:   $namespace=~s/\//\_/g;
                   5533:   $namespace=~s/\W//g;
1.620     albertel 5534:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5535:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5536:   if ($domain eq 'public' && $stuname eq 'public') {
                   5537:       $stuname=$ENV{'REMOTE_ADDR'};
                   5538:   }
1.168     albertel 5539:   my $now=time;
                   5540:   my %hash;
1.1117    foxr     5541:   my $path=LONCAPA::tempdir();
1.168     albertel 5542:   if (tie(%hash,'GDBM_File',
                   5543: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5544: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 5545:     $hash{"version:$symb"}++;
                   5546:     my $version=$hash{"version:$symb"};
                   5547:     my $allkeys=''; 
                   5548:     foreach my $key (keys(%$storehash)) {
                   5549:       $allkeys.=$key.':';
1.591     albertel 5550:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 5551:     }
                   5552:     $hash{"$version:$symb:timestamp"}=$now;
                   5553:     $allkeys.='timestamp';
                   5554:     $hash{"$version:keys:$symb"}=$allkeys;
                   5555:     if (untie(%hash)) {
                   5556:       return 'ok';
                   5557:     } else {
                   5558:       return "error:$!";
                   5559:     }
                   5560:   } else {
                   5561:     return "error:$!";
                   5562:   }
                   5563: }
1.167     albertel 5564: 
1.168     albertel 5565: # -----------------------------------------------------------------Temp Restore
1.167     albertel 5566: 
1.168     albertel 5567: sub tmprestore {
                   5568:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 5569: 
1.168     albertel 5570:   if (!$symb) {
                   5571:     $symb=&symbread();
1.620     albertel 5572:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 5573:   }
                   5574:   $symb=escape($symb);
                   5575: 
1.620     albertel 5576:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 5577: 
1.620     albertel 5578:   if (!$domain) { $domain=$env{'user.domain'}; }
                   5579:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 5580:   if ($domain eq 'public' && $stuname eq 'public') {
                   5581:       $stuname=$ENV{'REMOTE_ADDR'};
                   5582:   }
1.168     albertel 5583:   my %returnhash;
                   5584:   $namespace=~s/\//\_/g;
                   5585:   $namespace=~s/\W//g;
                   5586:   my %hash;
1.1117    foxr     5587:   my $path=LONCAPA::tempdir();
1.168     albertel 5588:   if (tie(%hash,'GDBM_File',
                   5589: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 5590: 	  &GDBM_READER(),0640)) {
1.168     albertel 5591:     my $version=$hash{"version:$symb"};
                   5592:     $returnhash{'version'}=$version;
                   5593:     my $scope;
                   5594:     for ($scope=1;$scope<=$version;$scope++) {
                   5595:       my $vkeys=$hash{"$scope:keys:$symb"};
                   5596:       my @keys=split(/:/,$vkeys);
                   5597:       my $key;
                   5598:       $returnhash{"$scope:keys"}=$vkeys;
                   5599:       foreach $key (@keys) {
1.591     albertel 5600: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   5601: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 5602:       }
                   5603:     }
1.168     albertel 5604:     if (!(untie(%hash))) {
                   5605:       return "error:$!";
                   5606:     }
                   5607:   } else {
                   5608:     return "error:$!";
                   5609:   }
                   5610:   return %returnhash;
1.167     albertel 5611: }
                   5612: 
1.9       www      5613: # ----------------------------------------------------------------------- Store
                   5614: 
                   5615: sub store {
1.1269    raeburn  5616:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5617:     my $home='';
                   5618: 
1.168     albertel 5619:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5620: 
1.213     www      5621:     $symb=&symbclean($symb);
1.122     albertel 5622:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5623: 
1.620     albertel 5624:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5625:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5626: 
                   5627:     &devalidate($symb,$stuname,$domain);
1.109     www      5628: 
                   5629:     $symb=escape($symb);
1.187     www      5630:     if (!$namespace) { 
1.620     albertel 5631:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5632:           return ''; 
                   5633:        } 
                   5634:     }
1.620     albertel 5635:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5636: 
                   5637:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5638:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   5639: 
1.12      www      5640:     my $namevalue='';
1.800     albertel 5641:     foreach my $key (keys(%$storehash)) {
                   5642:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5643:     }
1.12      www      5644:     $namevalue=~s/\&$//;
1.187     www      5645:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.1269    raeburn  5646:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.9       www      5647: }
                   5648: 
1.47      www      5649: # -------------------------------------------------------------- Critical Store
                   5650: 
                   5651: sub cstore {
1.1269    raeburn  5652:     my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
1.124     www      5653:     my $home='';
                   5654: 
1.168     albertel 5655:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5656: 
1.213     www      5657:     $symb=&symbclean($symb);
1.122     albertel 5658:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      5659: 
1.620     albertel 5660:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5661:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      5662: 
                   5663:     &devalidate($symb,$stuname,$domain);
1.109     www      5664: 
                   5665:     $symb=escape($symb);
1.187     www      5666:     if (!$namespace) { 
1.620     albertel 5667:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      5668:           return ''; 
                   5669:        } 
                   5670:     }
1.620     albertel 5671:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      5672: 
                   5673:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   5674:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 5675: 
1.47      www      5676:     my $namevalue='';
1.800     albertel 5677:     foreach my $key (keys(%$storehash)) {
                   5678:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 5679:     }
1.47      www      5680:     $namevalue=~s/\&$//;
1.187     www      5681:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      5682:     return critical
1.1269    raeburn  5683:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
1.47      www      5684: }
                   5685: 
1.9       www      5686: # --------------------------------------------------------------------- Restore
                   5687: 
                   5688: sub restore {
1.124     www      5689:     my ($symb,$namespace,$domain,$stuname) = @_;
                   5690:     my $home='';
                   5691: 
1.168     albertel 5692:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      5693: 
1.122     albertel 5694:     if (!$symb) {
1.1224    raeburn  5695:         return if ($namespace eq 'courserequests');
                   5696:         unless ($symb=escape(&symbread())) { return ''; }
1.122     albertel 5697:     } else {
1.1224    raeburn  5698:         unless ($namespace eq 'courserequests') {
                   5699:             $symb=&escape(&symbclean($symb));
                   5700:         }
1.122     albertel 5701:     }
1.188     www      5702:     if (!$namespace) { 
1.620     albertel 5703:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      5704:           return ''; 
                   5705:        } 
                   5706:     }
1.620     albertel 5707:     if (!$domain) { $domain=$env{'user.domain'}; }
                   5708:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   5709:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 5710:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   5711: 
1.12      www      5712:     my %returnhash=();
1.800     albertel 5713:     foreach my $line (split(/\&/,$answer)) {
                   5714: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 5715:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 5716:     }
1.75      www      5717:     my $version;
                   5718:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 5719:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   5720:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 5721:        }
1.75      www      5722:     }
1.13      www      5723:     return %returnhash;
1.34      www      5724: }
                   5725: 
                   5726: # ---------------------------------------------------------- Course Description
1.1118    foxr     5727: #
                   5728: #  
1.34      www      5729: 
                   5730: sub coursedescription {
1.731     albertel 5731:     my ($courseid,$args)=@_;
1.34      www      5732:     $courseid=~s/^\///;
1.49      www      5733:     $courseid=~s/\_/\//g;
1.34      www      5734:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 5735:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 5736:     my $normalid=$cdomain.'_'.$cnum;
                   5737:     # need to always cache even if we get errors otherwise we keep 
                   5738:     # trying and trying and trying to get the course description.
                   5739:     my %envhash=();
                   5740:     my %returnhash=();
1.731     albertel 5741:     
                   5742:     my $expiretime=600;
                   5743:     if ($env{'request.course.id'} eq $normalid) {
                   5744: 	$expiretime=120;
                   5745:     }
                   5746: 
                   5747:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   5748:     if (!$args->{'freshen_cache'}
                   5749: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   5750: 	foreach my $key (keys(%env)) {
                   5751: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   5752: 	    my ($setting) = $1;
                   5753: 	    $returnhash{$setting} = $env{$key};
                   5754: 	}
                   5755: 	return %returnhash;
                   5756:     }
                   5757: 
1.1118    foxr     5758:     # get the data again
                   5759: 
1.731     albertel 5760:     if (!$args->{'one_time'}) {
                   5761: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   5762:     }
1.811     albertel 5763: 
1.34      www      5764:     if ($chome ne 'no_host') {
1.302     albertel 5765:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 5766:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     5767: 	   my $username = $env{'user.name'}; # Defult username
                   5768: 	   if(defined $args->{'user'}) {
                   5769: 	       $username = $args->{'user'};
                   5770: 	   }
1.129     albertel 5771:            $returnhash{'home'}= $chome;
                   5772: 	   $returnhash{'domain'} = $cdomain;
                   5773: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  5774:            if (!defined($returnhash{'type'})) {
                   5775:                $returnhash{'type'} = 'Course';
                   5776:            }
1.130     albertel 5777:            while (my ($name,$value) = each %returnhash) {
1.53      www      5778:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 5779:            }
1.270     www      5780:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     5781:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     5782: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      5783:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   5784:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   5785:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      5786:        }
                   5787:     }
1.731     albertel 5788:     if (!$args->{'one_time'}) {
1.949     raeburn  5789: 	&appenv(\%envhash);
1.731     albertel 5790:     }
1.302     albertel 5791:     return %returnhash;
1.461     www      5792: }
                   5793: 
1.1080    raeburn  5794: sub update_released_required {
                   5795:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   5796:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   5797:         $cid = $env{'request.course.id'};
                   5798:         $cdom = $env{'course.'.$cid.'.domain'};
                   5799:         $cnum = $env{'course.'.$cid.'.num'};
                   5800:         $chome = $env{'course.'.$cid.'.home'};
                   5801:     }
                   5802:     if ($needsrelease) {
                   5803:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   5804:         my $needsupdate;
                   5805:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   5806:             $needsupdate = 1;
                   5807:         } else {
                   5808:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   5809:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   5810:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   5811:                 $needsupdate = 1;
                   5812:             }
                   5813:         }
                   5814:         if ($needsupdate) {
                   5815:             my %needshash = (
                   5816:                              'internal.releaserequired' => $needsrelease,
                   5817:                             );
                   5818:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   5819:             if ($putresult eq 'ok') {
                   5820:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   5821:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   5822:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   5823:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   5824:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   5825:                 }
                   5826:             }
                   5827:         }
                   5828:     }
                   5829:     return;
                   5830: }
                   5831: 
1.461     www      5832: # -------------------------------------------------See if a user is privileged
                   5833: 
                   5834: sub privileged {
1.1219    raeburn  5835:     my ($username,$domain,$possdomains,$possroles)=@_;
1.1170    droeschl 5836:     my $now = time;
1.1219    raeburn  5837:     my $roles;
                   5838:     if (ref($possroles) eq 'ARRAY') {
                   5839:         $roles = $possroles; 
                   5840:     } else {
                   5841:         $roles = ['dc','su'];
                   5842:     }
                   5843:     if (ref($possdomains) eq 'ARRAY') {
                   5844:         my %privileged = &privileged_by_domain($possdomains,$roles);
                   5845:         foreach my $dom (@{$possdomains}) {
                   5846:             if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
                   5847:                 (ref($privileged{$dom}) eq 'HASH')) {
                   5848:                 foreach my $role (@{$roles}) {
                   5849:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5850:                         if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
                   5851:                             my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
                   5852:                             return 1 unless (($end && $end < $now) ||
                   5853:                                              ($start && $start > $now));
                   5854:                         }
                   5855:                     }
                   5856:                 }
                   5857:             }
                   5858:         }
                   5859:     } else {
                   5860:         my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   5861:         my $now = time;
1.1170    droeschl 5862: 
1.1275    musolffc 5863:         for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
1.1170    droeschl 5864:             my ($trole, $tend, $tstart) = split(/_/, $role);
1.1219    raeburn  5865:             if (grep(/^\Q$trole\E$/,@{$roles})) {
1.1170    droeschl 5866:                 return 1 unless ($tend && $tend < $now) 
1.1219    raeburn  5867:                         or ($tstart && $tstart > $now);
1.1170    droeschl 5868:             }
1.1219    raeburn  5869:         }
                   5870:     }
                   5871:     return 0;
                   5872: }
1.1170    droeschl 5873: 
1.1219    raeburn  5874: sub privileged_by_domain {
                   5875:     my ($domains,$roles) = @_;
                   5876:     my %privileged = ();
                   5877:     my $cachetime = 60*60*24;
                   5878:     my $now = time;
                   5879:     unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
                   5880:         return %privileged;
                   5881:     }
                   5882:     foreach my $dom (@{$domains}) {
                   5883:         next if (ref($privileged{$dom}) eq 'HASH');
                   5884:         my $needroles;
                   5885:         foreach my $role (@{$roles}) {
                   5886:             my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
                   5887:             if (defined($cached)) {
                   5888:                 if (ref($result) eq 'HASH') {
                   5889:                     $privileged{$dom}{$role} = $result;
                   5890:                 }
                   5891:             } else {
                   5892:                 $needroles = 1;
                   5893:             }
                   5894:         }
                   5895:         if ($needroles) {
                   5896:             my %dompersonnel = &get_domain_roles($dom,$roles);
                   5897:             $privileged{$dom} = {};
                   5898:             foreach my $server (keys(%dompersonnel)) {
                   5899:                 if (ref($dompersonnel{$server}) eq 'HASH') {
                   5900:                     foreach my $item (keys(%{$dompersonnel{$server}})) {
                   5901:                         my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
                   5902:                         my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
                   5903:                         next if ($end && $end < $now);
                   5904:                         $privileged{$dom}{$trole}{$uname.':'.$udom} = 
                   5905:                             $dompersonnel{$server}{$item};
                   5906:                     }
                   5907:                 }
                   5908:             }
                   5909:             if (ref($privileged{$dom}) eq 'HASH') {
                   5910:                 foreach my $role (@{$roles}) {
                   5911:                     if (ref($privileged{$dom}{$role}) eq 'HASH') {
                   5912:                         &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
                   5913:                     } else {
                   5914:                         my %hash = ();
                   5915:                         &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
                   5916:                     }
                   5917:                 }
                   5918:             }
                   5919:         }
                   5920:     }
                   5921:     return %privileged;
1.9       www      5922: }
1.1       albertel 5923: 
1.103     harris41 5924: # -------------------------------------------------------- Get user privileges
1.11      www      5925: 
                   5926: sub rolesinit {
1.1169    droeschl 5927:     my ($domain, $username) = @_;
                   5928:     my %userroles = ('user.login.time' => time);
                   5929:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   5930: 
                   5931:     # firstaccess and timerinterval are related to timed maps/resources. 
                   5932:     # also, blocking can be triggered by an activating timer
                   5933:     # it's saved in the user's %env.
                   5934:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   5935:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   5936:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   5937:         %timerintchk, %timerintenv);
                   5938: 
1.1162    raeburn  5939:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 5940:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  5941:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   5942:     }
1.1169    droeschl 5943: 
1.1162    raeburn  5944:     foreach my $key (keys(%timerinterval)) {
                   5945:         my ($cid,$rest) = split(/\0/,$key);
                   5946:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   5947:     }
1.1169    droeschl 5948: 
1.11      www      5949:     my %allroles=();
1.1162    raeburn  5950:     my %allgroups=();
1.11      www      5951: 
1.1274    raeburn  5952:     for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
1.1169    droeschl 5953:         my $role = $rolesdump{$area};
                   5954:         $area =~ s/\_\w\w$//;
                   5955: 
                   5956:         my ($trole, $tend, $tstart, $group_privs);
                   5957: 
                   5958:         if ($role =~ /^cr/) {
                   5959:         # Custom role, defined by a user 
                   5960:         # e.g., user.role.cr/msu/smith/mynewrole
                   5961:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   5962:                 $trole = $1;
                   5963:                 ($tend, $tstart) = split('_', $2);
                   5964:             } else {
                   5965:                 $trole = $role;
                   5966:             }
                   5967:         } elsif ($role =~ m|^gr/|) {
                   5968:         # Role of member in a group, defined within a course/community
                   5969:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   5970:             ($trole, $tend, $tstart) = split(/_/, $role);
                   5971:             next if $tstart eq '-1';
                   5972:             ($trole, $group_privs) = split(/\//, $trole);
                   5973:             $group_privs = &unescape($group_privs);
                   5974:         } else {
                   5975:         # Just a normal role, defined in roles.tab
                   5976:             ($trole, $tend, $tstart) = split(/_/,$role);
                   5977:         }
                   5978: 
                   5979:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   5980:                  $username);
                   5981:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   5982: 
                   5983:         # role expired or not available yet?
                   5984:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   5985:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   5986: 
                   5987:         next if $area eq '' or $trole eq '';
                   5988: 
                   5989:         my $spec = "$trole.$area";
                   5990:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   5991: 
                   5992:         if ($trole =~ /^cr\//) {
                   5993:         # Custom role, defined by a user
                   5994:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5995:         } elsif ($trole eq 'gr') {
                   5996:         # Role of a member in a group, defined within a course/community
                   5997:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   5998:             next;
                   5999:         } else {
                   6000:         # Normal role, defined in roles.tab
                   6001:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   6002:         }
                   6003: 
                   6004:         my $cid = $tdomain.'_'.$trest;
                   6005:         unless ($firstaccchk{$cid}) {
                   6006:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   6007:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   6008:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   6009:                         $coursetimerstarts{$cid}{$item}; 
                   6010:                 }
                   6011:             }
                   6012:             $firstaccchk{$cid} = 1;
                   6013:         }
                   6014:         unless ($timerintchk{$cid}) {
                   6015:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   6016:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   6017:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   6018:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  6019:                 }
1.12      www      6020:             }
1.1169    droeschl 6021:             $timerintchk{$cid} = 1;
1.191     harris41 6022:         }
1.11      www      6023:     }
1.1169    droeschl 6024: 
1.1341    raeburn  6025:     @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
                   6026:                                                           \%allroles, \%allgroups);
1.1169    droeschl 6027:     $env{'user.adv'} = $userroles{'user.adv'};
1.1341    raeburn  6028:     $env{'user.rar'} = $userroles{'user.rar'};
1.1169    droeschl 6029: 
1.1162    raeburn  6030:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      6031: }
                   6032: 
1.567     raeburn  6033: sub set_arearole {
1.1215    raeburn  6034:     my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
                   6035:     unless ($nolog) {
1.567     raeburn  6036: # log the associated role with the area
1.1215    raeburn  6037:         &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
                   6038:     }
1.743     albertel 6039:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  6040: }
                   6041: 
                   6042: sub custom_roleprivs {
                   6043:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   6044:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
1.1250    raeburn  6045:     my $homsvr = &homeserver($rauthor,$rdomain);
1.838     albertel 6046:     if (&hostname($homsvr) ne '') {
1.567     raeburn  6047:         my ($rdummy,$roledef)=
                   6048:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   6049:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   6050:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   6051:             if (defined($syspriv)) {
1.1043    raeburn  6052:                 if ($trest =~ /^$match_community$/) {
                   6053:                     $syspriv =~ s/bre\&S//; 
                   6054:                 }
1.567     raeburn  6055:                 $$allroles{'cm./'}.=':'.$syspriv;
                   6056:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   6057:             }
                   6058:             if ($tdomain ne '') {
                   6059:                 if (defined($dompriv)) {
                   6060:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   6061:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   6062:                 }
                   6063:                 if (($trest ne '') && (defined($coursepriv))) {
1.1332    raeburn  6064:                     if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
                   6065:                         my $rolename = $1;
                   6066:                         $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
                   6067:                     }
1.567     raeburn  6068:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   6069:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   6070:                 }
                   6071:             }
                   6072:         }
                   6073:     }
                   6074: }
                   6075: 
1.1332    raeburn  6076: sub course_adhocrole_privs {
                   6077:     my ($rolename,$cdom,$cnum,$coursepriv) = @_;
                   6078:     my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
                   6079:     if ($overrides{"internal.adhocpriv.$rolename"}) {
                   6080:         my (%currprivs,%storeprivs);
                   6081:         foreach my $item (split(/:/,$coursepriv)) {
                   6082:             my ($priv,$restrict) = split(/\&/,$item);
                   6083:             $currprivs{$priv} = $restrict;
                   6084:         }
                   6085:         my (%possadd,%possremove,%full);
                   6086:         foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
                   6087:             my ($priv,$restrict)=split(/\&/,$item);
                   6088:             $full{$priv} = $restrict;
                   6089:         }
                   6090:         foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
                   6091:              next if ($item eq '');
                   6092:              my ($rule,$rest) = split(/=/,$item);
                   6093:              next unless (($rule eq 'off') || ($rule eq 'on'));
                   6094:              foreach my $priv (split(/:/,$rest)) {
                   6095:                  if ($priv ne '') {
                   6096:                      if ($rule eq 'off') {
                   6097:                          $possremove{$priv} = 1;
                   6098:                      } else {
                   6099:                          $possadd{$priv} = 1;
                   6100:                      }
                   6101:                  }
                   6102:              }
                   6103:          }
                   6104:          foreach my $priv (sort(keys(%full))) {
                   6105:              if (exists($currprivs{$priv})) {
                   6106:                  unless (exists($possremove{$priv})) {
                   6107:                      $storeprivs{$priv} = $currprivs{$priv};
                   6108:                  }
                   6109:              } elsif (exists($possadd{$priv})) {
                   6110:                  $storeprivs{$priv} = $full{$priv};
                   6111:              }
                   6112:          }
                   6113:          $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
                   6114:      }
                   6115:      return $coursepriv;
                   6116: }
                   6117: 
1.678     raeburn  6118: sub group_roleprivs {
                   6119:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   6120:     my $access = 1;
                   6121:     my $now = time;
                   6122:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   6123:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   6124:     if ($access) {
1.811     albertel 6125:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  6126:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   6127:     }
                   6128: }
1.567     raeburn  6129: 
                   6130: sub standard_roleprivs {
                   6131:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   6132:     if (defined($pr{$trole.':s'})) {
                   6133:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   6134:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   6135:     }
                   6136:     if ($tdomain ne '') {
                   6137:         if (defined($pr{$trole.':d'})) {
                   6138:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6139:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   6140:         }
                   6141:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   6142:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   6143:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   6144:         }
                   6145:     }
                   6146: }
                   6147: 
                   6148: sub set_userprivs {
1.1064    raeburn  6149:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  6150:     my $author=0;
                   6151:     my $adv=0;
1.1341    raeburn  6152:     my $rar=0;
1.678     raeburn  6153:     my %grouproles = ();
                   6154:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  6155:         my @groupkeys; 
1.1000    raeburn  6156:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  6157:             push(@groupkeys,$role);
                   6158:         }
                   6159:         if (ref($groups_roles) eq 'HASH') {
                   6160:             foreach my $key (keys(%{$groups_roles})) {
                   6161:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   6162:                     push(@groupkeys,$key);
                   6163:                 }
                   6164:             }
                   6165:         }
                   6166:         if (@groupkeys > 0) {
                   6167:             foreach my $role (@groupkeys) {
                   6168:                 my ($trole,$area,$sec,$extendedarea);
                   6169:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   6170:                     $trole = $1;
                   6171:                     $area = $2;
                   6172:                     $sec = $3;
                   6173:                     $extendedarea = $area.$sec;
                   6174:                     if (exists($$allgroups{$area})) {
                   6175:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   6176:                             my $spec = $trole.'.'.$extendedarea;
                   6177:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  6178:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  6179:                         }
1.678     raeburn  6180:                     }
                   6181:                 }
                   6182:             }
                   6183:         }
                   6184:     }
1.800     albertel 6185:     foreach my $group (keys(%grouproles)) {
                   6186:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  6187:     }
1.800     albertel 6188:     foreach my $role (keys(%{$allroles})) {
                   6189:         my %thesepriv;
1.941     raeburn  6190:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 6191:         foreach my $item (split(/:/,$$allroles{$role})) {
                   6192:             if ($item ne '') {
                   6193:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  6194:                 if ($restrictions eq '') {
                   6195:                     $thesepriv{$privilege}='F';
                   6196:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   6197:                     $thesepriv{$privilege}.=$restrictions;
                   6198:                 }
                   6199:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
1.1341    raeburn  6200:                 if ($thesepriv{'rar'} eq 'F') { $rar=1; }
1.567     raeburn  6201:             }
                   6202:         }
                   6203:         my $thesestr='';
1.1104    raeburn  6204:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 6205: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   6206: 	}
                   6207:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  6208:     }
1.1341    raeburn  6209:     return ($author,$adv,$rar);
1.567     raeburn  6210: }
                   6211: 
1.994     raeburn  6212: sub role_status {
1.1104    raeburn  6213:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  6214:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
1.1250    raeburn  6215:         my ($one,$two) = split(m{\./},$rolekey,2);
                   6216:         (undef,undef,$$role) = split(/\./,$one,3);
1.994     raeburn  6217:         unless (!defined($$role) || $$role eq '') {
1.1251    raeburn  6218:             $$where = '/'.$two;
1.994     raeburn  6219:             $$trolecode=$$role.'.'.$$where;
                   6220:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   6221:             $$tstatus='is';
1.1104    raeburn  6222:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  6223:                 $$tstatus='future';
1.1034    raeburn  6224:                 if ($$tstart<$now) {
                   6225:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  6226:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  6227:                             my (%allroles,%allgroups,$group_privs,
                   6228:                                 %groups_roles,@rolecodes);
1.1002    raeburn  6229:                             my %userroles = (
                   6230:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   6231:                             );
1.1064    raeburn  6232:                             @rolecodes = ('cm'); 
1.1002    raeburn  6233:                             my $spec=$$role.'.'.$$where;
                   6234:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   6235:                             if ($$role =~ /^cr\//) {
                   6236:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  6237:                                 push(@rolecodes,'cr');
1.1002    raeburn  6238:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  6239:                                 push(@rolecodes,$$role);
1.1002    raeburn  6240:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   6241:                                                     $env{'user.name'});
1.1064    raeburn  6242:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  6243:                                 (undef,my $group_privs) = split(/\//,$trole);
                   6244:                                 $group_privs = &unescape($group_privs);
                   6245:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  6246:                                 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  6247:                                 &get_groups_roles($tdomain,$trest,
                   6248:                                                   \%course_roles,\@rolecodes,
                   6249:                                                   \%groups_roles);
1.1002    raeburn  6250:                             } else {
1.1064    raeburn  6251:                                 push(@rolecodes,$$role);
1.1002    raeburn  6252:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   6253:                             }
1.1341    raeburn  6254:                             my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
                   6255:                                                                    \%groups_roles);
1.1064    raeburn  6256:                             &appenv(\%userroles,\@rolecodes);
1.1342    raeburn  6257:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1002    raeburn  6258:                         }
                   6259:                     }
1.1034    raeburn  6260:                     $$tstatus = 'is';
1.1002    raeburn  6261:                 }
1.994     raeburn  6262:             }
                   6263:             if ($$tend) {
1.1104    raeburn  6264:                 if ($$tend<$update) {
1.994     raeburn  6265:                     $$tstatus='expired';
                   6266:                 } elsif ($$tend<$now) {
                   6267:                     $$tstatus='will_not';
                   6268:                 }
                   6269:             }
                   6270:         }
                   6271:     }
                   6272: }
                   6273: 
1.1104    raeburn  6274: sub get_groups_roles {
                   6275:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   6276:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   6277:                   (ref($rolecodes) eq 'ARRAY') && 
                   6278:                   (ref($groups_roles) eq 'HASH')); 
                   6279:     if (keys(%{$cdom_courseroles}) > 0) {
                   6280:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   6281:         if ($cdom ne '' && $cnum ne '') {
                   6282:             foreach my $key (keys(%{$cdom_courseroles})) {
                   6283:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   6284:                     my $crsrole = $1;
                   6285:                     my $crssec = $2;
                   6286:                     if ($crsrole =~ /^cr/) {
                   6287:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   6288:                             push(@{$rolecodes},'cr');
                   6289:                         }
                   6290:                     } else {
                   6291:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   6292:                             push(@{$rolecodes},$crsrole);
                   6293:                         }
                   6294:                     }
                   6295:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   6296:                     if ($crssec ne '') {
                   6297:                         $rolekey .= "/$crssec";
                   6298:                     }
                   6299:                     $rolekey .= './';
                   6300:                     $groups_roles->{$rolekey} = $rolecodes;
                   6301:                 }
                   6302:             }
                   6303:         }
                   6304:     }
                   6305:     return;
                   6306: }
                   6307: 
                   6308: sub delete_env_groupprivs {
                   6309:     my ($where,$courseroles,$possroles) = @_;
                   6310:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   6311:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   6312:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   6313:         %{$courseroles->{$udom}} =
                   6314:             &get_my_roles('','','userroles',['active'],
                   6315:                           $possroles,[$udom],1);
                   6316:     }
                   6317:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   6318:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   6319:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   6320:             my $area = '/'.$cdom.'/'.$cnum;
                   6321:             my $privkey = "user.priv.$crsrole.$area";
                   6322:             if ($crssec ne '') {
                   6323:                 $privkey .= '/'.$crssec;
                   6324:             }
                   6325:             $privkey .= ".$area/$group";
                   6326:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   6327:         }
                   6328:     }
                   6329:     return;
                   6330: }
                   6331: 
1.994     raeburn  6332: sub check_adhoc_privs {
1.1329    raeburn  6333:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
1.994     raeburn  6334:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
1.1329    raeburn  6335:     if ($sec) {
                   6336:         $cckey .= '/'.$sec;
                   6337:     } 
1.1185    raeburn  6338:     my $setprivs;
1.994     raeburn  6339:     if ($env{$cckey}) {
                   6340:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  6341:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  6342:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1329    raeburn  6343:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6344:             $setprivs = 1;
1.994     raeburn  6345:         }
                   6346:     } else {
1.1330    raeburn  6347:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
1.1185    raeburn  6348:         $setprivs = 1;
1.994     raeburn  6349:     }
1.1185    raeburn  6350:     return $setprivs;
1.994     raeburn  6351: }
                   6352: 
                   6353: sub set_adhoc_privileges {
1.1326    raeburn  6354: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
1.1329    raeburn  6355:     my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
1.994     raeburn  6356:     my $area = '/'.$dcdom.'/'.$pickedcourse;
1.1329    raeburn  6357:     if ($sec ne '') {
                   6358:         $area .= '/'.$sec;
                   6359:     }
1.994     raeburn  6360:     my $spec = $role.'.'.$area;
                   6361:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
1.1215    raeburn  6362:                                   $env{'user.name'},1);
1.1326    raeburn  6363:     my %rolehash = ();
1.1332    raeburn  6364:     if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
                   6365:         my $rolename = $1;
1.1326    raeburn  6366:         &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
1.1332    raeburn  6367:         my %domdef = &get_domain_defaults($dcdom);
                   6368:         if (ref($domdef{'adhocroles'}) eq 'HASH') {
                   6369:             if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
                   6370:                 &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
                   6371:             }
                   6372:         }
1.1326    raeburn  6373:     } else {
                   6374:         &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
                   6375:     }
1.1341    raeburn  6376:     my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
1.994     raeburn  6377:     &appenv(\%userroles,[$role,'cm']);
1.1342    raeburn  6378:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
1.1088    raeburn  6379:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   6380:         &appenv( {'request.role'        => $spec,
                   6381:                   'request.role.domain' => $dcdom,
1.1332    raeburn  6382:                   'request.course.sec'  => $sec,
1.1088    raeburn  6383:                  }
                   6384:                );
                   6385:         my $tadv=0;
                   6386:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   6387:         &appenv({'request.role.adv'    => $tadv});
                   6388:     }
1.994     raeburn  6389: }
                   6390: 
1.12      www      6391: # --------------------------------------------------------------- get interface
                   6392: 
                   6393: sub get {
1.131     albertel 6394:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6395:    my $items='';
1.800     albertel 6396:    foreach my $item (@$storearr) {
                   6397:        $items.=&escape($item).'&';
1.191     harris41 6398:    }
1.12      www      6399:    $items=~s/\&$//;
1.620     albertel 6400:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6401:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 6402:    my $uhome=&homeserver($uname,$udomain);
                   6403: 
1.133     albertel 6404:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6405:    my @pairs=split(/\&/,$rep);
1.273     albertel 6406:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   6407:      return @pairs;
                   6408:    }
1.15      www      6409:    my %returnhash=();
1.42      www      6410:    my $i=0;
1.800     albertel 6411:    foreach my $item (@$storearr) {
                   6412:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6413:       $i++;
1.191     harris41 6414:    }
1.15      www      6415:    return %returnhash;
1.27      www      6416: }
                   6417: 
                   6418: # --------------------------------------------------------------- del interface
                   6419: 
                   6420: sub del {
1.133     albertel 6421:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      6422:    my $items='';
1.800     albertel 6423:    foreach my $item (@$storearr) {
                   6424:        $items.=&escape($item).'&';
1.191     harris41 6425:    }
1.984     neumanie 6426: 
1.27      www      6427:    $items=~s/\&$//;
1.620     albertel 6428:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6429:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6430:    my $uhome=&homeserver($uname,$udomain);
                   6431:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      6432: }
                   6433: 
                   6434: # -------------------------------------------------------------- dump interface
                   6435: 
1.1180    droeschl 6436: sub unserialize {
                   6437:     my ($rep, $escapedkeys) = @_;
                   6438: 
                   6439:     return {} if $rep =~ /^error/;
                   6440: 
                   6441:     my %returnhash=();
1.1252    raeburn  6442: 	foreach my $item (split(/\&/,$rep)) {
1.1180    droeschl 6443: 	    my ($key, $value) = split(/=/, $item, 2);
                   6444: 	    $key = unescape($key) unless $escapedkeys;
                   6445: 	    next if $key =~ /^error: 2 /;
1.1252    raeburn  6446: 	    $returnhash{$key} = &thaw_unescape($value);
1.1180    droeschl 6447: 	}
                   6448:     #return %returnhash;
                   6449:     return \%returnhash;
                   6450: }        
                   6451: 
                   6452: # see Lond::dump_with_regexp
                   6453: # if $escapedkeys hash keys won't get unescaped.
1.15      www      6454: sub dump {
1.1180    droeschl 6455:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 6456:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6457:     if (!$uname) { $uname=$env{'user.name'}; }
                   6458:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 6459: 
1.1266    raeburn  6460:     if ($regexp) {
                   6461:         $regexp=&escape($regexp);
                   6462:     } else {
                   6463:         $regexp='.';
                   6464:     }
1.1180    droeschl 6465:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   6466:         # user is hosted on this machine
1.1266    raeburn  6467:         my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
1.1226    raeburn  6468:                     $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
1.1180    droeschl 6469:         return %{unserialize($reply, $escapedkeys)};
                   6470:     }
1.1166    raeburn  6471:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 6472:     my @pairs=split(/\&/,$rep);
                   6473:     my %returnhash=();
1.1098    foxr     6474:     if (!($rep =~ /^error/ )) {
                   6475: 	foreach my $item (@pairs) {
                   6476: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 6477:         $key = unescape($key) unless $escapedkeys;
                   6478:         #$key = &unescape($key);
1.1098    foxr     6479: 	    next if ($key =~ /^error: 2 /);
                   6480: 	    $returnhash{$key}=&thaw_unescape($value);
                   6481: 	}
1.755     albertel 6482:     }
                   6483:     return %returnhash;
1.407     www      6484: }
                   6485: 
1.1098    foxr     6486: 
1.717     albertel 6487: # --------------------------------------------------------- dumpstore interface
                   6488: 
                   6489: sub dumpstore {
                   6490:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 6491:    # same as dump but keys must be escaped. They may contain colon separated
                   6492:    # lists of values that may themself contain colons (e.g. symbs).
                   6493:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 6494: }
                   6495: 
1.407     www      6496: # -------------------------------------------------------------- keys interface
                   6497: 
                   6498: sub getkeys {
                   6499:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 6500:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6501:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      6502:    my $uhome=&homeserver($uname,$udomain);
                   6503:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   6504:    my @keyarray=();
1.800     albertel 6505:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  6506:       next if ($key =~ /^error: 2 /);
1.800     albertel 6507:       push(@keyarray,&unescape($key));
1.407     www      6508:    }
                   6509:    return @keyarray;
1.318     matthew  6510: }
                   6511: 
1.319     matthew  6512: # --------------------------------------------------------------- currentdump
                   6513: sub currentdump {
1.328     matthew  6514:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 6515:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   6516:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   6517:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  6518:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 6519:    my $rep;
                   6520: 
                   6521:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   6522:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   6523:                    $courseid)));
                   6524:    } else {
                   6525:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   6526:    }
                   6527: 
1.318     matthew  6528:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  6529:    #
1.318     matthew  6530:    my %returnhash=();
1.319     matthew  6531:    #
1.1343    raeburn  6532:    if ($rep eq 'unknown_cmd') {
1.319     matthew  6533:        # an old lond will not know currentdump
                   6534:        # Do a dump and make it look like a currentdump
1.822     albertel 6535:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  6536:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   6537:        my %hash = @tmp;
                   6538:        @tmp=();
1.424     matthew  6539:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  6540:    } else {
                   6541:        my @pairs=split(/\&/,$rep);
1.800     albertel 6542:        foreach my $pair (@pairs) {
                   6543:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  6544:            my ($symb,$param) = split(/:/,$key);
                   6545:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 6546:                                                         &thaw_unescape($value);
1.319     matthew  6547:        }
1.191     harris41 6548:    }
1.12      www      6549:    return %returnhash;
1.424     matthew  6550: }
                   6551: 
                   6552: sub convert_dump_to_currentdump{
                   6553:     my %hash = %{shift()};
                   6554:     my %returnhash;
                   6555:     # Code ripped from lond, essentially.  The only difference
                   6556:     # here is the unescaping done by lonnet::dump().  Conceivably
                   6557:     # we might run in to problems with parameter names =~ /^v\./
                   6558:     while (my ($key,$value) = each(%hash)) {
                   6559:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 6560: 	$symb  = &unescape($symb);
                   6561: 	$param = &unescape($param);
1.424     matthew  6562:         next if ($v eq 'version' || $symb eq 'keys');
                   6563:         next if (exists($returnhash{$symb}) &&
                   6564:                  exists($returnhash{$symb}->{$param}) &&
                   6565:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   6566:         $returnhash{$symb}->{$param}=$value;
                   6567:         $returnhash{$symb}->{'v.'.$param}=$v;
                   6568:     }
                   6569:     #
                   6570:     # Remove all of the keys in the hashes which keep track of
                   6571:     # the version of the parameter.
                   6572:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   6573:         # use a foreach because we are going to delete from the hash.
                   6574:         foreach my $key (keys(%$param_hash)) {
                   6575:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   6576:         }
                   6577:     }
                   6578:     return \%returnhash;
1.12      www      6579: }
                   6580: 
1.627     albertel 6581: # ------------------------------------------------------ critical inc interface
                   6582: 
                   6583: sub cinc {
                   6584:     return &inc(@_,'critical');
                   6585: }
                   6586: 
1.449     matthew  6587: # --------------------------------------------------------------- inc interface
                   6588: 
                   6589: sub inc {
1.627     albertel 6590:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 6591:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6592:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  6593:     my $uhome=&homeserver($uname,$udomain);
                   6594:     my $items='';
                   6595:     if (! ref($store)) {
                   6596:         # got a single value, so use that instead
                   6597:         $items = &escape($store).'=&';
                   6598:     } elsif (ref($store) eq 'SCALAR') {
                   6599:         $items = &escape($$store).'=&';        
                   6600:     } elsif (ref($store) eq 'ARRAY') {
                   6601:         $items = join('=&',map {&escape($_);} @{$store});
                   6602:     } elsif (ref($store) eq 'HASH') {
                   6603:         while (my($key,$value) = each(%{$store})) {
                   6604:             $items.= &escape($key).'='.&escape($value).'&';
                   6605:         }
                   6606:     }
                   6607:     $items=~s/\&$//;
1.627     albertel 6608:     if ($critical) {
                   6609: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6610:     } else {
                   6611: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   6612:     }
1.449     matthew  6613: }
                   6614: 
1.12      www      6615: # --------------------------------------------------------------- put interface
                   6616: 
                   6617: sub put {
1.134     albertel 6618:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6619:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6620:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6621:    my $uhome=&homeserver($uname,$udomain);
1.12      www      6622:    my $items='';
1.800     albertel 6623:    foreach my $item (keys(%$storehash)) {
                   6624:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6625:    }
1.12      www      6626:    $items=~s/\&$//;
1.134     albertel 6627:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      6628: }
                   6629: 
1.631     albertel 6630: # ------------------------------------------------------------ newput interface
                   6631: 
                   6632: sub newput {
                   6633:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   6634:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6635:    if (!$uname) { $uname=$env{'user.name'}; }
                   6636:    my $uhome=&homeserver($uname,$udomain);
                   6637:    my $items='';
                   6638:    foreach my $key (keys(%$storehash)) {
                   6639:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   6640:    }
                   6641:    $items=~s/\&$//;
                   6642:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   6643: }
                   6644: 
                   6645: # ---------------------------------------------------------  putstore interface
                   6646: 
1.524     raeburn  6647: sub putstore {
1.1269    raeburn  6648:    my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
1.620     albertel 6649:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6650:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  6651:    my $uhome=&homeserver($uname,$udomain);
                   6652:    my $items='';
1.715     albertel 6653:    foreach my $key (keys(%$storehash)) {
                   6654:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  6655:    }
1.715     albertel 6656:    $items=~s/\&$//;
1.716     albertel 6657:    my $esc_symb=&escape($symb);
                   6658:    my $esc_v=&escape($version);
1.715     albertel 6659:    my $reply =
1.716     albertel 6660:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 6661: 	      $uhome);
1.1269    raeburn  6662:    if (($tolog) && ($reply eq 'ok')) {
                   6663:        my $namevalue='';
                   6664:        foreach my $key (keys(%{$storehash})) {
                   6665:            $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
                   6666:        }
                   6667:        $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
                   6668:                      '&host='.&escape($perlvar{'lonHostID'}).
                   6669:                      '&version='.$esc_v.
                   6670:                      '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
                   6671:        &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
                   6672:    }
1.715     albertel 6673:    if ($reply eq 'unknown_cmd') {
1.716     albertel 6674:        # gfall back to way things use to be done
1.715     albertel 6675:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   6676: 			    $uname);
1.524     raeburn  6677:    }
1.715     albertel 6678:    return $reply;
                   6679: }
                   6680: 
                   6681: sub old_putstore {
1.716     albertel 6682:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   6683:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6684:     if (!$uname) { $uname=$env{'user.name'}; }
                   6685:     my $uhome=&homeserver($uname,$udomain);
                   6686:     my %newstorehash;
1.800     albertel 6687:     foreach my $item (keys(%$storehash)) {
                   6688: 	my $key = $version.':'.&escape($symb).':'.$item;
                   6689: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 6690:     }
                   6691:     my $items='';
                   6692:     my %allitems = ();
1.800     albertel 6693:     foreach my $item (keys(%newstorehash)) {
                   6694: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 6695: 	    my $key = $1.':keys:'.$2;
                   6696: 	    $allitems{$key} .= $3.':';
                   6697: 	}
1.800     albertel 6698: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 6699:     }
1.800     albertel 6700:     foreach my $item (keys(%allitems)) {
                   6701: 	$allitems{$item} =~ s/\:$//;
                   6702: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 6703:     }
                   6704:     $items=~s/\&$//;
                   6705:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  6706: }
                   6707: 
1.47      www      6708: # ------------------------------------------------------ critical put interface
                   6709: 
                   6710: sub cput {
1.134     albertel 6711:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 6712:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6713:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 6714:    my $uhome=&homeserver($uname,$udomain);
1.47      www      6715:    my $items='';
1.800     albertel 6716:    foreach my $item (keys(%$storehash)) {
                   6717:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 6718:    }
1.47      www      6719:    $items=~s/\&$//;
1.134     albertel 6720:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6721: }
                   6722: 
                   6723: # -------------------------------------------------------------- eget interface
                   6724: 
                   6725: sub eget {
1.133     albertel 6726:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      6727:    my $items='';
1.800     albertel 6728:    foreach my $item (@$storearr) {
                   6729:        $items.=&escape($item).'&';
1.191     harris41 6730:    }
1.12      www      6731:    $items=~s/\&$//;
1.620     albertel 6732:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   6733:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 6734:    my $uhome=&homeserver($uname,$udomain);
                   6735:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      6736:    my @pairs=split(/\&/,$rep);
                   6737:    my %returnhash=();
1.42      www      6738:    my $i=0;
1.800     albertel 6739:    foreach my $item (@$storearr) {
                   6740:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      6741:       $i++;
1.191     harris41 6742:    }
1.12      www      6743:    return %returnhash;
                   6744: }
                   6745: 
1.667     albertel 6746: # ------------------------------------------------------------ tmpput interface
                   6747: sub tmpput {
1.802     raeburn  6748:     my ($storehash,$server,$context)=@_;
1.667     albertel 6749:     my $items='';
1.800     albertel 6750:     foreach my $item (keys(%$storehash)) {
                   6751: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 6752:     }
                   6753:     $items=~s/\&$//;
1.802     raeburn  6754:     if (defined($context)) {
                   6755:         $items .= ':'.&escape($context);
                   6756:     }
1.667     albertel 6757:     return &reply("tmpput:$items",$server);
                   6758: }
                   6759: 
                   6760: # ------------------------------------------------------------ tmpget interface
                   6761: sub tmpget {
1.688     albertel 6762:     my ($token,$server)=@_;
                   6763:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6764:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 6765:     my %returnhash;
1.1328    raeburn  6766:     if ($rep =~ /^(con_lost|error|no_such_host)/i) {
                   6767:         return %returnhash;
                   6768:     }
1.667     albertel 6769:     foreach my $item (split(/\&/,$rep)) {
                   6770: 	my ($key,$value)=split(/=/,$item);
                   6771: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   6772:     }
                   6773:     return %returnhash;
                   6774: }
                   6775: 
1.1113    raeburn  6776: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 6777: sub tmpdel {
                   6778:     my ($token,$server)=@_;
                   6779:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   6780:     return &reply("tmpdel:$token",$server);
                   6781: }
                   6782: 
1.1198    raeburn  6783: # ------------------------------------------------------------ get_timebased_id 
                   6784: 
                   6785: sub get_timebased_id {
                   6786:     my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
                   6787:         $maxtries) = @_;
                   6788:     my ($newid,$error,$dellock);
                   6789:     unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {  
                   6790:         return ('','ok','invalid call to get suffix');
                   6791:     }
                   6792: 
                   6793: # set defaults for any optional args for which values were not supplied
                   6794:     if ($who eq '') {
                   6795:         $who = $env{'user.name'}.':'.$env{'user.domain'};
                   6796:     }
                   6797:     if (!$locktries) {
                   6798:         $locktries = 3;
                   6799:     }
                   6800:     if (!$maxtries) {
                   6801:         $maxtries = 10;
                   6802:     }
                   6803:     
                   6804:     if (($cdom eq '') || ($cnum eq '')) {
                   6805:         if ($env{'request.course.id'}) {
                   6806:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6807:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6808:         }
                   6809:         if (($cdom eq '') || ($cnum eq '')) {
                   6810:             return ('','ok','call to get suffix not in course context');
                   6811:         }
                   6812:     }
                   6813: 
                   6814: # construct locking item
                   6815:     my $lockhash = {
                   6816:                       $prefix."\0".'locked_'.$keyid => $who,
                   6817:                    };
                   6818:     my $tries = 0;
                   6819: 
                   6820: # attempt to get lock on nohist_$namespace file
                   6821:     my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6822:     while (($gotlock ne 'ok') && $tries <$locktries) {
                   6823:         $tries ++;
                   6824:         sleep 1;
                   6825:         $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
                   6826:     }
                   6827: 
                   6828: # attempt to get unique identifier, based on current timestamp
                   6829:     if ($gotlock eq 'ok') {
                   6830:         my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
                   6831:         my $id = time;
                   6832:         $newid = $id;
1.1268    raeburn  6833:         if ($idtype eq 'addcode') {
                   6834:             $newid .= &sixnum_code();
                   6835:         }
1.1198    raeburn  6836:         my $idtries = 0;
                   6837:         while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
                   6838:             if ($idtype eq 'concat') {
                   6839:                 $newid = $id.$idtries;
1.1268    raeburn  6840:             } elsif ($idtype eq 'addcode') {
                   6841:                 $newid = $newid.&sixnum_code();
1.1198    raeburn  6842:             } else {
                   6843:                 $newid ++;
                   6844:             }
                   6845:             $idtries ++;
                   6846:         }
                   6847:         if (!exists($inuse{$prefix."\0".$newid})) {
                   6848:             my %new_item =  (
                   6849:                               $prefix."\0".$newid => $who,
                   6850:                             );
                   6851:             my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
                   6852:                                                  $cdom,$cnum);
                   6853:             if ($putresult ne 'ok') {
                   6854:                 undef($newid);
                   6855:                 $error = 'error saving new item: '.$putresult;
                   6856:             }
                   6857:         } else {
1.1268    raeburn  6858:              undef($newid);
1.1198    raeburn  6859:              $error = ('error: no unique suffix available for the new item ');
                   6860:         }
                   6861: #  remove lock
                   6862:         my @del_lock = ($prefix."\0".'locked_'.$keyid);
                   6863:         $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
                   6864:     } else {
                   6865:         $error = "error: could not obtain lockfile\n";
                   6866:         $dellock = 'ok';
1.1276    raeburn  6867:         if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
                   6868:             $dellock = 'nolock';
                   6869:         }
1.1198    raeburn  6870:     }
                   6871:     return ($newid,$dellock,$error);
                   6872: }
                   6873: 
1.1268    raeburn  6874: sub sixnum_code {
                   6875:     my $code;
                   6876:     for (0..6) {
                   6877:         $code .= int( rand(9) );
                   6878:     }
                   6879:     return $code;
                   6880: }
                   6881: 
1.765     albertel 6882: # -------------------------------------------------- portfolio access checking
                   6883: 
                   6884: sub portfolio_access {
1.1270    raeburn  6885:     my ($requrl,$clientip) = @_;
1.765     albertel 6886:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
1.1270    raeburn  6887:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
1.814     raeburn  6888:     if ($result) {
                   6889:         my %setters;
                   6890:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6891:             my ($startblock,$endblock) =
                   6892:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   6893:             if ($startblock && $endblock) {
                   6894:                 return 'B';
                   6895:             }
                   6896:         } else {
                   6897:             my ($startblock,$endblock) =
                   6898:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   6899:             if ($startblock && $endblock) {
                   6900:                 return 'B';
                   6901:             }
                   6902:         }
                   6903:     }
1.765     albertel 6904:     if ($result eq 'ok') {
1.766     albertel 6905:        return 'F';
1.765     albertel 6906:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 6907:        return 'A';
1.765     albertel 6908:     }
1.766     albertel 6909:     return '';
1.765     albertel 6910: }
                   6911: 
                   6912: sub get_portfolio_access {
1.1270    raeburn  6913:     my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
1.767     albertel 6914: 
                   6915:     if (!ref($access_hash)) {
                   6916: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   6917: 	my %access_controls = &get_access_controls($current_perms,$group,
                   6918: 						   $file_name);
                   6919: 	$access_hash = $access_controls{$file_name};
                   6920:     }
                   6921: 
1.1270    raeburn  6922:     my ($public,$guest,@domains,@users,@courses,@groups,@ips);
1.765     albertel 6923:     my $now = time;
                   6924:     if (ref($access_hash) eq 'HASH') {
                   6925:         foreach my $key (keys(%{$access_hash})) {
                   6926:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   6927:             if ($start > $now) {
                   6928:                 next;
                   6929:             }
                   6930:             if ($end && $end<$now) {
                   6931:                 next;
                   6932:             }
                   6933:             if ($scope eq 'public') {
                   6934:                 $public = $key;
                   6935:                 last;
                   6936:             } elsif ($scope eq 'guest') {
                   6937:                 $guest = $key;
                   6938:             } elsif ($scope eq 'domains') {
                   6939:                 push(@domains,$key);
                   6940:             } elsif ($scope eq 'users') {
                   6941:                 push(@users,$key);
                   6942:             } elsif ($scope eq 'course') {
                   6943:                 push(@courses,$key);
                   6944:             } elsif ($scope eq 'group') {
                   6945:                 push(@groups,$key);
1.1270    raeburn  6946:             } elsif ($scope eq 'ip') {
                   6947:                 push(@ips,$key);
1.765     albertel 6948:             }
                   6949:         }
                   6950:         if ($public) {
                   6951:             return 'ok';
1.1270    raeburn  6952:         } elsif (@ips > 0) {
                   6953:             my $allowed;
                   6954:             foreach my $ipkey (@ips) {
                   6955:                 if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
                   6956:                     if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
                   6957:                         $allowed = 1;
                   6958:                         last; 
                   6959:                     }
                   6960:                 }
                   6961:             }
                   6962:             if ($allowed) {
                   6963:                 return 'ok';
                   6964:             }
1.765     albertel 6965:         }
                   6966:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   6967:             if ($guest) {
                   6968:                 return $guest;
                   6969:             }
                   6970:         } else {
                   6971:             if (@domains > 0) {
                   6972:                 foreach my $domkey (@domains) {
                   6973:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   6974:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   6975:                             return 'ok';
                   6976:                         }
                   6977:                     }
                   6978:                 }
                   6979:             }
                   6980:             if (@users > 0) {
                   6981:                 foreach my $userkey (@users) {
1.865     raeburn  6982:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   6983:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   6984:                             if (ref($item) eq 'HASH') {
                   6985:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   6986:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   6987:                                     return 'ok';
                   6988:                                 }
                   6989:                             }
                   6990:                         }
                   6991:                     } 
1.765     albertel 6992:                 }
                   6993:             }
                   6994:             my %roleshash;
                   6995:             my @courses_and_groups = @courses;
                   6996:             push(@courses_and_groups,@groups); 
                   6997:             if (@courses_and_groups > 0) {
                   6998:                 my (%allgroups,%allroles); 
                   6999:                 my ($start,$end,$role,$sec,$group);
                   7000:                 foreach my $envkey (%env) {
1.1060    raeburn  7001:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7002:                         my $cid = $2.'_'.$3; 
                   7003:                         if ($1 eq 'gr') {
                   7004:                             $group = $4;
                   7005:                             $allgroups{$cid}{$group} = $env{$envkey};
                   7006:                         } else {
                   7007:                             if ($4 eq '') {
                   7008:                                 $sec = 'none';
                   7009:                             } else {
                   7010:                                 $sec = $4;
                   7011:                             }
                   7012:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7013:                         }
1.811     albertel 7014:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 7015:                         my $cid = $2.'_'.$3;
                   7016:                         if ($4 eq '') {
                   7017:                             $sec = 'none';
                   7018:                         } else {
                   7019:                             $sec = $4;
                   7020:                         }
                   7021:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   7022:                     }
                   7023:                 }
                   7024:                 if (keys(%allroles) == 0) {
                   7025:                     return;
                   7026:                 }
                   7027:                 foreach my $key (@courses_and_groups) {
                   7028:                     my %content = %{$$access_hash{$key}};
                   7029:                     my $cnum = $content{'number'};
                   7030:                     my $cdom = $content{'domain'};
                   7031:                     my $cid = $cdom.'_'.$cnum;
                   7032:                     if (!exists($allroles{$cid})) {
                   7033:                         next;
                   7034:                     }    
                   7035:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   7036:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   7037:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   7038:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   7039:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   7040:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   7041:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   7042:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   7043:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   7044:                                         if (grep/^all$/,@sections) {
                   7045:                                             return 'ok';
                   7046:                                         } else {
                   7047:                                             if (grep/^$sec$/,@sections) {
                   7048:                                                 return 'ok';
                   7049:                                             }
                   7050:                                         }
                   7051:                                     }
                   7052:                                 }
                   7053:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   7054:                                     if (grep/^none$/,@groups) {
                   7055:                                         return 'ok';
                   7056:                                     }
                   7057:                                 } else {
                   7058:                                     if (grep/^all$/,@groups) {
                   7059:                                         return 'ok';
                   7060:                                     } 
                   7061:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   7062:                                         if (grep/^$group$/,@groups) {
                   7063:                                             return 'ok';
                   7064:                                         }
                   7065:                                     }
                   7066:                                 } 
                   7067:                             }
                   7068:                         }
                   7069:                     }
                   7070:                 }
                   7071:             }
                   7072:             if ($guest) {
                   7073:                 return $guest;
                   7074:             }
                   7075:         }
                   7076:     }
                   7077:     return;
                   7078: }
                   7079: 
                   7080: sub course_group_datechecker {
                   7081:     my ($dates,$now,$status) = @_;
                   7082:     my ($start,$end) = split(/\./,$dates);
                   7083:     if (!$start && !$end) {
                   7084:         return 'ok';
                   7085:     }
                   7086:     if (grep/^active$/,@{$status}) {
                   7087:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   7088:             return 'ok';
                   7089:         }
                   7090:     }
                   7091:     if (grep/^previous$/,@{$status}) {
                   7092:         if ($end > $now ) {
                   7093:             return 'ok';
                   7094:         }
                   7095:     }
                   7096:     if (grep/^future$/,@{$status}) {
                   7097:         if ($start > $now) {
                   7098:             return 'ok';
                   7099:         }
                   7100:     }
                   7101:     return; 
                   7102: }
                   7103: 
                   7104: sub parse_portfolio_url {
                   7105:     my ($url) = @_;
                   7106: 
                   7107:     my ($type,$udom,$unum,$group,$file_name);
                   7108:     
1.823     albertel 7109:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 7110: 	$type = 1;
                   7111:         $udom = $1;
                   7112:         $unum = $2;
                   7113:         $file_name = $3;
1.823     albertel 7114:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 7115: 	$type = 2;
                   7116:         $udom = $1;
                   7117:         $unum = $2;
                   7118:         $group = $3;
                   7119:         $file_name = $3.'/'.$4;
                   7120:     }
                   7121:     if (wantarray) {
                   7122: 	return ($type,$udom,$unum,$file_name,$group);
                   7123:     }
                   7124:     return $type;
                   7125: }
                   7126: 
                   7127: sub is_portfolio_url {
                   7128:     my ($url) = @_;
                   7129:     return scalar(&parse_portfolio_url($url));
                   7130: }
                   7131: 
1.798     raeburn  7132: sub is_portfolio_file {
                   7133:     my ($file) = @_;
1.820     raeburn  7134:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  7135:         return 1;
                   7136:     }
                   7137:     return;
                   7138: }
                   7139: 
1.976     raeburn  7140: sub usertools_access {
1.1084    raeburn  7141:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  7142:     my ($access,%tools);
                   7143:     if ($context eq '') {
                   7144:         $context = 'tools';
                   7145:     }
                   7146:     if ($context eq 'requestcourses') {
                   7147:         %tools = (
                   7148:                       official   => 1,
                   7149:                       unofficial => 1,
1.1006    raeburn  7150:                       community  => 1,
1.1246    raeburn  7151:                       textbook   => 1,
1.1305    raeburn  7152:                       placement  => 1,
1.1368    raeburn  7153:                       lti        => 1,
1.985     raeburn  7154:                  );
1.1183    raeburn  7155:     } elsif ($context eq 'requestauthor') {
                   7156:         %tools = (
                   7157:                       requestauthor => 1,
                   7158:                  );
1.985     raeburn  7159:     } else {
                   7160:         %tools = (
                   7161:                       aboutme   => 1,
                   7162:                       blog      => 1,
1.1177    raeburn  7163:                       webdav    => 1,
1.985     raeburn  7164:                       portfolio => 1,
                   7165:                  );
                   7166:     }
1.976     raeburn  7167:     return if (!defined($tools{$tool}));
                   7168: 
1.1242    raeburn  7169:     if (($udom eq '') || ($uname eq '')) {
1.976     raeburn  7170:         $udom = $env{'user.domain'};
                   7171:         $uname = $env{'user.name'};
                   7172:     }
                   7173: 
1.978     raeburn  7174:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   7175:         if ($action ne 'reload') {
1.985     raeburn  7176:             if ($context eq 'requestcourses') {
                   7177:                 return $env{'environment.canrequest.'.$tool};
1.1183    raeburn  7178:             } elsif ($context eq 'requestauthor') {
                   7179:                 return $env{'environment.canrequest.author'};
1.985     raeburn  7180:             } else {
                   7181:                 return $env{'environment.availabletools.'.$tool};
                   7182:             }
                   7183:         }
1.976     raeburn  7184:     }
                   7185: 
1.1183    raeburn  7186:     my ($toolstatus,$inststatus,$envkey);
                   7187:     if ($context eq 'requestauthor') {
                   7188:         $envkey = $context; 
                   7189:     } else {
                   7190:         $envkey = $context.'.'.$tool;
                   7191:     }
1.976     raeburn  7192: 
1.985     raeburn  7193:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   7194:          ($action ne 'reload')) {
1.1183    raeburn  7195:         $toolstatus = $env{'environment.'.$envkey};
1.976     raeburn  7196:         $inststatus = $env{'environment.inststatus'};
                   7197:     } else {
1.1084    raeburn  7198:         if (ref($userenvref) eq 'HASH') {
1.1183    raeburn  7199:             $toolstatus = $userenvref->{$envkey};
1.1084    raeburn  7200:             $inststatus = $userenvref->{'inststatus'};
                   7201:         } else {
1.1183    raeburn  7202:             my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
                   7203:             $toolstatus = $userenv{$envkey};
1.1084    raeburn  7204:             $inststatus = $userenv{'inststatus'};
                   7205:         }
1.976     raeburn  7206:     }
                   7207: 
                   7208:     if ($toolstatus ne '') {
                   7209:         if ($toolstatus) {
                   7210:             $access = 1;
                   7211:         } else {
                   7212:             $access = 0;
                   7213:         }
                   7214:         return $access;
                   7215:     }
                   7216: 
1.1084    raeburn  7217:     my ($is_adv,%domdef);
                   7218:     if (ref($is_advref) eq 'HASH') {
                   7219:         $is_adv = $is_advref->{'is_adv'};
                   7220:     } else {
                   7221:         $is_adv = &is_advanced_user($udom,$uname);
                   7222:     }
                   7223:     if (ref($domdefref) eq 'HASH') {
                   7224:         %domdef = %{$domdefref};
                   7225:     } else {
                   7226:         %domdef = &get_domain_defaults($udom);
                   7227:     }
1.976     raeburn  7228:     if (ref($domdef{$tool}) eq 'HASH') {
                   7229:         if ($is_adv) {
                   7230:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   7231:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   7232:                     $access = 1;
                   7233:                 } else {
                   7234:                     $access = 0;
                   7235:                 }
                   7236:                 return $access;
                   7237:             }
                   7238:         }
                   7239:         if ($inststatus ne '') {
                   7240:             my ($hasaccess,$hasnoaccess);
                   7241:             foreach my $affiliation (split(/:/,$inststatus)) {
                   7242:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   7243:                     if ($domdef{$tool}{$affiliation}) {
                   7244:                         $hasaccess = 1;
                   7245:                     } else {
                   7246:                         $hasnoaccess = 1;
                   7247:                     }
                   7248:                 }
                   7249:             }
                   7250:             if ($hasaccess || $hasnoaccess) {
                   7251:                 if ($hasaccess) {
                   7252:                     $access = 1;
                   7253:                 } elsif ($hasnoaccess) {
                   7254:                     $access = 0; 
                   7255:                 }
                   7256:                 return $access;
                   7257:             }
                   7258:         } else {
                   7259:             if ($domdef{$tool}{'default'} ne '') {
                   7260:                 if ($domdef{$tool}{'default'}) {
                   7261:                     $access = 1;
                   7262:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   7263:                     $access = 0;
                   7264:                 }
                   7265:                 return $access;
                   7266:             }
                   7267:         }
                   7268:     } else {
1.1177    raeburn  7269:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  7270:             $access = 1;
                   7271:         } else {
                   7272:             $access = 0;
                   7273:         }
1.976     raeburn  7274:         return $access;
                   7275:     }
                   7276: }
                   7277: 
1.1050    raeburn  7278: sub is_course_owner {
                   7279:     my ($cdom,$cnum,$udom,$uname) = @_;
                   7280:     if (($udom eq '') || ($uname eq '')) {
                   7281:         $udom = $env{'user.domain'};
                   7282:         $uname = $env{'user.name'};
                   7283:     }
                   7284:     unless (($udom eq '') || ($uname eq '')) {
                   7285:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   7286:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   7287:                 return 1;
                   7288:             } else {
                   7289:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   7290:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   7291:                     return 1;
                   7292:                 }
                   7293:             }
                   7294:         }
                   7295:     }
                   7296:     return;
                   7297: }
                   7298: 
1.976     raeburn  7299: sub is_advanced_user {
                   7300:     my ($udom,$uname) = @_;
1.1085    raeburn  7301:     if ($udom ne '' && $uname ne '') {
                   7302:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  7303:             if (wantarray) {
                   7304:                 return ($env{'user.adv'},$env{'user.author'});
                   7305:             } else {
                   7306:                 return $env{'user.adv'};
                   7307:             }
1.1085    raeburn  7308:         }
                   7309:     }
1.976     raeburn  7310:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   7311:     my %allroles;
1.1128    raeburn  7312:     my ($is_adv,$is_author);
1.976     raeburn  7313:     foreach my $role (keys(%roleshash)) {
                   7314:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   7315:         my $area = '/'.$tdomain.'/'.$trest;
                   7316:         if ($sec ne '') {
                   7317:             $area .= '/'.$sec;
                   7318:         }
                   7319:         if (($area ne '') && ($trole ne '')) {
                   7320:             my $spec=$trole.'.'.$area;
                   7321:             if ($trole =~ /^cr\//) {
                   7322:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   7323:             } elsif ($trole ne 'gr') {
                   7324:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   7325:             }
1.1128    raeburn  7326:             if ($trole eq 'au') {
                   7327:                 $is_author = 1;
                   7328:             }
1.976     raeburn  7329:         }
                   7330:     }
                   7331:     foreach my $role (keys(%allroles)) {
                   7332:         last if ($is_adv);
                   7333:         foreach my $item (split(/:/,$allroles{$role})) {
                   7334:             if ($item ne '') {
                   7335:                 my ($privilege,$restrictions)=split(/&/,$item);
                   7336:                 if ($privilege eq 'adv') {
                   7337:                     $is_adv = 1;
                   7338:                     last;
                   7339:                 }
                   7340:             }
                   7341:         }
                   7342:     }
1.1128    raeburn  7343:     if (wantarray) {
                   7344:         return ($is_adv,$is_author);
                   7345:     }
1.976     raeburn  7346:     return $is_adv;
                   7347: }
1.798     raeburn  7348: 
1.1035    raeburn  7349: sub check_can_request {
1.1368    raeburn  7350:     my ($dom,$can_request,$request_domains,$uname,$udom) = @_;
1.1035    raeburn  7351:     my $canreq = 0;
1.1368    raeburn  7352:     if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7353:         $uname = $env{'user.name'};
                   7354:         $udom = $env{'user.domain'};
                   7355:     }
1.1035    raeburn  7356:     my ($types,$typename) = &Apache::loncommon::course_types();
                   7357:     my @options = ('approval','validate','autolimit');
                   7358:     my $optregex = join('|',@options);
                   7359:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   7360:         foreach my $type (@{$types}) {
1.1368    raeburn  7361:             if (&usertools_access($uname,$udom,$type,undef,
                   7362:                                   'requestcourses')) {
1.1035    raeburn  7363:                 $canreq ++;
1.1036    raeburn  7364:                 if (ref($request_domains) eq 'HASH') {
1.1368    raeburn  7365:                     push(@{$request_domains->{$type}},$udom);
1.1036    raeburn  7366:                 }
1.1368    raeburn  7367:                 if ($dom eq $udom) {
1.1035    raeburn  7368:                     $can_request->{$type} = 1;
                   7369:                 }
                   7370:             }
1.1368    raeburn  7371:             if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '') &&
                   7372:                 ($env{'environment.reqcrsotherdom.'.$type} ne '')) {
1.1035    raeburn  7373:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   7374:                 if (@curr > 0) {
1.1036    raeburn  7375:                     foreach my $item (@curr) {
                   7376:                         if (ref($request_domains) eq 'HASH') {
                   7377:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   7378:                             if ($otherdom ne '') {
                   7379:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   7380:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   7381:                                         push(@{$request_domains->{$type}},$otherdom);
                   7382:                                     }
                   7383:                                 } else {
                   7384:                                     push(@{$request_domains->{$type}},$otherdom);
                   7385:                                 }
                   7386:                             }
                   7387:                         }
                   7388:                     }
1.1368    raeburn  7389:                     unless ($dom eq $env{'user.domain'}) {
1.1036    raeburn  7390:                         $canreq ++;
1.1035    raeburn  7391:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   7392:                             $can_request->{$type} = 1;
                   7393:                         }
                   7394:                     }
                   7395:                 }
                   7396:             }
                   7397:         }
                   7398:     }
                   7399:     return $canreq;
                   7400: }
                   7401: 
1.341     www      7402: # ---------------------------------------------- Custom access rule evaluation
                   7403: 
                   7404: sub customaccess {
                   7405:     my ($priv,$uri)=@_;
1.807     albertel 7406:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      7407:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 7408:     $udom = &LONCAPA::clean_domain($udom);
                   7409:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      7410:     my $access=0;
1.800     albertel 7411:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 7412: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   7413: 	if ($type eq 'user') {
                   7414: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 7415: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 7416: 		if ($tdom) {
                   7417: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   7418: 		}
1.896     albertel 7419: 		if ($tuname) {
                   7420: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 7421: 		}
                   7422: 		$access=($effect eq 'allow');
                   7423: 		last;
                   7424: 	    }
                   7425: 	} else {
                   7426: 	    if ($role) {
                   7427: 		if ($role ne $urole) { next; }
                   7428: 	    }
                   7429: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   7430: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   7431: 		if ($tdom) {
                   7432: 		    if ($tdom ne $udom) { next; }
                   7433: 		}
                   7434: 		if ($tcrs) {
                   7435: 		    if ($tcrs ne $ucrs) { next; }
                   7436: 		}
                   7437: 		if ($tsec) {
                   7438: 		    if ($tsec ne $usec) { next; }
                   7439: 		}
                   7440: 		$access=($effect eq 'allow');
                   7441: 		last;
                   7442: 	    }
                   7443: 	    if ($realm eq '' && $role eq '') {
                   7444: 		$access=($effect eq 'allow');
                   7445: 	    }
1.402     bowersj2 7446: 	}
1.341     www      7447:     }
                   7448:     return $access;
                   7449: }
                   7450: 
1.103     harris41 7451: # ------------------------------------------------- Check for a user privilege
1.12      www      7452: 
                   7453: sub allowed {
1.1281    raeburn  7454:     my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
1.705     albertel 7455:     my $ver_orguri=$uri;
1.439     www      7456:     $uri=&deversion($uri);
1.152     www      7457:     my $orguri=$uri;
1.52      www      7458:     $uri=&declutter($uri);
1.809     raeburn  7459: 
1.810     raeburn  7460:     if ($priv eq 'evb') {
                   7461: # Evade communication block restrictions for specified role in a course
                   7462:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   7463:             return $1;
                   7464:         } else {
                   7465:             return;
                   7466:         }
                   7467:     }
                   7468: 
1.620     albertel 7469:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      7470: # Free bre access to adm and meta resources
1.1343    raeburn  7471:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|ext\.tool)$})) 
1.769     albertel 7472: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   7473: 	&& ($priv eq 'bre')) {
1.14      www      7474: 	return 'F';
1.159     www      7475:     }
                   7476: 
1.545     banghart 7477: # Free bre access to user's own portfolio contents
1.714     raeburn  7478:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  7479:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  7480: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  7481:         my %setters;
                   7482:         my ($startblock,$endblock) = 
                   7483:             &Apache::loncommon::blockcheck(\%setters,'port');
                   7484:         if ($startblock && $endblock) {
                   7485:             return 'B';
                   7486:         } else {
                   7487:             return 'F';
                   7488:         }
1.545     banghart 7489:     }
                   7490: 
1.762     raeburn  7491: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  7492:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   7493:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   7494:         if (exists($env{'request.course.id'})) {
                   7495:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7496:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   7497:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   7498:                 my $courseprivid=$env{'request.course.id'};
                   7499:                 $courseprivid=~s/\_/\//;
                   7500:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   7501:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   7502:                     return $1; 
1.762     raeburn  7503:                 } else {
                   7504:                     if ($env{'request.course.sec'}) {
                   7505:                         $courseprivid.='/'.$env{'request.course.sec'};
                   7506:                     }
                   7507:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   7508:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   7509:                         return $2;
                   7510:                     }
1.714     raeburn  7511:                 }
                   7512:             }
                   7513:         }
                   7514:     }
                   7515: 
1.159     www      7516: # Free bre to public access
                   7517: 
                   7518:     if ($priv eq 'bre') {
1.1362    raeburn  7519:         my $copyright;
                   7520:         unless ($uri =~ /ext\.tool/) {
                   7521:             $copyright=&metadata($uri,'copyright');
                   7522:         }
1.620     albertel 7523: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      7524:            return 'F'; 
                   7525:         }
1.238     www      7526:         if ($copyright eq 'priv') {
                   7527:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7528: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      7529: 		return '';
                   7530:             }
                   7531:         }
                   7532:         if ($copyright eq 'domain') {
                   7533:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 7534: 	    unless (($env{'user.domain'} eq $1) ||
                   7535:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      7536: 		return '';
                   7537:             }
1.262     matthew  7538:         }
1.620     albertel 7539:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  7540:             # Library role, so allow browsing of resources in this domain.
                   7541:             return 'F';
1.238     www      7542:         }
1.341     www      7543:         if ($copyright eq 'custom') {
                   7544: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   7545:         }
1.14      www      7546:     }
1.264     matthew  7547:     # Domain coordinator is trying to create a course
1.620     albertel 7548:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  7549:         # uri is the requested domain in this case.
                   7550:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  7551:         # a role of dc for the domain in question.
1.620     albertel 7552:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  7553:     }
1.29      www      7554: 
1.52      www      7555:     my $thisallowed='';
                   7556:     my $statecond=0;
                   7557:     my $courseprivid='';
                   7558: 
1.1039    raeburn  7559:     my $ownaccess;
1.1043    raeburn  7560:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  7561:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   7562:         if ($uri eq '') {
                   7563:             $ownaccess = 1;
                   7564:         } else {
                   7565:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   7566:                 my $udom = $env{'user.domain'};
                   7567:                 my $uname = $env{'user.name'};
                   7568:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   7569:                     $ownaccess = 1;
1.1040    raeburn  7570:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  7571:                     unless ($uri =~ m{\.\./}) {
                   7572:                         $ownaccess = 1;
                   7573:                     }
                   7574:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   7575:                     my $now = time;
                   7576:                     if ($uri =~ m{^([^/]+)/?$}) {
                   7577:                         my $adom = $1;
                   7578:                         foreach my $key (keys(%env)) {
1.1042    raeburn  7579:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  7580:                                 my ($start,$end) = split('.',$env{$key});
                   7581:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7582:                                     $ownaccess = 1;
                   7583:                                     last;
                   7584:                                 }
                   7585:                             }
                   7586:                         }
                   7587:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   7588:                         my $adom = $1;
                   7589:                         my $aname = $2;
1.1042    raeburn  7590:                         foreach my $role ('ca','aa') { 
                   7591:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   7592:                                 my ($start,$end) =
                   7593:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   7594:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   7595:                                     $ownaccess = 1;
                   7596:                                     last;
                   7597:                                 }
1.1039    raeburn  7598:                             }
                   7599:                         }
                   7600:                     }
                   7601:                 }
                   7602:             }
                   7603:         }
                   7604:     }
                   7605: 
1.52      www      7606: # Course
                   7607: 
1.620     albertel 7608:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7609:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7610:             $thisallowed.=$1;
                   7611:         }
1.52      www      7612:     }
1.29      www      7613: 
1.52      www      7614: # Domain
                   7615: 
1.620     albertel 7616:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 7617:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7618:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7619:             $thisallowed.=$1;
                   7620:         }
1.12      www      7621:     }
1.52      www      7622: 
1.1141    raeburn  7623: # User who is not author or co-author might still be able to edit
                   7624: # resource of an author in the domain (e.g., if Domain Coordinator).
                   7625:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   7626:         (&allowed('mdc',$env{'request.course.id'}))) {
                   7627:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   7628:             $thisallowed.=$1;
                   7629:         }
                   7630:     }
                   7631: 
1.52      www      7632: # Course: uri itself is a course
1.66      www      7633:     my $courseuri=$uri;
                   7634:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      7635:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      7636: 
1.620     albertel 7637:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 7638:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  7639:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  7640:             $thisallowed.=$1;
                   7641:         }
1.12      www      7642:     }
1.29      www      7643: 
1.665     albertel 7644: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 7645: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 7646:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 7647: 	$thisallowed='';
1.671     raeburn  7648:         my ($match)=&is_on_map($uri);
                   7649:         if ($match) {
                   7650:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   7651:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1281    raeburn  7652:                 my $value = $1;
                   7653:                 if ($noblockcheck) {
                   7654:                     $thisallowed.=$value;
1.1162    raeburn  7655:                 } else {
1.1281    raeburn  7656:                     my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7657:                     if (@blockers > 0) {
                   7658:                         $thisallowed = 'B';
                   7659:                     } else {
                   7660:                         $thisallowed.=$value;
                   7661:                     }
1.1162    raeburn  7662:                 }
1.671     raeburn  7663:             }
                   7664:         } else {
1.705     albertel 7665:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  7666:             if ($refuri) {
                   7667:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  7668:                     $thisallowed='F';
1.671     raeburn  7669:                 } else {
                   7670:                     $refuri=&declutter($refuri);
                   7671:                     my ($match) = &is_on_map($refuri);
                   7672:                     if ($match) {
1.1281    raeburn  7673:                         if ($noblockcheck) {
                   7674:                             $thisallowed='F';
1.1162    raeburn  7675:                         } else {
1.1281    raeburn  7676:                             my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7677:                             if (@blockers > 0) {
                   7678:                                 $thisallowed = 'B';
                   7679:                             } else {
                   7680:                                 $thisallowed='F';
                   7681:                             }
1.1162    raeburn  7682:                         }
1.671     raeburn  7683:                     }
1.669     raeburn  7684:                 }
1.671     raeburn  7685:             }
                   7686:         }
1.314     www      7687:     }
1.492     albertel 7688: 
1.766     albertel 7689:     if ($priv eq 'bre'
                   7690: 	&& $thisallowed ne 'F' 
                   7691: 	&& $thisallowed ne '2'
                   7692: 	&& &is_portfolio_url($uri)) {
1.1270    raeburn  7693: 	$thisallowed = &portfolio_access($uri,$clientip);
1.766     albertel 7694:     }
1.1250    raeburn  7695: 
1.52      www      7696: # Full access at system, domain or course-wide level? Exit.
1.29      www      7697:     if ($thisallowed=~/F/) {
                   7698: 	return 'F';
                   7699:     }
                   7700: 
1.52      www      7701: # If this is generating or modifying users, exit with special codes
1.29      www      7702: 
1.643     www      7703:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   7704: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 7705: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      7706: # no author name given, so this just checks on the general right to make a co-author in this domain
                   7707: 	    unless ($auname) { return $thisallowed; }
                   7708: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 7709: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   7710: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   7711: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   7712: 	}
1.52      www      7713: 	return $thisallowed;
                   7714:     }
                   7715: #
1.103     harris41 7716: # Gathered so far: system, domain and course wide privileges
1.52      www      7717: #
                   7718: # Course: See if uri or referer is an individual resource that is part of 
                   7719: # the course
                   7720: 
1.620     albertel 7721:     if ($env{'request.course.id'}) {
1.232     www      7722: 
1.620     albertel 7723:        $courseprivid=$env{'request.course.id'};
                   7724:        if ($env{'request.course.sec'}) {
                   7725:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      7726:        }
                   7727:        $courseprivid=~s/\_/\//;
                   7728:        my $checkreferer=1;
1.232     www      7729:        my ($match,$cond)=&is_on_map($uri);
                   7730:        if ($match) {
                   7731:            $statecond=$cond;
1.620     albertel 7732:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7733:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7734:                my $value = $1;
                   7735:                if ($priv eq 'bre') {
1.1281    raeburn  7736:                    if ($noblockcheck) {
                   7737:                        $thisallowed.=$value;
1.1162    raeburn  7738:                    } else {
1.1281    raeburn  7739:                        my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   7740:                        if (@blockers > 0) {
                   7741:                            $thisallowed = 'B';
                   7742:                        } else {
                   7743:                            $thisallowed.=$value;
                   7744:                        }
1.1162    raeburn  7745:                    }
                   7746:                } else {
                   7747:                    $thisallowed.=$value;
                   7748:                }
1.52      www      7749:                $checkreferer=0;
                   7750:            }
1.29      www      7751:        }
1.83      www      7752:        
1.148     www      7753:        if ($checkreferer) {
1.620     albertel 7754: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      7755:             unless ($refuri) {
1.800     albertel 7756:                 foreach my $key (keys(%env)) {
                   7757: 		    if ($key=~/^httpref\..*\*/) {
                   7758: 			my $pattern=$key;
1.156     www      7759:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      7760:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   7761:                         $pattern=~s/\//\\\//g;
1.152     www      7762:                         if ($orguri=~/$pattern/) {
1.800     albertel 7763: 			    $refuri=$env{$key};
1.148     www      7764:                         }
                   7765:                     }
1.191     harris41 7766:                 }
1.148     www      7767:             }
1.232     www      7768: 
1.148     www      7769:          if ($refuri) { 
1.152     www      7770: 	  $refuri=&declutter($refuri);
1.232     www      7771:           my ($match,$cond)=&is_on_map($refuri);
                   7772:             if ($match) {
                   7773:               my $refstatecond=$cond;
1.620     albertel 7774:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 7775:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  7776:                   my $value = $1;
                   7777:                   if ($priv eq 'bre') {
1.1281    raeburn  7778:                       if ($noblockcheck) {
                   7779:                           $thisallowed.=$value;
1.1162    raeburn  7780:                       } else {
1.1281    raeburn  7781:                           my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   7782:                           if (@blockers > 0) {
                   7783:                               $thisallowed = 'B';
                   7784:                           } else {
                   7785:                               $thisallowed.=$value;
                   7786:                           }
1.1162    raeburn  7787:                       }
                   7788:                   } else {
                   7789:                       $thisallowed.=$value;
                   7790:                   }
1.53      www      7791:                   $uri=$refuri;
                   7792:                   $statecond=$refstatecond;
1.52      www      7793:               }
                   7794:           }
1.148     www      7795:         }
1.29      www      7796:        }
1.52      www      7797:    }
1.29      www      7798: 
1.52      www      7799: #
1.103     harris41 7800: # Gathered now: all privileges that could apply, and condition number
1.52      www      7801: # 
                   7802: #
                   7803: # Full or no access?
                   7804: #
1.29      www      7805: 
1.52      www      7806:     if ($thisallowed=~/F/) {
                   7807: 	return 'F';
                   7808:     }
1.29      www      7809: 
1.52      www      7810:     unless ($thisallowed) {
                   7811:         return '';
                   7812:     }
1.29      www      7813: 
1.52      www      7814: # Restrictions exist, deal with them
                   7815: #
                   7816: #   C:according to course preferences
                   7817: #   R:according to resource settings
                   7818: #   L:unless locked
                   7819: #   X:according to user session state
                   7820: #
                   7821: 
                   7822: # Possibly locked functionality, check all courses
1.54      www      7823: # Locks might take effect only after 10 minutes cache expiration for other
                   7824: # courses, and 2 minutes for current course
1.52      www      7825: 
                   7826:     my $envkey;
                   7827:     if ($thisallowed=~/L/) {
1.1000    raeburn  7828:         foreach $envkey (keys(%env)) {
1.54      www      7829:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   7830:                my $courseid=$2;
                   7831:                my $roleid=$1.'.'.$2;
1.92      www      7832:                $courseid=~s/^\///;
1.54      www      7833:                my $expiretime=600;
1.620     albertel 7834:                if ($env{'request.role'} eq $roleid) {
1.54      www      7835: 		  $expiretime=120;
                   7836:                }
                   7837: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   7838:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 7839:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 7840: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      7841:                }
1.620     albertel 7842:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7843:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   7844: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   7845:                        &log($env{'user.domain'},$env{'user.name'},
                   7846:                             $env{'user.home'},
1.57      www      7847:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      7848:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7849:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7850: 		       return '';
                   7851:                    }
                   7852:                }
1.620     albertel 7853:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   7854:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   7855: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   7856:                        &log($env{'user.domain'},$env{'user.name'},
                   7857:                             $env{'user.home'},
1.57      www      7858:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      7859:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 7860:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      7861: 		       return '';
                   7862:                    }
                   7863:                }
                   7864: 	   }
1.29      www      7865:        }
1.52      www      7866:     }
                   7867:    
                   7868: #
                   7869: # Rest of the restrictions depend on selected course
                   7870: #
                   7871: 
1.620     albertel 7872:     unless ($env{'request.course.id'}) {
1.766     albertel 7873: 	if ($thisallowed eq 'A') {
                   7874: 	    return 'A';
1.814     raeburn  7875:         } elsif ($thisallowed eq 'B') {
                   7876:             return 'B';
1.766     albertel 7877: 	} else {
                   7878: 	    return '1';
                   7879: 	}
1.52      www      7880:     }
1.29      www      7881: 
1.52      www      7882: #
                   7883: # Now user is definitely in a course
                   7884: #
1.53      www      7885: 
                   7886: 
                   7887: # Course preferences
                   7888: 
                   7889:    if ($thisallowed=~/C/) {
1.620     albertel 7890:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   7891:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   7892:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 7893: 	   =~/\Q$rolecode\E/) {
1.1304    raeburn  7894: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7895: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7896: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   7897: 			$env{'request.course.id'});
                   7898: 	   }
1.237     www      7899:            return '';
                   7900:        }
                   7901: 
1.620     albertel 7902:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 7903: 	   =~/\Q$unamedom\E/) {
1.1304    raeburn  7904: 	   if (($priv ne 'pch') && ($priv ne 'plc') && ($priv ne 'pac')) {
1.689     albertel 7905: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   7906: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   7907: 			$env{'request.course.id'});
                   7908: 	   }
1.54      www      7909:            return '';
                   7910:        }
1.53      www      7911:    }
                   7912: 
                   7913: # Resource preferences
                   7914: 
                   7915:    if ($thisallowed=~/R/) {
1.620     albertel 7916:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 7917:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  7918: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 7919: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   7920: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   7921: 	   }
                   7922: 	   return '';
1.54      www      7923:        }
1.53      www      7924:    }
1.30      www      7925: 
1.246     www      7926: # Restricted by state or randomout?
1.30      www      7927: 
1.52      www      7928:    if ($thisallowed=~/X/) {
1.620     albertel 7929:       if ($env{'acc.randomout'}) {
1.579     albertel 7930: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 7931:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      7932:             return ''; 
                   7933:          }
1.247     www      7934:       }
                   7935:       if (&condval($statecond)) {
1.52      www      7936: 	 return '2';
                   7937:       } else {
                   7938:          return '';
                   7939:       }
                   7940:    }
1.30      www      7941: 
1.766     albertel 7942:     if ($thisallowed eq 'A') {
                   7943: 	return 'A';
1.814     raeburn  7944:     } elsif ($thisallowed eq 'B') {
                   7945:         return 'B';
1.766     albertel 7946:     }
1.52      www      7947:    return 'F';
1.232     www      7948: }
1.1162    raeburn  7949: 
1.1192    raeburn  7950: # ------------------------------------------- Check construction space access
                   7951: 
                   7952: sub constructaccess {
                   7953:     my ($url,$setpriv)=@_;
                   7954: 
                   7955: # We do not allow editing of previous versions of files
                   7956:     if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
                   7957: 
                   7958: # Get username and domain from URL
                   7959:     my ($ownername,$ownerdomain,$ownerhome);
                   7960: 
                   7961:     ($ownerdomain,$ownername) =
1.1325    raeburn  7962:         ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)(?:/daxepage|/daxeopen)?/priv/($match_domain)/($match_username)(?:/|$)});
1.1192    raeburn  7963: 
                   7964: # The URL does not really point to any authorspace, forget it
                   7965:     unless (($ownername) && ($ownerdomain)) { return ''; }
                   7966: 
                   7967: # Now we need to see if the user has access to the authorspace of
                   7968: # $ownername at $ownerdomain
                   7969: 
                   7970:     if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
                   7971: # Real author for this?
                   7972:        $ownerhome = $env{'user.home'};
                   7973:        if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
                   7974:           return ($ownername,$ownerdomain,$ownerhome);
                   7975:        }
                   7976:     } else {
                   7977: # Co-author for this?
                   7978:         if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
                   7979:             exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
                   7980:             $ownerhome = &homeserver($ownername,$ownerdomain);
                   7981:             return ($ownername,$ownerdomain,$ownerhome);
                   7982:         }
1.1312    raeburn  7983:         if ($env{'request.course.id'}) {
                   7984:             if (($ownername eq $env{'course.'.$env{'request.course.id'}.'.num'}) &&
                   7985:                 ($ownerdomain eq $env{'course.'.$env{'request.course.id'}.'.domain'})) {
                   7986:                 if (&allowed('mdc',$env{'request.course.id'})) {
                   7987:                     $ownerhome = $env{'course.'.$env{'request.course.id'}.'.home'};
                   7988:                     return ($ownername,$ownerdomain,$ownerhome);
                   7989:                 }
                   7990:             }
                   7991:         }
1.1192    raeburn  7992:     }
                   7993: 
                   7994: # We don't have any access right now. If we are not possibly going to do anything about this,
                   7995: # we might as well leave
                   7996:    unless ($setpriv) { return ''; }
                   7997: 
                   7998: # Backdoor access?
                   7999:     my $allowed=&allowed('eco',$ownerdomain);
                   8000: # Nope
                   8001:     unless ($allowed) { return ''; }
                   8002: # Looks like we may have access, but could be locked by the owner of the construction space
                   8003:     if ($allowed eq 'U') {
                   8004:         my %blocked=&get('environment',['domcoord.author'],
                   8005:                          $ownerdomain,$ownername);
                   8006: # Is blocked by owner
                   8007:         if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
                   8008:     }
                   8009:     if (($allowed eq 'F') || ($allowed eq 'U')) {
                   8010: # Grant temporary access
                   8011:         my $then=$env{'user.login.time'};
1.1209    raeburn  8012:         my $update=$env{'user.update.time'};
1.1192    raeburn  8013:         if (!$update) { $update = $then; }
                   8014:         my $refresh=$env{'user.refresh.time'};
                   8015:         if (!$refresh) { $refresh = $update; }
                   8016:         my $now = time;
                   8017:         &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
                   8018:                            $now,'ca','constructaccess');
                   8019:         $ownerhome = &homeserver($ownername,$ownerdomain);
                   8020:         return($ownername,$ownerdomain,$ownerhome);
                   8021:     }
                   8022: # No business here
                   8023:     return '';
                   8024: }
                   8025: 
1.1282    raeburn  8026: # ----------------------------------------------------------- Content Blocking
                   8027: 
                   8028: {
                   8029: # Caches for faster Course Contents display where content blocking
                   8030: # is in operation (i.e., interval param set) for timed quiz.
                   8031: #
                   8032: # User for whom data are being temporarily cached.
                   8033: my $cacheduser='';
                   8034: # Cached blockers for this user (a hash of blocking items). 
                   8035: my %cachedblockers=();
                   8036: # When the data were last cached.
                   8037: my $cachedlast='';
                   8038: 
                   8039: sub load_all_blockers {
                   8040:     my ($uname,$udom,$blocks)=@_;
                   8041:     if (($uname ne '') && ($udom ne '')) { 
                   8042:         if (($cacheduser eq $uname.':'.$udom) &&
                   8043:             (abs($cachedlast-time)<5)) {
                   8044:             return;
                   8045:         }
                   8046:     }
                   8047:     $cachedlast=time;
                   8048:     $cacheduser=$uname.':'.$udom;
                   8049:     %cachedblockers = &get_commblock_resources($blocks);
                   8050: }
                   8051: 
1.1162    raeburn  8052: sub get_comm_blocks {
                   8053:     my ($cdom,$cnum) = @_;
                   8054:     if ($cdom eq '' || $cnum eq '') {
                   8055:         return unless ($env{'request.course.id'});
                   8056:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   8057:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   8058:     }
                   8059:     my %commblocks;
                   8060:     my $hashid=$cdom.'_'.$cnum;
                   8061:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   8062:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   8063:         %commblocks = %{$blocksref};
                   8064:     } else {
                   8065:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   8066:         my $cachetime = 600;
                   8067:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   8068:     }
                   8069:     return %commblocks;
                   8070: }
                   8071: 
1.1282    raeburn  8072: sub get_commblock_resources {
                   8073:     my ($blocks) = @_;
                   8074:     my %blockers = ();
                   8075:     return %blockers unless ($env{'request.course.id'});
                   8076:     return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
1.1162    raeburn  8077:     my %commblocks;
                   8078:     if (ref($blocks) eq 'HASH') {
                   8079:         %commblocks = %{$blocks};
                   8080:     } else {
                   8081:         %commblocks = &get_comm_blocks();
                   8082:     }
1.1282    raeburn  8083:     return %blockers unless (keys(%commblocks) > 0); 
                   8084:     my $navmap = Apache::lonnavmaps::navmap->new();
                   8085:     return %blockers unless (ref($navmap));
1.1162    raeburn  8086:     my $now = time;
                   8087:     foreach my $block (keys(%commblocks)) {
                   8088:         if ($block =~ /^(\d+)____(\d+)$/) {
                   8089:             my ($start,$end) = ($1,$2);
                   8090:             if ($start <= $now && $end >= $now) {
                   8091:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8092:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   8093:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
1.1282    raeburn  8094:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8095:                                 $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'}; 
1.1162    raeburn  8096:                             }
                   8097:                         }
                   8098:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
1.1282    raeburn  8099:                             if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8100:                                 $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1162    raeburn  8101:                             }
                   8102:                         }
                   8103:                     }
                   8104:                 }
                   8105:             }
                   8106:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   8107:             my $item = $1;
1.1163    raeburn  8108:             my @to_test;
1.1162    raeburn  8109:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   8110:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
1.1282    raeburn  8111:                     my @interval;
                   8112:                     my $type = 'map';
                   8113:                     if ($item eq 'course') {
                   8114:                         $type = 'course';
                   8115:                         @interval=&EXT("resource.0.interval");
                   8116:                     } else {
                   8117:                         if ($item =~ /___\d+___/) {
                   8118:                             $type = 'resource';
                   8119:                             @interval=&EXT("resource.0.interval",$item);
                   8120:                             if (ref($navmap)) {                        
                   8121:                                 my $res = $navmap->getBySymb($item); 
                   8122:                                 push(@to_test,$res);
                   8123:                             }
1.1162    raeburn  8124:                         } else {
1.1282    raeburn  8125:                             my $mapsymb = &symbread($item,1);
                   8126:                             if ($mapsymb) {
                   8127:                                 if (ref($navmap)) {
                   8128:                                     my $mapres = $navmap->getBySymb($mapsymb);
                   8129:                                     @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
                   8130:                                     foreach my $res (@to_test) {
                   8131:                                         my $symb = $res->symb();
                   8132:                                         next if ($symb eq $mapsymb);
                   8133:                                         if ($symb ne '') {
                   8134:                                             @interval=&EXT("resource.0.interval",$symb);
                   8135:                                             if ($interval[1] eq 'map') {
                   8136:                                                 last;
1.1162    raeburn  8137:                                             }
                   8138:                                         }
                   8139:                                     }
                   8140:                                 }
                   8141:                             }
                   8142:                         }
1.1282    raeburn  8143:                     }
1.1310    raeburn  8144:                     if ($interval[0] =~ /^(\d+)/) {
1.1308    raeburn  8145:                         my $timelimit = $1; 
1.1282    raeburn  8146:                         my $first_access;
                   8147:                         if ($type eq 'resource') {
                   8148:                             $first_access=&get_first_access($interval[1],$item);
                   8149:                         } elsif ($type eq 'map') {
                   8150:                             $first_access=&get_first_access($interval[1],undef,$item);
                   8151:                         } else {
                   8152:                             $first_access=&get_first_access($interval[1]);
                   8153:                         }
                   8154:                         if ($first_access) {
1.1292    raeburn  8155:                             my $timesup = $first_access+$timelimit;
1.1282    raeburn  8156:                             if ($timesup > $now) {
                   8157:                                 my $activeblock;
                   8158:                                 foreach my $res (@to_test) {
1.1283    raeburn  8159:                                     if ($res->answerable()) {
1.1282    raeburn  8160:                                         $activeblock = 1;
                   8161:                                         last;
                   8162:                                     }
                   8163:                                 }
                   8164:                                 if ($activeblock) {
                   8165:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   8166:                                          if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
                   8167:                                              $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
                   8168:                                          }
                   8169:                                     }
                   8170:                                     if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   8171:                                         if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
                   8172:                                             $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
1.1163    raeburn  8173:                                         }
1.1162    raeburn  8174:                                     }
                   8175:                                 }
                   8176:                             }
                   8177:                         }
                   8178:                     }
                   8179:                 }
                   8180:             }
                   8181:         }
                   8182:     }
1.1282    raeburn  8183:     return %blockers;
1.1162    raeburn  8184: }
                   8185: 
1.1282    raeburn  8186: sub has_comm_blocking {
                   8187:     my ($priv,$symb,$uri,$blocks) = @_;
                   8188:     my @blockers;
                   8189:     return unless ($env{'request.course.id'});
                   8190:     return unless ($priv eq 'bre');
                   8191:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   8192:     return if ($env{'request.state'} eq 'construct');
                   8193:     &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
                   8194:     return unless (keys(%cachedblockers) > 0);
                   8195:     my (%possibles,@symbs);
                   8196:     if (!$symb) {
                   8197:         $symb = &symbread($uri,1,1,1,\%possibles);
1.1162    raeburn  8198:     }
1.1282    raeburn  8199:     if ($symb) {
                   8200:         @symbs = ($symb);
                   8201:     } elsif (keys(%possibles)) { 
                   8202:         @symbs = keys(%possibles);
                   8203:     }
                   8204:     my $noblock;
                   8205:     foreach my $symb (@symbs) {
                   8206:         last if ($noblock);
                   8207:         my ($map,$resid,$resurl)=&decode_symb($symb);
                   8208:         foreach my $block (keys(%cachedblockers)) {
                   8209:             if ($block =~ /^firstaccess____(.+)$/) {
                   8210:                 my $item = $1;
                   8211:                 if (($item eq $map) || ($item eq $symb)) {
                   8212:                     $noblock = 1;
                   8213:                     last;
                   8214:                 }
                   8215:             }
                   8216:             if (ref($cachedblockers{$block}) eq 'HASH') {
                   8217:                 if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
                   8218:                     if ($cachedblockers{$block}{'resources'}{$symb}) {
                   8219:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   8220:                             push(@blockers,$block);
                   8221:                         }
                   8222:                     }
                   8223:                 }
1.1162    raeburn  8224:             }
1.1282    raeburn  8225:             if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
                   8226:                 if ($cachedblockers{$block}{'maps'}{$map}) {
                   8227:                     unless (grep(/^\Q$block\E$/,@blockers)) {
                   8228:                         push(@blockers,$block);
                   8229:                     }
                   8230:                 }
1.1162    raeburn  8231:             }
                   8232:         }
                   8233:     }
1.1282    raeburn  8234:     return if ($noblock);
                   8235:     return @blockers;
                   8236: }
1.1162    raeburn  8237: }
                   8238: 
1.1282    raeburn  8239: # -------------------------------- Deversion and split uri into path an filename   
                   8240: 
1.1133    foxr     8241: #
1.1282    raeburn  8242: #   Removes the version from a URI and
1.1133    foxr     8243: #   splits it in to its filename and path to the filename.
                   8244: #   Seems like File::Basename could have done this more clearly.
                   8245: #   Parameters:
                   8246: #      $uri   - input URI
                   8247: #   Returns:
                   8248: #     Two element list consisting of 
                   8249: #     $pathname  - the URI up to and excluding the trailing /
                   8250: #     $filename  - The part of the URI following the last /
                   8251: #  NOTE:
                   8252: #    Another realization of this is simply:
                   8253: #    use File::Basename;
                   8254: #    ...
                   8255: #    $uri = shift;
                   8256: #    $filename = basename($uri);
                   8257: #    $path     = dirname($uri);
                   8258: #    return ($filename, $path);
                   8259: #
                   8260: #     The implementation below is probably faster however.
                   8261: #
1.710     albertel 8262: sub split_uri_for_cond {
                   8263:     my $uri=&deversion(&declutter(shift));
                   8264:     my @uriparts=split(/\//,$uri);
                   8265:     my $filename=pop(@uriparts);
                   8266:     my $pathname=join('/',@uriparts);
                   8267:     return ($pathname,$filename);
                   8268: }
1.232     www      8269: # --------------------------------------------------- Is a resource on the map?
                   8270: 
                   8271: sub is_on_map {
1.710     albertel 8272:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 8273:     #Trying to find the conditional for the file
1.620     albertel 8274:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 8275: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      8276:     if ($match) {
1.289     bowersj2 8277: 	return (1,$1);
                   8278:     } else {
1.434     www      8279: 	return (0,0);
1.289     bowersj2 8280:     }
1.12      www      8281: }
                   8282: 
1.427     www      8283: # --------------------------------------------------------- Get symb from alias
                   8284: 
                   8285: sub get_symb_from_alias {
                   8286:     my $symb=shift;
                   8287:     my ($map,$resid,$url)=&decode_symb($symb);
                   8288: # Already is a symb
                   8289:     if ($url) { return $symb; }
                   8290: # Must be an alias
                   8291:     my $aliassymb='';
                   8292:     my %bighash;
1.620     albertel 8293:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      8294:                             &GDBM_READER(),0640)) {
                   8295:         my $rid=$bighash{'mapalias_'.$symb};
                   8296: 	if ($rid) {
                   8297: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 8298: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   8299: 				    $resid,$bighash{'src_'.$rid});
1.427     www      8300: 	}
                   8301:         untie %bighash;
                   8302:     }
                   8303:     return $aliassymb;
                   8304: }
                   8305: 
1.12      www      8306: # ----------------------------------------------------------------- Define Role
                   8307: 
                   8308: sub definerole {
                   8309:   if (allowed('mcr','/')) {
1.1326    raeburn  8310:     my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
1.800     albertel 8311:     foreach my $role (split(':',$sysrole)) {
                   8312: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8313:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   8314:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   8315: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8316:                return "refused:s:$crole&$cqual"; 
                   8317:             }
                   8318:         }
1.191     harris41 8319:     }
1.800     albertel 8320:     foreach my $role (split(':',$domrole)) {
                   8321: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8322:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   8323:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   8324: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      8325:                return "refused:d:$crole&$cqual"; 
                   8326:             }
                   8327:         }
1.191     harris41 8328:     }
1.800     albertel 8329:     foreach my $role (split(':',$courole)) {
                   8330: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 8331:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   8332:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   8333: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      8334:                return "refused:c:$crole&$cqual"; 
                   8335:             }
                   8336:         }
1.191     harris41 8337:     }
1.1326    raeburn  8338:     my $uhome;
                   8339:     if (($uname ne '') && ($udom ne '')) {
                   8340:         $uhome = &homeserver($uname,$udom);
                   8341:         return $uhome if ($uhome eq 'no_host');
                   8342:     } else {
                   8343:         $uname = $env{'user.name'};
                   8344:         $udom = $env{'user.domain'};
                   8345:         $uhome = $env{'user.home'};
                   8346:     }
1.620     albertel 8347:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.1326    raeburn  8348:                 "$udom:$uname:rolesdef_$rolename=".
1.21      www      8349:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.1326    raeburn  8350:     return reply($command,$uhome);
1.12      www      8351:   } else {
                   8352:     return 'refused';
                   8353:   }
1.105     harris41 8354: }
                   8355: 
                   8356: # ---------------- Make a metadata query against the network of library servers
                   8357: 
                   8358: sub metadata_query {
1.1237    raeburn  8359:     my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
1.120     harris41 8360:     my %rhash;
1.845     albertel 8361:     my %libserv = &all_library();
1.244     matthew  8362:     my @server_list = (defined($server_array) ? @$server_array
                   8363:                                               : keys(%libserv) );
                   8364:     for my $server (@server_list) {
1.1237    raeburn  8365:         my $domains = ''; 
                   8366:         if (ref($domains_hash) eq 'HASH') {
                   8367:             $domains = $domains_hash->{$server}; 
                   8368:         }
1.118     harris41 8369: 	unless ($custom or $customshow) {
1.1237    raeburn  8370: 	    my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
1.118     harris41 8371: 	    $rhash{$server}=$reply;
                   8372: 	}
                   8373: 	else {
                   8374: 	    my $reply=&reply("querysend:".&escape($query).':'.
1.1237    raeburn  8375: 			     &escape($custom).':'.&escape($customshow).':'.&escape($domains),
1.118     harris41 8376: 			     $server);
                   8377: 	    $rhash{$server}=$reply;
                   8378: 	}
1.112     harris41 8379:     }
1.118     harris41 8380:     return \%rhash;
1.240     www      8381: }
                   8382: 
                   8383: # ----------------------------------------- Send log queries and wait for reply
                   8384: 
                   8385: sub log_query {
                   8386:     my ($uname,$udom,$query,%filters)=@_;
                   8387:     my $uhome=&homeserver($uname,$udom);
                   8388:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 8389:     my $uhost=&hostname($uhome);
1.800     albertel 8390:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      8391:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   8392:                        $uhome);
1.479     albertel 8393:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      8394:     return get_query_reply($queryid);
                   8395: }
                   8396: 
1.818     raeburn  8397: # -------------------------- Update MySQL table for portfolio file
                   8398: 
                   8399: sub update_portfolio_table {
1.821     raeburn  8400:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  8401:     if ($group ne '') {
                   8402:         $file_name =~s /^\Q$group\E//;
                   8403:     }
1.818     raeburn  8404:     my $homeserver = &homeserver($uname,$udom);
                   8405:     my $queryid=
1.821     raeburn  8406:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   8407:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  8408:     my $reply = &get_query_reply($queryid);
                   8409:     return $reply;
                   8410: }
                   8411: 
1.899     raeburn  8412: # -------------------------- Update MySQL allusers table
                   8413: 
                   8414: sub update_allusers_table {
                   8415:     my ($uname,$udom,$names) = @_;
                   8416:     my $homeserver = &homeserver($uname,$udom);
                   8417:     my $queryid=
                   8418:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   8419:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   8420:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   8421:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   8422:                'generation='.&escape($names->{'generation'}).'%%'.
                   8423:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   8424:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  8425:     return;
1.899     raeburn  8426: }
                   8427: 
1.508     raeburn  8428: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  8429: 
                   8430: sub fetch_enrollment_query {
1.511     raeburn  8431:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.1317    raeburn  8432:     my ($homeserver,$sleep,$loopmax);
1.547     raeburn  8433:     my $maxtries = 1;
1.508     raeburn  8434:     if ($context eq 'automated') {
                   8435:         $homeserver = $perlvar{'lonHostID'};
1.1317    raeburn  8436:         $sleep = 2;
                   8437:         $loopmax = 100;
1.547     raeburn  8438:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  8439:     } else {
                   8440:         $homeserver = &homeserver($cnum,$dom);
                   8441:     }
1.838     albertel 8442:     my $host=&hostname($homeserver);
1.506     raeburn  8443:     my $cmd = '';
1.1000    raeburn  8444:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 8445:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  8446:     }
                   8447:     $cmd =~ s/%%$//;
                   8448:     $cmd = &escape($cmd);
                   8449:     my $query = 'fetchenrollment';
1.620     albertel 8450:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  8451:     unless ($queryid=~/^\Q$host\E\_/) { 
                   8452:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   8453:         return 'error: '.$queryid;
                   8454:     }
1.1317    raeburn  8455:     my $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8456:     my $tries = 1;
                   8457:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1.1317    raeburn  8458:         $reply = &get_query_reply($queryid,$sleep,$loopmax);
1.547     raeburn  8459:         $tries ++;
                   8460:     }
1.526     raeburn  8461:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 8462:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  8463:     } else {
1.901     albertel 8464:         my @responses = split(/:/,$reply);
1.1322    raeburn  8465:         if (grep { $_ eq $homeserver } &current_machine_ids()) {
1.800     albertel 8466:             foreach my $line (@responses) {
                   8467:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  8468:                 $$replyref{$key} = $value;
                   8469:             }
                   8470:         } else {
1.1117    foxr     8471:             my $pathname = LONCAPA::tempdir();
1.800     albertel 8472:             foreach my $line (@responses) {
                   8473:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  8474:                 $$replyref{$key} = $value;
                   8475:                 if ($value > 0) {
1.800     albertel 8476:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   8477:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  8478:                         my $destname = $pathname.'/'.$filename;
                   8479:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  8480:                         if ($xml_classlist =~ /^error/) {
                   8481:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   8482:                         } else {
1.1359    raeburn  8483:                             if ( open(FILE,">",$destname) ) {
1.506     raeburn  8484:                                 print FILE &unescape($xml_classlist);
                   8485:                                 close(FILE);
1.526     raeburn  8486:                             } else {
                   8487:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  8488:                             }
                   8489:                         }
                   8490:                     }
                   8491:                 }
                   8492:             }
                   8493:         }
                   8494:         return 'ok';
                   8495:     }
                   8496:     return 'error';
                   8497: }
                   8498: 
1.242     www      8499: sub get_query_reply {
1.1317    raeburn  8500:     my ($queryid,$sleep,$loopmax) = @_;;
                   8501:     if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
                   8502:         $sleep = 0.2;
                   8503:     }
                   8504:     if (($loopmax eq '') || ($loopmax =~ /\D/)) {
                   8505:         $loopmax = 100;
                   8506:     }
1.1117    foxr     8507:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      8508:     my $reply='';
1.1317    raeburn  8509:     for (1..$loopmax) {
                   8510: 	sleep($sleep);
1.240     www      8511:         if (-e $replyfile.'.end') {
1.1359    raeburn  8512: 	    if (open(my $fh,"<",$replyfile)) {
1.904     albertel 8513: 		$reply = join('',<$fh>);
                   8514: 		close($fh);
1.240     www      8515: 	   } else { return 'error: reply_file_error'; }
1.242     www      8516:            return &unescape($reply);
                   8517: 	}
1.240     www      8518:     }
1.242     www      8519:     return 'timeout:'.$queryid;
1.240     www      8520: }
                   8521: 
                   8522: sub courselog_query {
1.241     www      8523: #
                   8524: # possible filters:
                   8525: # url: url or symb
                   8526: # username
                   8527: # domain
                   8528: # action: view, submit, grade
                   8529: # start: timestamp
                   8530: # end: timestamp
                   8531: #
1.240     www      8532:     my (%filters)=@_;
1.620     albertel 8533:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      8534:     if ($filters{'url'}) {
                   8535: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   8536:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   8537:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   8538:     }
1.620     albertel 8539:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   8540:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      8541:     return &log_query($cname,$cdom,'courselog',%filters);
                   8542: }
                   8543: 
                   8544: sub userlog_query {
1.858     raeburn  8545: #
                   8546: # possible filters:
                   8547: # action: log check role
                   8548: # start: timestamp
                   8549: # end: timestamp
                   8550: #
1.240     www      8551:     my ($uname,$udom,%filters)=@_;
                   8552:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      8553: }
                   8554: 
1.506     raeburn  8555: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   8556: 
                   8557: sub auto_run {
1.508     raeburn  8558:     my ($cnum,$cdom) = @_;
1.876     raeburn  8559:     my $response = 0;
                   8560:     my $settings;
                   8561:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   8562:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   8563:         $settings = $domconfig{'autoenroll'};
                   8564:         if ($settings->{'run'} eq '1') {
                   8565:             $response = 1;
                   8566:         }
                   8567:     } else {
1.934     raeburn  8568:         my $homeserver;
                   8569:         if (&is_course($cdom,$cnum)) {
                   8570:             $homeserver = &homeserver($cnum,$cdom);
                   8571:         } else {
                   8572:             $homeserver = &domain($cdom,'primary');
                   8573:         }
                   8574:         if ($homeserver ne 'no_host') {
                   8575:             $response = &reply('autorun:'.$cdom,$homeserver);
                   8576:         }
1.876     raeburn  8577:     }
1.506     raeburn  8578:     return $response;
                   8579: }
1.776     albertel 8580: 
1.506     raeburn  8581: sub auto_get_sections {
1.508     raeburn  8582:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  8583:     my $homeserver;
                   8584:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   8585:         $homeserver = &homeserver($cnum,$cdom);
                   8586:     }
                   8587:     if (!defined($homeserver)) { 
                   8588:         if ($cdom =~ /^$match_domain$/) {
                   8589:             $homeserver = &domain($cdom,'primary');
                   8590:         }
                   8591:     }
                   8592:     my @secs;
                   8593:     if (defined($homeserver)) {
                   8594:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   8595:         unless ($response eq 'refused') {
                   8596:             @secs = split(/:/,$response);
                   8597:         }
1.506     raeburn  8598:     }
                   8599:     return @secs;
                   8600: }
1.776     albertel 8601: 
1.506     raeburn  8602: sub auto_new_course {
1.1099    raeburn  8603:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  8604:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  8605:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  8606:     return $response;
                   8607: }
1.776     albertel 8608: 
1.506     raeburn  8609: sub auto_validate_courseID {
1.508     raeburn  8610:     my ($cnum,$cdom,$inst_course_id) = @_;
                   8611:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  8612:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  8613:     return $response;
                   8614: }
1.776     albertel 8615: 
1.1007    raeburn  8616: sub auto_validate_instcode {
1.1020    raeburn  8617:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  8618:     my ($homeserver,$response);
                   8619:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8620:         $homeserver = &homeserver($cnum,$cdom);
                   8621:     }
                   8622:     if (!defined($homeserver)) {
                   8623:         if ($cdom =~ /^$match_domain$/) {
                   8624:             $homeserver = &domain($cdom,'primary');
                   8625:         }
                   8626:     }
1.1065    raeburn  8627:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   8628:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1216    raeburn  8629:     my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
                   8630:     return ($outcome,$description,$defaultcredits);
1.1007    raeburn  8631: }
                   8632: 
1.506     raeburn  8633: sub auto_create_password {
1.873     raeburn  8634:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   8635:     my ($homeserver,$response);
1.506     raeburn  8636:     my $create_passwd = 0;
                   8637:     my $authchk = '';
1.873     raeburn  8638:     if ($udom =~ /^$match_domain$/) {
                   8639:         $homeserver = &domain($udom,'primary');
                   8640:     }
                   8641:     if ($homeserver eq '') {
                   8642:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   8643:             $homeserver = &homeserver($cnum,$cdom);
                   8644:         }
                   8645:     }
                   8646:     if ($homeserver eq '') {
                   8647:         $authchk = 'nodomain';
1.506     raeburn  8648:     } else {
1.873     raeburn  8649:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   8650:         if ($response eq 'refused') {
                   8651:             $authchk = 'refused';
                   8652:         } else {
1.901     albertel 8653:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  8654:         }
1.506     raeburn  8655:     }
                   8656:     return ($authparam,$create_passwd,$authchk);
                   8657: }
                   8658: 
1.706     raeburn  8659: sub auto_photo_permission {
                   8660:     my ($cnum,$cdom,$students) = @_;
                   8661:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 8662:     my ($outcome,$perm_reqd,$conditions) = 
                   8663: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 8664:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8665: 	return (undef,undef);
                   8666:     }
1.706     raeburn  8667:     return ($outcome,$perm_reqd,$conditions);
                   8668: }
                   8669: 
                   8670: sub auto_checkphotos {
                   8671:     my ($uname,$udom,$pid) = @_;
                   8672:     my $homeserver = &homeserver($uname,$udom);
                   8673:     my ($result,$resulttype);
                   8674:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 8675: 				   &escape($uname).':'.&escape($pid),
                   8676: 				   $homeserver));
1.709     albertel 8677:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8678: 	return (undef,undef);
                   8679:     }
1.706     raeburn  8680:     if ($outcome) {
                   8681:         ($result,$resulttype) = split(/:/,$outcome);
                   8682:     } 
                   8683:     return ($result,$resulttype);
                   8684: }
                   8685: 
                   8686: sub auto_photochoice {
                   8687:     my ($cnum,$cdom) = @_;
                   8688:     my $homeserver = &homeserver($cnum,$cdom);
                   8689:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 8690: 						       &escape($cdom),
                   8691: 						       $homeserver)));
1.709     albertel 8692:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   8693: 	return (undef,undef);
                   8694:     }
1.706     raeburn  8695:     return ($update,$comment);
                   8696: }
                   8697: 
                   8698: sub auto_photoupdate {
                   8699:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   8700:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 8701:     my $host=&hostname($homeserver);
1.706     raeburn  8702:     my $cmd = '';
                   8703:     my $maxtries = 1;
1.800     albertel 8704:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   8705:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  8706:     }
                   8707:     $cmd =~ s/%%$//;
                   8708:     $cmd = &escape($cmd);
                   8709:     my $query = 'institutionalphotos';
                   8710:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   8711:     unless ($queryid=~/^\Q$host\E\_/) {
                   8712:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   8713:         return 'error: '.$queryid;
                   8714:     }
                   8715:     my $reply = &get_query_reply($queryid);
                   8716:     my $tries = 1;
                   8717:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   8718:         $reply = &get_query_reply($queryid);
                   8719:         $tries ++;
                   8720:     }
                   8721:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   8722:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   8723:     } else {
                   8724:         my @responses = split(/:/,$reply);
                   8725:         my $outcome = shift(@responses); 
                   8726:         foreach my $item (@responses) {
                   8727:             my ($key,$value) = split(/=/,$item);
                   8728:             $$photo{$key} = $value;
                   8729:         }
                   8730:         return $outcome;
                   8731:     }
                   8732:     return 'error';
                   8733: }
                   8734: 
1.521     raeburn  8735: sub auto_instcode_format {
1.793     albertel 8736:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   8737: 	$cat_order) = @_;
1.521     raeburn  8738:     my $courses = '';
1.772     raeburn  8739:     my @homeservers;
1.521     raeburn  8740:     if ($caller eq 'global') {
1.841     albertel 8741: 	my %servers = &get_servers($codedom,'library');
                   8742: 	foreach my $tryserver (keys(%servers)) {
                   8743: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8744: 		push(@homeservers,$tryserver);
                   8745: 	    }
1.584     raeburn  8746:         }
1.1022    raeburn  8747:     } elsif ($caller eq 'requests') {
                   8748:         if ($codedom =~ /^$match_domain$/) {
                   8749:             my $chome = &domain($codedom,'primary');
                   8750:             unless ($chome eq 'no_host') {
                   8751:                 push(@homeservers,$chome);
                   8752:             }
                   8753:         }
1.521     raeburn  8754:     } else {
1.772     raeburn  8755:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  8756:     }
1.793     albertel 8757:     foreach my $code (keys(%{$instcodes})) {
                   8758:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  8759:     }
                   8760:     chop($courses);
1.772     raeburn  8761:     my $ok_response = 0;
                   8762:     my $response;
                   8763:     while (@homeservers > 0 && $ok_response == 0) {
                   8764:         my $server = shift(@homeservers); 
                   8765:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   8766:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   8767:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 8768: 		split(/:/,$response);
1.772     raeburn  8769:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   8770:             push(@{$codetitles},&str2array($codetitles_str));
                   8771:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   8772:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   8773:             $ok_response = 1;
                   8774:         }
                   8775:     }
                   8776:     if ($ok_response) {
1.521     raeburn  8777:         return 'ok';
1.772     raeburn  8778:     } else {
                   8779:         return $response;
1.521     raeburn  8780:     }
                   8781: }
                   8782: 
1.792     raeburn  8783: sub auto_instcode_defaults {
                   8784:     my ($domain,$returnhash,$code_order) = @_;
                   8785:     my @homeservers;
1.841     albertel 8786: 
                   8787:     my %servers = &get_servers($domain,'library');
                   8788:     foreach my $tryserver (keys(%servers)) {
                   8789: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8790: 	    push(@homeservers,$tryserver);
                   8791: 	}
1.792     raeburn  8792:     }
1.841     albertel 8793: 
1.792     raeburn  8794:     my $response;
1.841     albertel 8795:     foreach my $server (@homeservers) {
1.792     raeburn  8796:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 8797:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   8798: 	
                   8799: 	foreach my $pair (split(/\&/,$response)) {
                   8800: 	    my ($name,$value)=split(/\=/,$pair);
                   8801: 	    if ($name eq 'code_order') {
                   8802: 		@{$code_order} = split(/\&/,&unescape($value));
                   8803: 	    } else {
                   8804: 		$returnhash->{&unescape($name)}=&unescape($value);
                   8805: 	    }
                   8806: 	}
                   8807: 	return 'ok';
1.792     raeburn  8808:     }
1.841     albertel 8809: 
                   8810:     return $response;
1.1003    raeburn  8811: }
                   8812: 
                   8813: sub auto_possible_instcodes {
1.1007    raeburn  8814:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   8815:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   8816:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8817:         return;
                   8818:     }
1.1003    raeburn  8819:     my (@homeservers,$uhome);
                   8820:     if (defined(&domain($domain,'primary'))) {
                   8821:         $uhome=&domain($domain,'primary');
                   8822:         push(@homeservers,&domain($domain,'primary'));
                   8823:     } else {
                   8824:         my %servers = &get_servers($domain,'library');
                   8825:         foreach my $tryserver (keys(%servers)) {
                   8826:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   8827:                 push(@homeservers,$tryserver);
                   8828:             }
                   8829:         }
                   8830:     }
                   8831:     my $response;
                   8832:     foreach my $server (@homeservers) {
                   8833:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   8834:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  8835:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   8836:             split(':',$response);
                   8837:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   8838:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  8839:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  8840:             my ($name,$value)=split('=',$item);
                   8841:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8842:         }
                   8843:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  8844:             my ($name,$value)=split('=',$item);
                   8845:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  8846:         }
                   8847:         return 'ok';
                   8848:     }
                   8849:     return $response;
                   8850: }
1.792     raeburn  8851: 
1.1010    raeburn  8852: sub auto_courserequest_checks {
                   8853:     my ($dom) = @_;
1.1020    raeburn  8854:     my ($homeserver,%validations);
                   8855:     if ($dom =~ /^$match_domain$/) {
                   8856:         $homeserver = &domain($dom,'primary');
                   8857:     }
                   8858:     unless ($homeserver eq 'no_host') {
                   8859:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   8860:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8861:             my @items = split(/&/,$response);
                   8862:             foreach my $item (@items) {
                   8863:                 my ($key,$value) = split('=',$item);
                   8864:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   8865:             }
                   8866:         }
                   8867:     }
1.1010    raeburn  8868:     return %validations; 
                   8869: }
                   8870: 
1.1020    raeburn  8871: sub auto_courserequest_validation {
1.1255    raeburn  8872:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
1.1020    raeburn  8873:     my ($homeserver,$response);
                   8874:     if ($dom =~ /^$match_domain$/) {
                   8875:         $homeserver = &domain($dom,'primary');
                   8876:     }
1.1255    raeburn  8877:     unless ($homeserver eq 'no_host') {
                   8878:         my $customdata;
                   8879:         if (ref($custominfo) eq 'HASH') {
                   8880:             $customdata = &freeze_escape($custominfo);
                   8881:         }
1.1020    raeburn  8882:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  8883:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1255    raeburn  8884:                                     ':'.&escape($instcode).':'.&escape($instseclist).':'.
                   8885:                                     $customdata,$homeserver));
1.1020    raeburn  8886:     }
                   8887:     return $response;
                   8888: }
                   8889: 
1.777     albertel 8890: sub auto_validate_class_sec {
1.918     raeburn  8891:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  8892:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  8893:     my $ownerlist;
                   8894:     if (ref($owners) eq 'ARRAY') {
                   8895:         $ownerlist = join(',',@{$owners});
                   8896:     } else {
                   8897:         $ownerlist = $owners;
                   8898:     }
1.773     raeburn  8899:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  8900:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  8901:     return $response;
                   8902: }
                   8903: 
1.1367    raeburn  8904: sub auto_validate_instclasses {
                   8905:     my ($cdom,$cnum,$owners,$classesref) = @_;
                   8906:     my ($homeserver,%validations);
                   8907:     $homeserver = &homeserver($cnum,$cdom);
                   8908:     unless ($homeserver eq 'no_host') {
                   8909:         my $ownerlist;
                   8910:         if (ref($owners) eq 'ARRAY') {
                   8911:             $ownerlist = join(',',@{$owners});
                   8912:         } else {
                   8913:             $ownerlist = $owners;
                   8914:         }
                   8915:         if (ref($classesref) eq 'HASH') {
                   8916:             my $classes = &freeze_escape($classesref);
                   8917:             my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
                   8918:                                 ':'.$cdom.':'.$classes,$homeserver);
                   8919:             unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8920:                 my @items = split(/&/,$response);
                   8921:                 foreach my $item (@items) {
                   8922:                     my ($key,$value) = split('=',$item);
                   8923:                     $validations{&unescape($key)} = &thaw_unescape($value);
                   8924:                 }
                   8925:             }
                   8926:         }
                   8927:     }
                   8928:     return %validations;
                   8929: }
                   8930: 
1.1248    raeburn  8931: sub auto_crsreq_update {
                   8932:     my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
1.1257    raeburn  8933:         $code,$accessstart,$accessend,$inbound) = @_;
1.1248    raeburn  8934:     my ($homeserver,%crsreqresponse);
                   8935:     if ($cdom =~ /^$match_domain$/) {
                   8936:         $homeserver = &domain($cdom,'primary');
                   8937:     }
                   8938:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8939:         my $info;
                   8940:         if (ref($inbound) eq 'HASH') {
                   8941:             $info = &freeze_escape($inbound);
                   8942:         }
                   8943:         my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
                   8944:                             ':'.&escape($action).':'.&escape($ownername).':'.
                   8945:                             &escape($ownerdomain).':'.&escape($fullname).':'.
1.1257    raeburn  8946:                             &escape($title).':'.&escape($code).':'.
                   8947:                             &escape($accessstart).':'.&escape($accessend).':'.$info,
                   8948:                             $homeserver);
1.1248    raeburn  8949:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   8950:             my @items = split(/&/,$response);
                   8951:             foreach my $item (@items) {
                   8952:                 my ($key,$value) = split('=',$item);
                   8953:                 $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
                   8954:             }
                   8955:         }
                   8956:     }
                   8957:     return \%crsreqresponse;
                   8958: }
                   8959: 
1.1305    raeburn  8960: sub auto_export_grades {
1.1309    raeburn  8961:     my ($cdom,$cnum,$inforef,$gradesref) = @_;
                   8962:     my ($homeserver,%exportresponse);
                   8963:     if ($cdom =~ /^$match_domain$/) {
                   8964:         $homeserver = &domain($cdom,'primary');
                   8965:     }
                   8966:     unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
                   8967:         my $info;
                   8968:         if (ref($inforef) eq 'HASH') {
                   8969:             $info = &freeze_escape($inforef);
                   8970:         }
                   8971:         if (ref($gradesref) eq 'HASH') {
                   8972:             my $grades = &freeze_escape($gradesref);
                   8973:             my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
                   8974:                                 $info.':'.$grades,$homeserver);
                   8975:             unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
                   8976:                 my @items = split(/&/,$response);
                   8977:                 foreach my $item (@items) {
                   8978:                     my ($key,$value) = split('=',$item);
                   8979:                     $exportresponse{&unescape($key)} = &thaw_unescape($value);
                   8980:                 }
                   8981:             }
                   8982:         }
                   8983:     }
                   8984:     return \%exportresponse;
1.1305    raeburn  8985: }
                   8986: 
1.1287    raeburn  8987: sub check_instcode_cloning {
                   8988:     my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
                   8989:     unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   8990:         return;
                   8991:     }
                   8992:     my $canclone;
                   8993:     if (@{$code_order} > 0) {
                   8994:         my $instcoderegexp ='^';
                   8995:         my @clonecodes = split(/\&/,$cloner);
                   8996:         foreach my $item (@{$code_order}) {
                   8997:             if (grep(/^\Q$item\E=/,@clonecodes)) {
                   8998:                 foreach my $pair (@clonecodes) {
                   8999:                     my ($key,$val) = split(/\=/,$pair,2);
                   9000:                     $val = &unescape($val);
                   9001:                     if ($key eq $item) {
                   9002:                         $instcoderegexp .= '('.$val.')';
                   9003:                         last;
                   9004:                     }
                   9005:                 }
                   9006:             } else {
                   9007:                 $instcoderegexp .= $codedefaults->{$item};
                   9008:             }
                   9009:         }
                   9010:         $instcoderegexp .= '$';
                   9011:         my (@from,@to);
                   9012:         eval {
                   9013:                (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9014:                (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9015:         };
                   9016:         if ((@from > 0) && (@to > 0)) {
                   9017:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9018:             if (!@diffs) {
                   9019:                 $canclone = 1;
                   9020:             }
                   9021:         }
                   9022:     }
                   9023:     return $canclone;
                   9024: }
                   9025: 
                   9026: sub default_instcode_cloning {
                   9027:     my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
                   9028:     my (%codedefaults,@code_order,$canclone);
                   9029:     if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
                   9030:         %codedefaults = %{$codedefaultsref};
                   9031:         @code_order = @{$codeorderref};
                   9032:     } elsif ($clonedom) {
                   9033:         &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
                   9034:     }
                   9035:     if (($domdefclone) && (@code_order)) {
                   9036:         my @clonecodes = split(/\+/,$domdefclone);
                   9037:         my $instcoderegexp ='^';
                   9038:         foreach my $item (@code_order) {
                   9039:             if (grep(/^\Q$item\E$/,@clonecodes)) {
                   9040:                 $instcoderegexp .= '('.$codedefaults{$item}.')';
                   9041:             } else {
                   9042:                 $instcoderegexp .= $codedefaults{$item};
                   9043:             }
                   9044:         }
                   9045:         $instcoderegexp .= '$';
                   9046:         my (@from,@to);
                   9047:         eval {
                   9048:             (@from) = ($clonefromcode =~ /$instcoderegexp/);
                   9049:             (@to) = ($clonetocode =~ /$instcoderegexp/);
                   9050:         };
                   9051:         if ((@from > 0) && (@to > 0)) {
                   9052:             my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
                   9053:             if (!@diffs) {
                   9054:                 $canclone = 1;
                   9055:             }
                   9056:         }
                   9057:     }
                   9058:     return $canclone;
                   9059: }
                   9060: 
1.679     raeburn  9061: # ------------------------------------------------------- Course Group routines
                   9062: 
                   9063: sub get_coursegroups {
1.809     raeburn  9064:     my ($cdom,$cnum,$group,$namespace) = @_;
                   9065:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  9066: }
                   9067: 
1.679     raeburn  9068: sub modify_coursegroup {
                   9069:     my ($cdom,$cnum,$groupsettings) = @_;
                   9070:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   9071: }
                   9072: 
1.809     raeburn  9073: sub toggle_coursegroup_status {
                   9074:     my ($cdom,$cnum,$group,$action) = @_;
                   9075:     my ($from_namespace,$to_namespace);
                   9076:     if ($action eq 'delete') {
                   9077:         $from_namespace = 'coursegroups';
                   9078:         $to_namespace = 'deleted_groups';
                   9079:     } else {
                   9080:         $from_namespace = 'deleted_groups';
                   9081:         $to_namespace = 'coursegroups';
                   9082:     }
                   9083:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  9084:     if (my $tmp = &error(%curr_group)) {
                   9085:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   9086:         return ('read error',$tmp);
                   9087:     } else {
                   9088:         my %savedsettings = %curr_group; 
1.809     raeburn  9089:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  9090:         my $deloutcome;
                   9091:         if ($result eq 'ok') {
1.809     raeburn  9092:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  9093:         } else {
                   9094:             return ('write error',$result);
                   9095:         }
                   9096:         if ($deloutcome eq 'ok') {
                   9097:             return 'ok';
                   9098:         } else {
                   9099:             return ('delete error',$deloutcome);
                   9100:         }
                   9101:     }
                   9102: }
                   9103: 
1.679     raeburn  9104: sub modify_group_roles {
1.957     raeburn  9105:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  9106:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   9107:     my $role = 'gr/'.&escape($userprivs);
                   9108:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  9109:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  9110:     if ($result eq 'ok') {
                   9111:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   9112:     }
1.679     raeburn  9113:     return $result;
                   9114: }
                   9115: 
                   9116: sub modify_coursegroup_membership {
                   9117:     my ($cdom,$cnum,$membership) = @_;
                   9118:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   9119:     return $result;
                   9120: }
                   9121: 
1.682     raeburn  9122: sub get_active_groups {
                   9123:     my ($udom,$uname,$cdom,$cnum) = @_;
                   9124:     my $now = time;
                   9125:     my %groups = ();
                   9126:     foreach my $key (keys(%env)) {
1.811     albertel 9127:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  9128:             my ($start,$end) = split(/\./,$env{$key});
                   9129:             if (($end!=0) && ($end<$now)) { next; }
                   9130:             if (($start!=0) && ($start>$now)) { next; }
                   9131:             if ($1 eq $cdom && $2 eq $cnum) {
                   9132:                 $groups{$3} = $env{$key} ;
                   9133:             }
                   9134:         }
                   9135:     }
                   9136:     return %groups;
                   9137: }
                   9138: 
1.683     raeburn  9139: sub get_group_membership {
                   9140:     my ($cdom,$cnum,$group) = @_;
                   9141:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   9142: }
                   9143: 
                   9144: sub get_users_groups {
                   9145:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  9146:     my @usersgroups;
1.683     raeburn  9147:     my $cachetime=1800;
                   9148: 
                   9149:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  9150:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   9151:     if (defined($cached)) {
1.734     albertel 9152:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  9153:     } else {  
                   9154:         $grouplist = '';
1.816     raeburn  9155:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  9156:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  9157:         my $access_end = $env{'course.'.$courseid.
                   9158:                               '.default_enrollment_end_date'};
                   9159:         my $now = time;
                   9160:         foreach my $key (keys(%roleshash)) {
                   9161:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   9162:                 my $group = $1;
                   9163:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   9164:                     my $start = $2;
                   9165:                     my $end = $1;
                   9166:                     if ($start == -1) { next; } # deleted from group
                   9167:                     if (($start!=0) && ($start>$now)) { next; }
                   9168:                     if (($end!=0) && ($end<$now)) {
                   9169:                         if ($access_end && $access_end < $now) {
                   9170:                             if ($access_end - $end < 86400) {
                   9171:                                 push(@usersgroups,$group);
1.733     raeburn  9172:                             }
                   9173:                         }
1.817     raeburn  9174:                         next;
1.733     raeburn  9175:                     }
1.817     raeburn  9176:                     push(@usersgroups,$group);
1.683     raeburn  9177:                 }
                   9178:             }
                   9179:         }
1.817     raeburn  9180:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   9181:         $grouplist = join(':',@usersgroups);
                   9182:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  9183:     }
1.733     raeburn  9184:     return @usersgroups;
1.683     raeburn  9185: }
                   9186: 
                   9187: sub devalidate_getgroups_cache {
                   9188:     my ($udom,$uname,$cdom,$cnum)=@_;
                   9189:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 9190: 
1.683     raeburn  9191:     my $hashid="$udom:$uname:$courseid";
                   9192:     &devalidate_cache_new('getgroups',$hashid);
                   9193: }
                   9194: 
1.12      www      9195: # ------------------------------------------------------------------ Plain Text
                   9196: 
                   9197: sub plaintext {
1.988     raeburn  9198:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  9199:     if ($short =~ m{^cr/}) {
1.758     albertel 9200: 	return (split('/',$short))[-1];
                   9201:     }
1.742     raeburn  9202:     if (!defined($cid)) {
                   9203:         $cid = $env{'request.course.id'};
                   9204:     }
                   9205:     my %rolenames = (
1.1008    raeburn  9206:                       Course    => 'std',
                   9207:                       Community => 'alt1',
1.1305    raeburn  9208:                       Placement => 'std',
1.742     raeburn  9209:                     );
1.1037    raeburn  9210:     if ($cid ne '') {
                   9211:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   9212:             unless ($forcedefault) {
                   9213:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   9214:                 &Apache::lonlocal::mt_escape(\$roletext);
                   9215:                 return &Apache::lonlocal::mt($roletext);
                   9216:             }
                   9217:         }
                   9218:     }
                   9219:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   9220:         (defined($rolenames{$type})) && 
                   9221:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  9222:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  9223:     } elsif ($cid ne '') {
                   9224:         my $crstype = $env{'course.'.$cid.'.type'};
                   9225:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   9226:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   9227:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   9228:         }
1.742     raeburn  9229:     }
1.1037    raeburn  9230:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      9231: }
                   9232: 
                   9233: # ----------------------------------------------------------------- Assign Role
                   9234: 
                   9235: sub assignrole {
1.957     raeburn  9236:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   9237:         $context)=@_;
1.21      www      9238:     my $mrole;
                   9239:     if ($role =~ /^cr\//) {
1.393     www      9240:         my $cwosec=$url;
1.811     albertel 9241:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      9242: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  9243:            my $refused = 1;
                   9244:            if ($context eq 'requestcourses') {
                   9245:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   9246:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   9247:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   9248:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9249:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9250:                            if ($crsenv{'internal.courseowner'} eq
                   9251:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   9252:                                $refused = '';
                   9253:                            }
                   9254:                        }
                   9255:                    }
                   9256:                }
                   9257:            }
                   9258:            if ($refused) {
                   9259:                &logthis('Refused custom assignrole: '.
                   9260:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   9261:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   9262:                return 'refused';
                   9263:            }
1.104     www      9264:         }
1.21      www      9265:         $mrole='cr';
1.678     raeburn  9266:     } elsif ($role =~ /^gr\//) {
                   9267:         my $cwogrp=$url;
1.811     albertel 9268:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  9269:         unless (&allowed('mdg',$cwogrp)) {
                   9270:             &logthis('Refused group assignrole: '.
                   9271:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   9272:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   9273:             return 'refused';
                   9274:         }
                   9275:         $mrole='gr';
1.21      www      9276:     } else {
1.82      www      9277:         my $cwosec=$url;
1.811     albertel 9278:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  9279:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   9280:             my $refused;
                   9281:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   9282:                 if (!(&allowed('c'.$role,$url))) {
                   9283:                     $refused = 1;
                   9284:                 }
                   9285:             } else {
                   9286:                 $refused = 1;
                   9287:             }
1.947     raeburn  9288:             if ($refused) {
1.1045    raeburn  9289:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   9290:                 if (!$selfenroll && $context eq 'course') {
                   9291:                     my %crsenv;
                   9292:                     if ($role eq 'cc' || $role eq 'co') {
                   9293:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9294:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   9295:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   9296:                                 if ($crsenv{'internal.courseowner'} eq 
                   9297:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9298:                                     $refused = '';
                   9299:                                 }
                   9300:                             }
                   9301:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   9302:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   9303:                                 if ($crsenv{'internal.courseowner'} eq 
                   9304:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   9305:                                     $refused = '';
                   9306:                                 }
                   9307:                             }
                   9308:                         }
                   9309:                     }
1.1368    raeburn  9310:                 } elsif (($selfenroll == 1) && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   9311:                     if ($role eq 'st') {
                   9312:                         $refused = '';
                   9313:                     } elsif (($context eq 'ltienroll') && ($env{'request.lti'})) {
                   9314:                         $refused = '';
                   9315:                     }
1.1017    raeburn  9316:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  9317:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  9318:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  9319:                         my $wrongcc;
                   9320:                         if ($cnum =~ /^$match_community$/) {
                   9321:                             $wrongcc = 1 if ($role eq 'cc');
                   9322:                         } else {
                   9323:                             $wrongcc = 1 if ($role eq 'co');
                   9324:                         }
                   9325:                         unless ($wrongcc) {
                   9326:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   9327:                             if ($crsenv{'internal.courseowner'} eq 
                   9328:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   9329:                                 $refused = '';
                   9330:                             }
1.1017    raeburn  9331:                         }
                   9332:                     }
1.1183    raeburn  9333:                 } elsif ($context eq 'requestauthor') {
                   9334:                     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) && 
                   9335:                         ($url eq '/'.$udom.'/') && ($role eq 'au')) {
                   9336:                         if ($env{'environment.requestauthor'} eq 'automatic') {
                   9337:                             $refused = '';
                   9338:                         } else {
                   9339:                             my %domdefaults = &get_domain_defaults($udom);
                   9340:                             if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
                   9341:                                 my $checkbystatus;
                   9342:                                 if ($env{'user.adv'}) { 
                   9343:                                     my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
                   9344:                                     if ($disposition eq 'automatic') {
                   9345:                                         $refused = '';
                   9346:                                     } elsif ($disposition eq '') {
                   9347:                                         $checkbystatus = 1;
                   9348:                                     } 
                   9349:                                 } else {
                   9350:                                     $checkbystatus = 1;
                   9351:                                 }
                   9352:                                 if ($checkbystatus) {
                   9353:                                     if ($env{'environment.inststatus'}) {
                   9354:                                         my @inststatuses = split(/,/,$env{'environment.inststatus'});
                   9355:                                         foreach my $type (@inststatuses) {
                   9356:                                             if (($type ne '') &&
                   9357:                                                 ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
                   9358:                                                 $refused = '';
                   9359:                                             }
                   9360:                                         }
                   9361:                                     } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
                   9362:                                         $refused = '';
                   9363:                                     }
                   9364:                                 }
                   9365:                             }
                   9366:                         }
                   9367:                     }
1.1017    raeburn  9368:                 }
                   9369:                 if ($refused) {
1.947     raeburn  9370:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   9371:                              ' '.$role.' '.$end.' '.$start.' by '.
                   9372: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   9373:                     return 'refused';
                   9374:                 }
1.932     raeburn  9375:             }
1.1131    raeburn  9376:         } elsif ($role eq 'au') {
                   9377:             if ($url ne '/'.$udom.'/') {
                   9378:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   9379:                          ' to assign author role for '.$uname.':'.$udom.
                   9380:                          ' in domain: '.$url.' refused (wrong domain).');
                   9381:                 return 'refused';
                   9382:             }
1.104     www      9383:         }
1.21      www      9384:         $mrole=$role;
                   9385:     }
1.620     albertel 9386:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      9387:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      9388:     if ($end) { $command.='_'.$end; }
1.21      www      9389:     if ($start) {
                   9390: 	if ($end) { 
1.81      www      9391:            $command.='_'.$start; 
1.21      www      9392:         } else {
1.81      www      9393:            $command.='_0_'.$start;
1.21      www      9394:         }
                   9395:     }
1.739     raeburn  9396:     my $origstart = $start;
                   9397:     my $origend = $end;
1.957     raeburn  9398:     my $delflag;
1.357     www      9399: # actually delete
                   9400:     if ($deleteflag) {
1.373     www      9401: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      9402: # modify command to delete the role
1.620     albertel 9403:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      9404:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 9405: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      9406: # set start and finish to negative values for userrolelog
                   9407:            $start=-1;
                   9408:            $end=-1;
1.957     raeburn  9409:            $delflag = 1;
1.357     www      9410:         }
                   9411:     }
                   9412: # send command
1.349     www      9413:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      9414: # log new user role if status is ok
1.349     www      9415:     if ($answer eq 'ok') {
1.663     raeburn  9416: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.1184    raeburn  9417:         if (($role eq 'cc') || ($role eq 'in') ||
                   9418:             ($role eq 'ep') || ($role eq 'ad') ||
                   9419:             ($role eq 'ta') || ($role eq 'st') ||
                   9420:             ($role=~/^cr/) || ($role eq 'gr') ||
                   9421:             ($role eq 'co')) {
1.1200    raeburn  9422: # for course roles, perform group memberships changes triggered by role change.
                   9423:             unless ($role =~ /^gr/) {
                   9424:                 &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
                   9425:                                                  $origstart,$selfenroll,$context);
                   9426:             }
1.1184    raeburn  9427:             &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9428:                            $selfenroll,$context);
                   9429:         } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
1.1334    raeburn  9430:                  ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
                   9431:                  ($role eq 'da')) {
1.1184    raeburn  9432:             &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9433:                            $context);
                   9434:         } elsif (($role eq 'ca') || ($role eq 'aa')) {
                   9435:             &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
                   9436:                              $context); 
                   9437:         }
1.1053    raeburn  9438:         if ($role eq 'cc') {
                   9439:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   9440:         }
1.349     www      9441:     }
                   9442:     return $answer;
1.169     harris41 9443: }
                   9444: 
1.1053    raeburn  9445: sub autoupdate_coowners {
                   9446:     my ($url,$end,$start,$uname,$udom) = @_;
                   9447:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   9448:     if (($cdom ne '') && ($cnum ne '')) {
                   9449:         my $now = time;
                   9450:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   9451:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   9452:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   9453:             my $instcode = $coursehash{'internal.coursecode'};
                   9454:             if ($instcode ne '') {
1.1056    raeburn  9455:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   9456:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  9457:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  9458:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   9459:                         if ($result eq 'valid') {
                   9460:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  9461:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9462:                                     push(@newcoowners,$coowner);
                   9463:                                 }
                   9464:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   9465:                                     push(@newcoowners,$uname.':'.$udom);
                   9466:                                 }
                   9467:                                 @newcoowners = sort(@newcoowners);
                   9468:                             } else {
                   9469:                                 push(@newcoowners,$uname.':'.$udom);
                   9470:                             }
                   9471:                         } else {
                   9472:                             if ($coursehash{'internal.co-owners'}) {
                   9473:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   9474:                                     unless ($coowner eq $uname.':'.$udom) {
                   9475:                                         push(@newcoowners,$coowner);
                   9476:                                     }
                   9477:                                 }
                   9478:                                 unless (@newcoowners > 0) {
                   9479:                                     $delcoowners = 1;
                   9480:                                     $coowners = '';
                   9481:                                 }
                   9482:                             }
                   9483:                         }
                   9484:                         if (@newcoowners || $delcoowners) {
                   9485:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   9486:                                             $delcoowners,@newcoowners);
                   9487:                         }
                   9488:                     }
                   9489:                 }
                   9490:             }
                   9491:         }
                   9492:     }
                   9493: }
                   9494: 
                   9495: sub store_coowners {
                   9496:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   9497:     my $cid = $cdom.'_'.$cnum;
                   9498:     my ($coowners,$delresult,$putresult);
                   9499:     if (@newcoowners) {
                   9500:         $coowners = join(',',@newcoowners);
                   9501:         my %coownershash = (
                   9502:                             'internal.co-owners' => $coowners,
                   9503:                            );
                   9504:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   9505:         if ($putresult eq 'ok') {
                   9506:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   9507:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   9508:             }
                   9509:         }
                   9510:     }
                   9511:     if ($delcoowners) {
                   9512:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   9513:         if ($delresult eq 'ok') {
                   9514:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   9515:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   9516:             }
                   9517:         }
                   9518:     }
                   9519:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   9520:         my %crsinfo =
                   9521:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   9522:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   9523:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   9524:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   9525:         }
                   9526:     }
                   9527: }
                   9528: 
1.169     harris41 9529: # -------------------------------------------------- Modify user authentication
1.197     www      9530: # Overrides without validation
                   9531: 
1.169     harris41 9532: sub modifyuserauth {
                   9533:     my ($udom,$uname,$umode,$upass)=@_;
                   9534:     my $uhome=&homeserver($uname,$udom);
1.197     www      9535:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   9536:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 9537:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9538:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 9539:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   9540: 		     &escape($upass),$uhome);
1.620     albertel 9541:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      9542:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   9543:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   9544:     &log($udom,,$uname,$uhome,
1.620     albertel 9545:         'Authentication changed by '.$env{'user.domain'}.', '.
                   9546:                                      $env{'user.name'}.', '.$umode.
1.197     www      9547:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 9548:     unless ($reply eq 'ok') {
1.197     www      9549:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 9550: 	return 'error: '.$reply;
                   9551:     }   
1.170     harris41 9552:     return 'ok';
1.80      www      9553: }
                   9554: 
1.81      www      9555: # --------------------------------------------------------------- Modify a user
1.80      www      9556: 
1.81      www      9557: sub modifyuser {
1.206     matthew  9558:     my ($udom,    $uname, $uid,
                   9559:         $umode,   $upass, $first,
                   9560:         $middle,  $last,  $gene,
1.1058    raeburn  9561:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 9562:     $udom= &LONCAPA::clean_domain($udom);
                   9563:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  9564:     my $showcandelete = 'none';
                   9565:     if (ref($candelete) eq 'ARRAY') {
                   9566:         if (@{$candelete} > 0) {
                   9567:             $showcandelete = join(', ',@{$candelete});
                   9568:         }
                   9569:     }
1.81      www      9570:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      9571:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  9572: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  9573:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   9574:                                      ' desiredhome not specified'). 
1.620     albertel 9575:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   9576:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 9577:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  9578:     my $newuser;
                   9579:     if ($uhome eq 'no_host') {
                   9580:         $newuser = 1;
1.1368    raeburn  9581:         unless (($umode && ($upass ne '')) || ($umode eq 'localauth') ||
                   9582:                 ($umode eq 'lti')) {
                   9583:             return 'error: more information needed to create new user';
                   9584:         }
1.1075    raeburn  9585:     }
1.80      www      9586: # ----------------------------------------------------------------- Create User
1.406     albertel 9587:     if (($uhome eq 'no_host') && 
1.1368    raeburn  9588: 	(($umode && $upass) || ($umode eq 'localauth') || ($umode eq 'lti'))) {
1.80      www      9589:         my $unhome='';
1.844     albertel 9590:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  9591:             $unhome = $desiredhome;
1.620     albertel 9592: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   9593: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  9594:         } else { # load balancing routine for determining $unhome
1.81      www      9595:             my $loadm=10000000;
1.841     albertel 9596: 	    my %servers = &get_servers($udom,'library');
                   9597: 	    foreach my $tryserver (keys(%servers)) {
                   9598: 		my $answer=reply('load',$tryserver);
                   9599: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   9600: 		    $loadm=$answer;
                   9601: 		    $unhome=$tryserver;
                   9602: 		}
1.80      www      9603: 	    }
                   9604:         }
                   9605:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  9606: 	    return 'error: unable to find a home server for '.$uname.
                   9607:                    ' in domain '.$udom;
1.80      www      9608:         }
                   9609:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   9610:                          &escape($upass),$unhome);
                   9611: 	unless ($reply eq 'ok') {
                   9612:             return 'error: '.$reply;
                   9613:         }   
1.230     stredwic 9614:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      9615:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  9616: 	    return 'error: unable verify users home machine.';
1.80      www      9617:         }
1.209     matthew  9618:     }   # End of creation of new user
1.80      www      9619: # ---------------------------------------------------------------------- Add ID
                   9620:     if ($uid) {
                   9621:        $uid=~tr/A-Z/a-z/;
                   9622:        my %uidhash=&idrget($udom,$uname);
1.196     www      9623:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   9624:          && (!$forceid)) {
1.80      www      9625: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  9626: 	      return 'error: user id "'.$uid.'" does not match '.
                   9627:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      9628:           }
                   9629:        } else {
1.1300    raeburn  9630: 	  &idput($udom,{$uname => $uid},$uhome,'ids');
1.80      www      9631:        }
                   9632:     }
                   9633: # -------------------------------------------------------------- Add names, etc
1.313     matthew  9634:     my @tmp=&get('environment',
1.899     raeburn  9635: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  9636:                     'permanentemail','inststatus'],
1.134     albertel 9637: 		   $udom,$uname);
1.1075    raeburn  9638:     my (%names,%oldnames);
1.313     matthew  9639:     if ($tmp[0] =~ m/^error:.*/) { 
                   9640:         %names=(); 
                   9641:     } else {
                   9642:         %names = @tmp;
1.1075    raeburn  9643:         %oldnames = %names;
1.313     matthew  9644:     }
1.388     www      9645: #
1.1058    raeburn  9646: # If name, email and/or uid are blank (e.g., because an uploaded file
                   9647: # of users did not contain them), do not overwrite existing values
                   9648: # unless field is in $candelete array ref.  
                   9649: #
                   9650: 
                   9651:     my @fields = ('firstname','middlename','lastname','generation',
                   9652:                   'permanentemail','id');
                   9653:     my %newvalues;
                   9654:     if (ref($candelete) eq 'ARRAY') {
                   9655:         foreach my $field (@fields) {
                   9656:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   9657:                 if ($field eq 'firstname') {
                   9658:                     $names{$field} = $first;
                   9659:                 } elsif ($field eq 'middlename') {
                   9660:                     $names{$field} = $middle;
                   9661:                 } elsif ($field eq 'lastname') {
                   9662:                     $names{$field} = $last;
                   9663:                 } elsif ($field eq 'generation') { 
                   9664:                     $names{$field} = $gene;
                   9665:                 } elsif ($field eq 'permanentemail') {
                   9666:                     $names{$field} = $email;
                   9667:                 } elsif ($field eq 'id') {
                   9668:                     $names{$field}  = $uid;
                   9669:                 }
                   9670:             }
                   9671:         }
                   9672:     }
1.388     www      9673:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  9674:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      9675:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  9676:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      9677:     if ($email) {
                   9678:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  9679:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      9680:     }
1.899     raeburn  9681:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  9682:     if (defined($inststatus)) {
                   9683:         $names{'inststatus'} = '';
                   9684:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   9685:         if (ref($usertypes) eq 'HASH') {
                   9686:             my @okstatuses; 
                   9687:             foreach my $item (split(/:/,$inststatus)) {
                   9688:                 if (defined($usertypes->{$item})) {
                   9689:                     push(@okstatuses,$item);  
                   9690:                 }
                   9691:             }
                   9692:             if (@okstatuses) {
                   9693:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   9694:             }
                   9695:         }
                   9696:     }
1.1075    raeburn  9697:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  9698:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  9699:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  9700:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   9701:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   9702:     } else {
                   9703:         $logmsg .= ' during self creation';
                   9704:     }
1.1075    raeburn  9705:     my $changed;
                   9706:     if ($newuser) {
                   9707:         $changed = 1;
                   9708:     } else {
                   9709:         foreach my $field (@fields) {
                   9710:             if ($names{$field} ne $oldnames{$field}) {
                   9711:                 $changed = 1;
                   9712:                 last;
                   9713:             }
                   9714:         }
                   9715:     }
                   9716:     unless ($changed) {
                   9717:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   9718:         &logthis($logmsg);
                   9719:         return 'ok';
                   9720:     }
                   9721:     my $reply = &put('environment', \%names, $udom,$uname);
                   9722:     if ($reply ne 'ok') { 
                   9723:         return 'error: '.$reply;
                   9724:     }
1.1087    raeburn  9725:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   9726:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   9727:     }
1.1075    raeburn  9728:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   9729:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   9730:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  9731:     &logthis($logmsg);
1.134     albertel 9732:     return 'ok';
1.80      www      9733: }
                   9734: 
1.81      www      9735: # -------------------------------------------------------------- Modify student
1.80      www      9736: 
1.81      www      9737: sub modifystudent {
                   9738:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  9739:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.1314    raeburn  9740:         $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
1.455     albertel 9741:     if (!$cid) {
1.620     albertel 9742: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9743: 	    return 'not_in_class';
                   9744: 	}
1.80      www      9745:     }
                   9746: # --------------------------------------------------------------- Make the user
1.81      www      9747:     my $reply=&modifyuser
1.209     matthew  9748: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  9749:          $desiredhome,$email,$inststatus);
1.80      www      9750:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  9751:     # This will cause &modify_student_enrollment to get the uid from the
1.1235    raeburn  9752:     # student's environment
1.297     matthew  9753:     $uid = undef if (!$forceid);
1.455     albertel 9754:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.1216    raeburn  9755:                                         $gene,$usec,$end,$start,$type,$locktype,
1.1314    raeburn  9756:                                         $cid,$selfenroll,$context,$credits,$instsec);
1.297     matthew  9757:     return $reply;
                   9758: }
                   9759: 
                   9760: sub modify_student_enrollment {
1.1216    raeburn  9761:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
1.1314    raeburn  9762:         $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
1.455     albertel 9763:     my ($cdom,$cnum,$chome);
                   9764:     if (!$cid) {
1.620     albertel 9765: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 9766: 	    return 'not_in_class';
                   9767: 	}
1.620     albertel 9768: 	$cdom=$env{'course.'.$cid.'.domain'};
                   9769: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 9770:     } else {
                   9771: 	($cdom,$cnum)=split(/_/,$cid);
                   9772:     }
1.620     albertel 9773:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 9774:     if (!$chome) {
1.457     raeburn  9775: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  9776:     }
1.455     albertel 9777:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  9778:     # Make sure the user exists
1.81      www      9779:     my $uhome=&homeserver($uname,$udom);
                   9780:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9781: 	return 'error: no such user';
                   9782:     }
1.297     matthew  9783:     # Get student data if we were not given enough information
                   9784:     if (!defined($first)  || $first  eq '' || 
                   9785:         !defined($last)   || $last   eq '' || 
                   9786:         !defined($uid)    || $uid    eq '' || 
                   9787:         !defined($middle) || $middle eq '' || 
                   9788:         !defined($gene)   || $gene   eq '') {
1.294     matthew  9789:         # They did not supply us with enough data to enroll the student, so
                   9790:         # we need to pick up more information.
1.297     matthew  9791:         my %tmp = &get('environment',
1.294     matthew  9792:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  9793:                        ,$udom,$uname);
                   9794: 
1.800     albertel 9795:         #foreach my $key (keys(%tmp)) {
                   9796:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 9797:         #}
1.294     matthew  9798:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   9799:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   9800:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  9801:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  9802:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   9803:     }
1.556     albertel 9804:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  9805:     my $user = "$uname:$udom";
                   9806:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 9807:     my $reply=cput('classlist',
1.1148    raeburn  9808: 		   {$user => 
1.1314    raeburn  9809: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
1.487     albertel 9810: 		   $cdom,$cnum);
1.1148    raeburn  9811:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   9812:         &devalidate_getsection_cache($udom,$uname,$cid);
                   9813:     } else { 
1.81      www      9814: 	return 'error: '.$reply;
                   9815:     }
1.297     matthew  9816:     # Add student role to user
1.83      www      9817:     my $uurl='/'.$cid;
1.81      www      9818:     $uurl=~s/\_/\//g;
                   9819:     if ($usec) {
                   9820: 	$uurl.='/'.$usec;
                   9821:     }
1.1148    raeburn  9822:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   9823:                              $selfenroll,$context);
                   9824:     if ($result ne 'ok') {
                   9825:         if ($old_entry{$user} ne '') {
                   9826:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   9827:         } else {
                   9828:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   9829:         }
                   9830:     }
                   9831:     return $result; 
1.21      www      9832: }
                   9833: 
1.556     albertel 9834: sub format_name {
                   9835:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   9836:     my $name;
                   9837:     if ($first ne 'lastname') {
                   9838: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   9839:     } else {
                   9840: 	if ($lastname=~/\S/) {
                   9841: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   9842: 	    $name=~s/\s+,/,/;
                   9843: 	} else {
                   9844: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   9845: 	}
                   9846:     }
                   9847:     $name=~s/^\s+//;
                   9848:     $name=~s/\s+$//;
                   9849:     $name=~s/\s+/ /g;
                   9850:     return $name;
                   9851: }
                   9852: 
1.84      www      9853: # ------------------------------------------------- Write to course preferences
                   9854: 
                   9855: sub writecoursepref {
                   9856:     my ($courseid,%prefs)=@_;
                   9857:     $courseid=~s/^\///;
                   9858:     $courseid=~s/\_/\//g;
                   9859:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   9860:     my $chome=homeserver($cnum,$cdomain);
                   9861:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   9862: 	return 'error: no such course';
                   9863:     }
                   9864:     my $cstring='';
1.800     albertel 9865:     foreach my $pref (keys(%prefs)) {
                   9866: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 9867:     }
1.84      www      9868:     $cstring=~s/\&$//;
                   9869:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   9870: }
                   9871: 
                   9872: # ---------------------------------------------------------- Make/modify course
                   9873: 
                   9874: sub createcourse {
1.741     raeburn  9875:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  9876:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      9877:     $url=&declutter($url);
                   9878:     my $cid='';
1.1028    raeburn  9879:     if ($context eq 'requestcourses') {
                   9880:         my $can_create = 0;
                   9881:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   9882:         if ($udom eq $ownerdom) {
                   9883:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   9884:                                   $context)) {
                   9885:                 $can_create = 1;
                   9886:             }
                   9887:         } else {
                   9888:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   9889:                                            $category);
                   9890:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   9891:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   9892:                 if (@curr > 0) {
                   9893:                     my @options = qw(approval validate autolimit);
                   9894:                     my $optregex = join('|',@options);
                   9895:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   9896:                         $can_create = 1;
                   9897:                     }
                   9898:                 }
                   9899:             }
                   9900:         }
                   9901:         if ($can_create) {
                   9902:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   9903:                 unless (&allowed('ccc',$udom)) {
                   9904:                     return 'refused'; 
                   9905:                 }
1.1017    raeburn  9906:             }
                   9907:         } else {
                   9908:             return 'refused';
                   9909:         }
1.1028    raeburn  9910:     } elsif (!&allowed('ccc',$udom)) {
                   9911:         return 'refused';
1.84      www      9912:     }
1.1011    raeburn  9913: # --------------------------------------------------------------- Get Unique ID
                   9914:     my $uname;
                   9915:     if ($cnum =~ /^$match_courseid$/) {
                   9916:         my $chome=&homeserver($cnum,$udom,'true');
                   9917:         if (($chome eq '') || ($chome eq 'no_host')) {
                   9918:             $uname = $cnum;
                   9919:         } else {
1.1038    raeburn  9920:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9921:         }
                   9922:     } else {
1.1038    raeburn  9923:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  9924:     }
                   9925:     return $uname if ($uname =~ /^error/);
                   9926: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  9927:     if (!defined($course_server)) {
                   9928:         if (defined(&domain($udom,'primary'))) {
                   9929:             $course_server = &domain($udom,'primary');
                   9930:         } else {
                   9931:             $course_server = $env{'user.home'}; 
                   9932:         }
                   9933:     }
                   9934:     my %host_servers =
                   9935:         &Apache::lonnet::get_servers($udom,'library');
                   9936:     unless ($host_servers{$course_server}) {
                   9937:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  9938:     }
1.84      www      9939: # ------------------------------------------------------------- Make the course
                   9940:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  9941:                       $course_server);
1.84      www      9942:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  9943:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      9944:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   9945: 	return 'error: no such course';
                   9946:     }
1.271     www      9947: # ----------------------------------------------------------------- Course made
1.516     raeburn  9948: # log existence
1.1029    raeburn  9949:     my $now = time;
1.918     raeburn  9950:     my $newcourse = {
                   9951:                     $udom.'_'.$uname => {
1.921     raeburn  9952:                                      description => $description,
                   9953:                                      inst_code   => $inst_code,
                   9954:                                      owner       => $course_owner,
                   9955:                                      type        => $crstype,
1.1029    raeburn  9956:                                      creator     => $env{'user.name'}.':'.
                   9957:                                                     $env{'user.domain'},
                   9958:                                      created     => $now,
                   9959:                                      context     => $context,
1.918     raeburn  9960:                                                 },
                   9961:                     };
1.921     raeburn  9962:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      9963: # set toplevel url
1.271     www      9964:     my $topurl=$url;
                   9965:     unless ($nonstandard) {
                   9966: # ------------------------------------------ For standard courses, make top url
                   9967:         my $mapurl=&clutter($url);
1.278     www      9968:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 9969:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      9970: <map>
                   9971: <resource id="1" type="start"></resource>
                   9972: <resource id="2" src="$mapurl"></resource>
                   9973: <resource id="3" type="finish"></resource>
                   9974: <link index="1" from="1" to="2"></link>
                   9975: <link index="2" from="2" to="3"></link>
                   9976: </map>
                   9977: ENDINITMAP
                   9978:         $topurl=&declutter(
1.638     albertel 9979:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      9980:                           );
                   9981:     }
                   9982: # ----------------------------------------------------------- Write preferences
1.84      www      9983:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  9984:                      ('description'              => $description,
                   9985:                       'url'                      => $topurl,
                   9986:                       'internal.creator'         => $env{'user.name'}.':'.
                   9987:                                                     $env{'user.domain'},
                   9988:                       'internal.created'         => $now,
                   9989:                       'internal.creationcontext' => $context)
                   9990:                     );
1.84      www      9991:     return '/'.$udom.'/'.$uname;
                   9992: }
                   9993: 
1.1011    raeburn  9994: # ------------------------------------------------------------------- Create ID
                   9995: sub generate_coursenum {
1.1038    raeburn  9996:     my ($udom,$crstype) = @_;
1.1011    raeburn  9997:     my $domdesc = &domain($udom);
                   9998:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  9999:     my $first;
                   10000:     if ($crstype eq 'Community') {
                   10001:         $first = '0';
                   10002:     } else {
                   10003:         $first = int(1+rand(9)); 
                   10004:     } 
                   10005:     my $uname=$first.
1.1011    raeburn  10006:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10007:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10008:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10009: # ----------------------------------------------- Make sure that does not exist
                   10010:     my $uhome=&homeserver($uname,$udom,'true');
                   10011:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  10012:         if ($crstype eq 'Community') {
                   10013:             $first = '0';
                   10014:         } else {
                   10015:             $first = int(1+rand(9));
                   10016:         }
                   10017:         $uname=$first.
1.1011    raeburn  10018:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   10019:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   10020:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   10021:         $uhome=&homeserver($uname,$udom,'true');
                   10022:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   10023:             return 'error: unable to generate unique course-ID';
                   10024:         }
                   10025:     }
                   10026:     return $uname;
                   10027: }
                   10028: 
1.813     albertel 10029: sub is_course {
1.1167    droeschl 10030:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   10031:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   10032: 
                   10033:     return unless $cdom and $cnum;
                   10034: 
                   10035:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   10036:         '.');
                   10037: 
1.1219    raeburn  10038:     return unless(exists($courses{$cdom.'_'.$cnum}));
1.1167    droeschl 10039:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 10040: }
                   10041: 
1.1015    raeburn  10042: sub store_userdata {
                   10043:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  10044:     my $result;
1.1016    raeburn  10045:     if ($datakey ne '') {
1.1013    raeburn  10046:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  10047:             if ($udom eq '' || $uname eq '') {
                   10048:                 $udom = $env{'user.domain'};
                   10049:                 $uname = $env{'user.name'};
                   10050:             }
                   10051:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  10052:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   10053:                 $result = 'error: no_host';
                   10054:             } else {
                   10055:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   10056:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   10057: 
                   10058:                 my $namevalue='';
                   10059:                 foreach my $key (keys(%{$storehash})) {
                   10060:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   10061:                 }
                   10062:                 $namevalue=~s/\&$//;
1.1224    raeburn  10063:                 unless ($namespace eq 'courserequests') {
                   10064:                     $datakey = &escape($datakey);
                   10065:                 }
1.1105    raeburn  10066:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   10067:                                   $namevalue,$uhome);
1.1013    raeburn  10068:             }
                   10069:         } else {
                   10070:             $result = 'error: data to store was not a hash reference'; 
                   10071:         }
                   10072:     } else {
                   10073:         $result= 'error: invalid requestkey'; 
                   10074:     }
                   10075:     return $result;
                   10076: }
                   10077: 
1.21      www      10078: # ---------------------------------------------------------- Assign Custom Role
                   10079: 
                   10080: sub assigncustomrole {
1.957     raeburn  10081:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10082:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  10083:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      10084: }
                   10085: 
                   10086: # ----------------------------------------------------------------- Revoke Role
                   10087: 
                   10088: sub revokerole {
1.957     raeburn  10089:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10090:     my $now=time;
1.965     raeburn  10091:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      10092: }
                   10093: 
                   10094: # ---------------------------------------------------------- Revoke Custom Role
                   10095: 
                   10096: sub revokecustomrole {
1.957     raeburn  10097:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      10098:     my $now=time;
1.357     www      10099:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  10100:            $deleteflag,$selfenroll,$context);
1.17      www      10101: }
                   10102: 
1.533     banghart 10103: # ------------------------------------------------------------ Disk usage
1.535     albertel 10104: sub diskusage {
1.955     raeburn  10105:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   10106:     $directorypath =~ s/\/$//;
                   10107:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   10108:                        .&escape($getpropath).':'.&escape($uname).':'
                   10109:                        .&escape($udom),homeserver($uname,$udom));
                   10110:     if ($listing eq 'unknown_cmd') {
                   10111:         if ($getpropath) {
                   10112:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   10113:         }
                   10114:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   10115:     }
1.514     albertel 10116:     return $listing;
1.512     banghart 10117: }
                   10118: 
1.566     banghart 10119: sub is_locked {
1.1096    raeburn  10120:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 10121:     my @check;
                   10122:     my $is_locked;
1.1093    raeburn  10123:     push (@check,$file_name);
1.613     albertel 10124:     my %locked = &get('file_permissions',\@check,
1.620     albertel 10125: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 10126:     my ($tmp)=keys(%locked);
                   10127:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  10128:     
1.566     banghart 10129:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  10130:         $is_locked = 'false';
                   10131:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  10132:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  10133:                $is_locked = 'true';
1.1096    raeburn  10134:                if (ref($which) eq 'ARRAY') {
                   10135:                    push(@{$which},$entry);
                   10136:                } else {
                   10137:                    last;
                   10138:                }
1.745     raeburn  10139:            }
                   10140:        }
1.566     banghart 10141:     } else {
                   10142:         $is_locked = 'false';
                   10143:     }
1.1093    raeburn  10144:     return $is_locked;
1.566     banghart 10145: }
                   10146: 
1.759     albertel 10147: sub declutter_portfile {
                   10148:     my ($file) = @_;
1.833     albertel 10149:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 10150:     return $file;
                   10151: }
                   10152: 
1.559     banghart 10153: # ------------------------------------------------------------- Mark as Read Only
                   10154: 
                   10155: sub mark_as_readonly {
                   10156:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 10157:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10158:     my ($tmp)=keys(%current_permissions);
                   10159:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 10160:     foreach my $file (@{$files}) {
1.759     albertel 10161: 	$file = &declutter_portfile($file);
1.561     banghart 10162:         push(@{$current_permissions{$file}},$what);
1.559     banghart 10163:     }
1.613     albertel 10164:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10165:     return;
                   10166: }
                   10167: 
1.572     banghart 10168: # ------------------------------------------------------------Save Selected Files
                   10169: 
                   10170: sub save_selected_files {
                   10171:     my ($user, $path, @files) = @_;
                   10172:     my $filename = $user."savedfiles";
1.573     banghart 10173:     my @other_files = &files_not_in_path($user, $path);
1.1359    raeburn  10174:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.573     banghart 10175:     foreach my $file (@files) {
1.620     albertel 10176:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 10177:     }
                   10178:     foreach my $file (@other_files) {
1.574     banghart 10179:         print (OUT $file."\n");
1.572     banghart 10180:     }
1.574     banghart 10181:     close (OUT);
1.572     banghart 10182:     return 'ok';
                   10183: }
                   10184: 
1.574     banghart 10185: sub clear_selected_files {
                   10186:     my ($user) = @_;
                   10187:     my $filename = $user."savedfiles";
1.1359    raeburn  10188:     open (OUT,'>',LONCAPA::tempdir().$filename);
1.574     banghart 10189:     print (OUT undef);
                   10190:     close (OUT);
                   10191:     return ("ok");    
                   10192: }
                   10193: 
1.572     banghart 10194: sub files_in_path {
                   10195:     my ($user, $path) = @_;
                   10196:     my $filename = $user."savedfiles";
                   10197:     my %return_files;
1.1359    raeburn  10198:     open (IN,'<',LONCAPA::tempdir().$filename);
1.573     banghart 10199:     while (my $line_in = <IN>) {
1.574     banghart 10200:         chomp ($line_in);
                   10201:         my @paths_and_file = split (m!/!, $line_in);
                   10202:         my $file_part = pop (@paths_and_file);
                   10203:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 10204:         $path_part.='/';
                   10205:         my $path_and_file = $path_part.$file_part;
                   10206:         if ($path_part eq $path) {
                   10207:             $return_files{$file_part}= 'selected';
                   10208:         }
                   10209:     }
1.574     banghart 10210:     close (IN);
                   10211:     return (\%return_files);
1.572     banghart 10212: }
                   10213: 
                   10214: # called in portfolio select mode, to show files selected NOT in current directory
                   10215: sub files_not_in_path {
                   10216:     my ($user, $path) = @_;
                   10217:     my $filename = $user."savedfiles";
                   10218:     my @return_files;
                   10219:     my $path_part;
1.1359    raeburn  10220:     open(IN, '<',LONCAPA::tempdir().$filename);
1.800     albertel 10221:     while (my $line = <IN>) {
1.572     banghart 10222:         #ok, I know it's clunky, but I want it to work
1.800     albertel 10223:         my @paths_and_file = split(m|/|, $line);
                   10224:         my $file_part = pop(@paths_and_file);
                   10225:         chomp($file_part);
                   10226:         my $path_part = join('/', @paths_and_file);
1.572     banghart 10227:         $path_part .= '/';
                   10228:         my $path_and_file = $path_part.$file_part;
                   10229:         if ($path_part ne $path) {
1.800     albertel 10230:             push(@return_files, ($path_and_file));
1.572     banghart 10231:         }
                   10232:     }
1.800     albertel 10233:     close(OUT);
1.574     banghart 10234:     return (@return_files);
1.572     banghart 10235: }
                   10236: 
1.1273    raeburn  10237: #------------------------------Submitted/Handedback Portfolio Files Versioning
                   10238:  
                   10239: sub portfiles_versioning {
                   10240:     my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
                   10241:     my $portfolio_root = '/userfiles/portfolio';
                   10242:     return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
                   10243:     foreach my $file (@{$portfiles}) {
                   10244:         &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
                   10245:         my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
                   10246:         my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
                   10247:         my $getpropath = 1;
                   10248:         my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
                   10249:                                              $stu_name,$getpropath);
                   10250:         my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
                   10251:         my $new_answer = 
                   10252:             &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
                   10253:         if ($new_answer ne 'problem getting file') {
                   10254:             push(@{$versioned_portfiles}, $directory.$new_answer);
                   10255:             &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
                   10256:                               [$symb,$env{'request.course.id'},'graded']);
                   10257:         }
                   10258:     }
                   10259: }
                   10260: 
                   10261: sub get_next_version {
                   10262:     my ($answer_name, $answer_ext, $dir_list) = @_;
                   10263:     my $version;
                   10264:     if (ref($dir_list) eq 'ARRAY') {
                   10265:         foreach my $row (@{$dir_list}) {
                   10266:             my ($file) = split(/\&/,$row,2);
                   10267:             my ($file_name,$file_version,$file_ext) =
                   10268:                 &file_name_version_ext($file);
                   10269:             if (($file_name eq $answer_name) &&
                   10270:                 ($file_ext eq $answer_ext)) {
                   10271:                      # gets here if filename and extension match,
                   10272:                      # regardless of version
                   10273:                 if ($file_version ne '') {
                   10274:                     # a versioned file is found  so save it for later
                   10275:                     if ($file_version > $version) {
                   10276:                         $version = $file_version;
                   10277:                     }
                   10278:                 }
                   10279:             }
                   10280:         }
                   10281:     }
                   10282:     $version ++;
                   10283:     return($version);
                   10284: }
                   10285: 
                   10286: sub version_selected_portfile {
                   10287:     my ($domain,$stu_name,$directory,$file_name,$version) = @_;
                   10288:     my ($answer_name,$answer_ver,$answer_ext) =
                   10289:         &file_name_version_ext($file_name);
                   10290:     my $new_answer;
                   10291:     $env{'form.copy'} =
                   10292:         &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
                   10293:     if($env{'form.copy'} eq '-1') {
                   10294:         $new_answer = 'problem getting file';
                   10295:     } else {
                   10296:         $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
                   10297:         my $copy_result = 
                   10298:             &finishuserfileupload($stu_name,$domain,'copy',
                   10299:                                   '/portfolio'.$directory.$new_answer);
                   10300:     }
                   10301:     undef($env{'form.copy'});
                   10302:     return ($new_answer);
                   10303: }
                   10304: 
                   10305: sub file_name_version_ext {
                   10306:     my ($file)=@_;
                   10307:     my @file_parts = split(/\./, $file);
                   10308:     my ($name,$version,$ext);
                   10309:     if (@file_parts > 1) {
                   10310:         $ext=pop(@file_parts);
                   10311:         if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
                   10312:             $version=pop(@file_parts);
                   10313:         }
                   10314:         $name=join('.',@file_parts);
                   10315:     } else {
                   10316:         $name=join('.',@file_parts);
                   10317:     }
                   10318:     return($name,$version,$ext);
                   10319: }
                   10320: 
1.745     raeburn  10321: #----------------------------------------------Get portfolio file permissions
1.629     banghart 10322: 
1.745     raeburn  10323: sub get_portfile_permissions {
                   10324:     my ($domain,$user) = @_;
1.613     albertel 10325:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 10326:     my ($tmp)=keys(%current_permissions);
                   10327:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10328:     return \%current_permissions;
                   10329: }
                   10330: 
                   10331: #---------------------------------------------Get portfolio file access controls
                   10332: 
1.749     raeburn  10333: sub get_access_controls {
1.745     raeburn  10334:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 10335:     my %access;
                   10336:     my $real_file = $file;
                   10337:     $file =~ s/\.meta$//;
1.745     raeburn  10338:     if (defined($file)) {
1.749     raeburn  10339:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   10340:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 10341:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  10342:             }
                   10343:         }
1.745     raeburn  10344:     } else {
1.749     raeburn  10345:         foreach my $key (keys(%{$current_permissions})) {
                   10346:             if ($key =~ /\0accesscontrol$/) {
                   10347:                 if (defined($group)) {
                   10348:                     if ($key !~ m-^\Q$group\E/-) {
                   10349:                         next;
                   10350:                     }
                   10351:                 }
                   10352:                 my ($fullpath) = split(/\0/,$key);
                   10353:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   10354:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   10355:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   10356:                     }
                   10357:                 }
                   10358:             }
                   10359:         }
                   10360:     }
                   10361:     return %access;
                   10362: }
                   10363: 
                   10364: sub modify_access_controls {
                   10365:     my ($file_name,$changes,$domain,$user)=@_;
                   10366:     my ($outcome,$deloutcome);
                   10367:     my %store_permissions;
                   10368:     my %new_values;
                   10369:     my %new_control;
                   10370:     my %translation;
                   10371:     my @deletions = ();
                   10372:     my $now = time;
                   10373:     if (exists($$changes{'activate'})) {
                   10374:         if (ref($$changes{'activate'}) eq 'HASH') {
                   10375:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   10376:             my $numnew = scalar(@newitems);
                   10377:             for (my $i=0; $i<$numnew; $i++) {
                   10378:                 my $newkey = $newitems[$i];
                   10379:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  10380:                 if ($newkey =~ /^\d+:/) { 
                   10381:                     $newkey =~ s/^(\d+)/$newid/;
                   10382:                     $translation{$1} = $newid;
                   10383:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   10384:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   10385:                     $translation{$1} = $newid;
                   10386:                 }
1.749     raeburn  10387:                 $new_values{$file_name."\0".$newkey} = 
                   10388:                                           $$changes{'activate'}{$newitems[$i]};
                   10389:                 $new_control{$newkey} = $now;
                   10390:             }
                   10391:         }
                   10392:     }
                   10393:     my %todelete;
                   10394:     my %changed_items;
                   10395:     foreach my $action ('delete','update') {
                   10396:         if (exists($$changes{$action})) {
                   10397:             if (ref($$changes{$action}) eq 'HASH') {
                   10398:                 foreach my $key (keys(%{$$changes{$action}})) {
                   10399:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   10400:                     if ($action eq 'delete') { 
                   10401:                         $todelete{$itemnum} = 1;
                   10402:                     } else {
                   10403:                         $changed_items{$itemnum} = $key;
                   10404:                     }
                   10405:                 }
1.745     raeburn  10406:             }
                   10407:         }
1.749     raeburn  10408:     }
                   10409:     # get lock on access controls for file.
                   10410:     my $lockhash = {
                   10411:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   10412:                                                        ':'.$env{'user.domain'},
                   10413:                    }; 
                   10414:     my $tries = 0;
                   10415:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10416:    
1.1288    damieng  10417:     while (($gotlock ne 'ok') && $tries < 10) {
1.749     raeburn  10418:         $tries ++;
1.1289    damieng  10419:         sleep(0.1);
1.749     raeburn  10420:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   10421:     }
                   10422:     if ($gotlock eq 'ok') {
                   10423:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   10424:         my ($tmp)=keys(%curr_permissions);
                   10425:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   10426:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   10427:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   10428:             if (ref($curr_controls) eq 'HASH') {
                   10429:                 foreach my $control_item (keys(%{$curr_controls})) {
                   10430:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   10431:                     if (defined($todelete{$itemnum})) {
                   10432:                         push(@deletions,$file_name."\0".$control_item);
                   10433:                     } else {
                   10434:                         if (defined($changed_items{$itemnum})) {
                   10435:                             $new_control{$changed_items{$itemnum}} = $now;
                   10436:                             push(@deletions,$file_name."\0".$control_item);
                   10437:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   10438:                         } else {
                   10439:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   10440:                         }
                   10441:                     }
1.745     raeburn  10442:                 }
                   10443:             }
                   10444:         }
1.970     raeburn  10445:         my ($group);
                   10446:         if (&is_course($domain,$user)) {
                   10447:             ($group,my $file) = split(/\//,$file_name,2);
                   10448:         }
1.749     raeburn  10449:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   10450:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   10451:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   10452:         #  remove lock
                   10453:         my @del_lock = ($file_name."\0".'locked_access_records');
                   10454:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  10455:         my $sqlresult =
1.970     raeburn  10456:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  10457:                                     $group);
1.749     raeburn  10458:     } else {
                   10459:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  10460:     }
1.749     raeburn  10461:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  10462: }
                   10463: 
1.827     raeburn  10464: sub make_public_indefinitely {
1.1271    raeburn  10465:     my (@requrl) = @_;
                   10466:     return &automated_portfile_access('public',\@requrl);
                   10467: }
                   10468: 
                   10469: sub automated_portfile_access {
                   10470:     my ($accesstype,$addsref,$delsref,$info) = @_;
1.1273    raeburn  10471:     unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
                   10472:         return 'invalid';
                   10473:     }
1.1271    raeburn  10474:     my %urls;
                   10475:     if (ref($addsref) eq 'ARRAY') {
                   10476:         foreach my $requrl (@{$addsref}) {
                   10477:             if (&is_portfolio_url($requrl)) {
                   10478:                 unless (exists($urls{$requrl})) {
                   10479:                     $urls{$requrl} = 'add';
                   10480:                 }
                   10481:             }
                   10482:         }
                   10483:     }
                   10484:     if (ref($delsref) eq 'ARRAY') {
                   10485:         foreach my $requrl (@{$delsref}) { 
                   10486:             if (&is_portfolio_url($requrl)) {
                   10487:                 unless (exists($urls{$requrl})) {
                   10488:                     $urls{$requrl} = 'delete'; 
                   10489:                 }
                   10490:             }
                   10491:         }
                   10492:     }
                   10493:     unless (keys(%urls)) {
                   10494:         return 'invalid';
                   10495:     }
                   10496:     my $ip;
                   10497:     if ($accesstype eq 'ip') {
                   10498:         if (ref($info) eq 'HASH') {
                   10499:             if ($info->{'ip'} ne '') {
                   10500:                 $ip = $info->{'ip'};
                   10501:             }
                   10502:         }
                   10503:         if ($ip eq '') {
                   10504:             return 'invalid';
                   10505:         }
                   10506:     }
                   10507:     my $errors;
1.827     raeburn  10508:     my $now = time;
1.1271    raeburn  10509:     my %current_perms;
                   10510:     foreach my $requrl (sort(keys(%urls))) {
                   10511:         my $action;
                   10512:         if ($urls{$requrl} eq 'add') {
                   10513:             $action = 'activate';
                   10514:         } else {
                   10515:             $action = 'none';
                   10516:         }
                   10517:         my $aclnum = 0;
1.827     raeburn  10518:         my (undef,$udom,$unum,$file_name,$group) =
                   10519:             &parse_portfolio_url($requrl);
1.1271    raeburn  10520:         unless (exists($current_perms{$unum.':'.$udom})) {
                   10521:             $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
                   10522:         }
                   10523:         my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
1.827     raeburn  10524:                                                    $group,$file_name);
                   10525:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   10526:             my ($num,$scope,$end,$start) = 
                   10527:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
1.1271    raeburn  10528:             if ($scope eq $accesstype) {
                   10529:                 if (($start <= $now) && ($end == 0)) {
                   10530:                     if ($accesstype eq 'ip') {
                   10531:                         if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
                   10532:                             if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
                   10533:                                 if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
                   10534:                                     if ($urls{$requrl} eq 'add') {
                   10535:                                         $action = 'none';
                   10536:                                         last;
                   10537:                                     } else {
                   10538:                                         $action = 'delete';
                   10539:                                         $aclnum = $num;
                   10540:                                         last;
                   10541:                                     }
                   10542:                                 }
                   10543:                             }
                   10544:                         }
                   10545:                     } elsif ($accesstype eq 'public') {
                   10546:                         if ($urls{$requrl} eq 'add') {
                   10547:                             $action = 'none';
                   10548:                             last;
                   10549:                         } else {
                   10550:                             $action = 'delete';
                   10551:                             $aclnum = $num;
                   10552:                             last;
                   10553:                         }
                   10554:                     }
                   10555:                 } elsif ($accesstype eq 'public') {
1.827     raeburn  10556:                     $action = 'update';
                   10557:                     $aclnum = $num;
1.1271    raeburn  10558:                     last;
1.827     raeburn  10559:                 }
                   10560:             }
                   10561:         }
                   10562:         if ($action eq 'none') {
1.1271    raeburn  10563:             next;
1.827     raeburn  10564:         } else {
                   10565:             my %changes;
                   10566:             my $newend = 0;
                   10567:             my $newstart = $now;
1.1271    raeburn  10568:             my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
1.827     raeburn  10569:             $changes{$action}{$newkey} = {
1.1271    raeburn  10570:                 type => $accesstype,
1.827     raeburn  10571:                 time => {
                   10572:                     start => $newstart,
                   10573:                     end   => $newend,
                   10574:                 },
                   10575:             };
1.1271    raeburn  10576:             if ($accesstype eq 'ip') {
                   10577:                 $changes{$action}{$newkey}{'ip'} = [$ip];
                   10578:             }
1.827     raeburn  10579:             my ($outcome,$deloutcome,$new_values,$translation) =
                   10580:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
1.1271    raeburn  10581:             unless ($outcome eq 'ok') {
                   10582:                 $errors .= $outcome.' ';
                   10583:             }
1.827     raeburn  10584:         }
1.1271    raeburn  10585:     }
                   10586:     if ($errors) {
                   10587:         $errors =~ s/\s$//;
                   10588:         return $errors;
1.827     raeburn  10589:     } else {
1.1271    raeburn  10590:         return 'ok';
1.827     raeburn  10591:     }
                   10592: }
                   10593: 
1.745     raeburn  10594: #------------------------------------------------------Get Marked as Read Only
                   10595: 
                   10596: sub get_marked_as_readonly {
                   10597:     my ($domain,$user,$what,$group) = @_;
                   10598:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 10599:     my @readonly_files;
1.629     banghart 10600:     my $cmp1=$what;
                   10601:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  10602:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10603:         if (defined($group)) {
                   10604:             if ($file_name !~ m-^\Q$group\E/-) {
                   10605:                 next;
                   10606:             }
                   10607:         }
1.561     banghart 10608:         if (ref($value) eq "ARRAY"){
                   10609:             foreach my $stored_what (@{$value}) {
1.629     banghart 10610:                 my $cmp2=$stored_what;
1.759     albertel 10611:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  10612:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  10613:                 }
1.629     banghart 10614:                 if ($cmp1 eq $cmp2) {
1.561     banghart 10615:                     push(@readonly_files, $file_name);
1.745     raeburn  10616:                     last;
1.563     banghart 10617:                 } elsif (!defined($what)) {
                   10618:                     push(@readonly_files, $file_name);
1.745     raeburn  10619:                     last;
1.561     banghart 10620:                 }
                   10621:             }
1.745     raeburn  10622:         }
1.561     banghart 10623:     }
                   10624:     return @readonly_files;
                   10625: }
1.577     banghart 10626: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 10627: 
1.577     banghart 10628: sub get_marked_as_readonly_hash {
1.745     raeburn  10629:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 10630:     my %readonly_files;
1.745     raeburn  10631:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   10632:         if (defined($group)) {
                   10633:             if ($file_name !~ m-^\Q$group\E/-) {
                   10634:                 next;
                   10635:             }
                   10636:         }
1.577     banghart 10637:         if (ref($value) eq "ARRAY"){
                   10638:             foreach my $stored_what (@{$value}) {
1.745     raeburn  10639:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 10640:                     foreach my $lock_descriptor(@{$stored_what}) {
                   10641:                         if ($lock_descriptor eq 'graded') {
                   10642:                             $readonly_files{$file_name} = 'graded';
                   10643:                         } elsif ($lock_descriptor eq 'handback') {
                   10644:                             $readonly_files{$file_name} = 'handback';
                   10645:                         } else {
                   10646:                             if (!exists($readonly_files{$file_name})) {
                   10647:                                 $readonly_files{$file_name} = 'locked';
                   10648:                             }
                   10649:                         }
1.745     raeburn  10650:                     }
1.750     banghart 10651:                 } 
1.577     banghart 10652:             }
                   10653:         } 
                   10654:     }
                   10655:     return %readonly_files;
                   10656: }
1.559     banghart 10657: # ------------------------------------------------------------ Unmark as Read Only
                   10658: 
                   10659: sub unmark_as_readonly {
1.629     banghart 10660:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   10661:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  10662:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 10663:     $file_name = &declutter_portfile($file_name);
1.634     albertel 10664:     my $symb_crs = $what;
                   10665:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  10666:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 10667:     my ($tmp)=keys(%current_permissions);
                   10668:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  10669:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 10670:     foreach my $file (@readonly_files) {
1.759     albertel 10671: 	my $clean_file = &declutter_portfile($file);
                   10672: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 10673: 	my $current_locks = $current_permissions{$file};
1.563     banghart 10674:         my @new_locks;
                   10675:         my @del_keys;
                   10676:         if (ref($current_locks) eq "ARRAY"){
                   10677:             foreach my $locker (@{$current_locks}) {
1.632     albertel 10678:                 my $compare=$locker;
1.749     raeburn  10679:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  10680:                     $compare=join('',@{$locker});
1.746     raeburn  10681:                     if ($compare ne $symb_crs) {
                   10682:                         push(@new_locks, $locker);
                   10683:                     }
1.563     banghart 10684:                 }
                   10685:             }
1.650     albertel 10686:             if (scalar(@new_locks) > 0) {
1.563     banghart 10687:                 $current_permissions{$file} = \@new_locks;
                   10688:             } else {
                   10689:                 push(@del_keys, $file);
1.613     albertel 10690:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 10691:                 delete($current_permissions{$file});
1.563     banghart 10692:             }
                   10693:         }
1.561     banghart 10694:     }
1.613     albertel 10695:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 10696:     return;
                   10697: }
1.512     banghart 10698: 
1.17      www      10699: # ------------------------------------------------------------ Directory lister
                   10700: 
                   10701: sub dirlist {
1.955     raeburn  10702:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      10703:     $uri=~s/^\///;
                   10704:     $uri=~s/\/$//;
1.253     stredwic 10705:     my ($udom, $uname);
1.955     raeburn  10706:     if ($getuserdir) {
1.253     stredwic 10707:         $udom = $userdomain;
                   10708:         $uname = $username;
1.955     raeburn  10709:     } else {
                   10710:         (undef,$udom,$uname)=split(/\//,$uri);
                   10711:         if(defined($userdomain)) {
                   10712:             $udom = $userdomain;
                   10713:         }
                   10714:         if(defined($username)) {
                   10715:             $uname = $username;
                   10716:         }
1.253     stredwic 10717:     }
1.955     raeburn  10718:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 10719: 
1.955     raeburn  10720:     $dirRoot = $perlvar{'lonDocRoot'};
                   10721:     if (defined($getpropath)) {
                   10722:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 10723:         $dirRoot =~ s/\/$//;
1.955     raeburn  10724:     } elsif (defined($getuserdir)) {
                   10725:         my $subdir=$uname.'__';
                   10726:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   10727:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   10728:                    ."/$udom/$subdir/$uname";
                   10729:     } elsif (defined($alternateRoot)) {
                   10730:         $dirRoot = $alternateRoot;
1.751     banghart 10731:     }
1.253     stredwic 10732: 
                   10733:     if($udom) {
                   10734:         if($uname) {
1.1135    raeburn  10735:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  10736:             if ($uhome eq 'no_host') {
                   10737:                 return ([],'no_host');
                   10738:             }
1.955     raeburn  10739:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  10740:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  10741:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  10742:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10743:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  10744:             } else {
                   10745:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10746:             }
1.605     matthew  10747:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  10748:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  10749:                 @listing_results = split(/:/,$listing);
                   10750:             } else {
                   10751:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10752:             }
1.1135    raeburn  10753:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  10754:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10755:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10756:                 return ([],$listing);
                   10757:             } else {
                   10758:                 return (\@listing_results);
1.1135    raeburn  10759:             }
1.955     raeburn  10760:         } elsif(!$alternateRoot) {
1.1136    raeburn  10761:             my (%allusers,%listerror);
1.841     albertel 10762: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  10763:  	    foreach my $tryserver (keys(%servers)) {
                   10764:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   10765:                                   &escape($udom),$tryserver);
                   10766:                 if ($listing eq 'unknown_cmd') {
                   10767: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10768: 				      $udom, $tryserver);
                   10769:                 } else {
                   10770:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   10771:                 }
1.841     albertel 10772: 		if ($listing eq 'unknown_cmd') {
                   10773: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   10774: 				      $udom, $tryserver);
                   10775: 		    @listing_results = split(/:/,$listing);
                   10776: 		} else {
                   10777: 		    @listing_results =
                   10778: 			map { &unescape($_); } split(/:/,$listing);
                   10779: 		}
1.1136    raeburn  10780:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   10781:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   10782:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   10783:                     $listerror{$tryserver} = $listing;
                   10784:                 } else {
1.841     albertel 10785: 		    foreach my $line (@listing_results) {
                   10786: 			my ($entry) = split(/&/,$line,2);
                   10787: 			$allusers{$entry} = 1;
                   10788: 		    }
                   10789: 		}
1.253     stredwic 10790:             }
1.1136    raeburn  10791:             my @alluserslist=();
1.800     albertel 10792:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  10793:                 push(@alluserslist,$user.'&user');
1.253     stredwic 10794:             }
1.1318    droeschl 10795: 
                   10796:             if (!%listerror) {
                   10797:                 # no errors
                   10798:                 return (\@alluserslist);
                   10799:             } elsif (scalar(keys(%servers)) == 1) {
                   10800:                 # one library server, one error 
                   10801:                 my ($key) = keys(%listerror);
                   10802:                 return (\@alluserslist, $listerror{$key});
                   10803:             } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
                   10804:                 # con_lost indicates that we might miss data from at least one
                   10805:                 # library server
                   10806:                 return (\@alluserslist, 'con_lost');
                   10807:             } else {
                   10808:                 # multiple library servers and no con_lost -> data should be
                   10809:                 # complete. 
                   10810:                 return (\@alluserslist);
                   10811:             }
                   10812: 
1.253     stredwic 10813:         } else {
1.1136    raeburn  10814:             return ([],'missing username');
1.253     stredwic 10815:         }
1.955     raeburn  10816:     } elsif(!defined($getpropath)) {
1.1136    raeburn  10817:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   10818:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   10819:         return (\@all_domains);
1.955     raeburn  10820:     } else {
1.1136    raeburn  10821:         return ([],'missing domain');
1.275     stredwic 10822:     }
                   10823: }
                   10824: 
                   10825: # --------------------------------------------- GetFileTimestamp
                   10826: # This function utilizes dirlist and returns the date stamp for
                   10827: # when it was last modified.  It will also return an error of -1
                   10828: # if an error occurs
                   10829: 
                   10830: sub GetFileTimestamp {
1.955     raeburn  10831:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 10832:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   10833:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  10834:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   10835:                                     undef,$getuserdir);
                   10836:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10837:         return -1;
                   10838:     }
                   10839:     if (ref($fileref) eq 'ARRAY') {
                   10840:         my @stats = split('&',$fileref->[0]);
1.375     matthew  10841:         # @stats contains first the filename, then the stat output
                   10842:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 10843:     } else {
                   10844:         return -1;
1.253     stredwic 10845:     }
1.26      www      10846: }
                   10847: 
1.712     albertel 10848: sub stat_file {
                   10849:     my ($uri) = @_;
1.787     albertel 10850:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 10851: 
1.955     raeburn  10852:     my ($udom,$uname,$file);
1.712     albertel 10853:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   10854: 	($udom,$uname,$file) =
1.811     albertel 10855: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 10856: 	$file = 'userfiles/'.$file;
                   10857:     }
                   10858:     if ($uri =~ m-^/res/-) {
                   10859: 	($udom,$uname) = 
1.807     albertel 10860: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 10861: 	$file = $uri;
                   10862:     }
                   10863: 
                   10864:     if (!$udom || !$uname || !$file) {
                   10865: 	# unable to handle the uri
                   10866: 	return ();
                   10867:     }
1.956     raeburn  10868:     my $getpropath;
                   10869:     if ($file =~ /^userfiles\//) {
                   10870:         $getpropath = 1;
                   10871:     }
1.1136    raeburn  10872:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   10873:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   10874:         return ();
                   10875:     } else {
                   10876:         if (ref($listref) eq 'ARRAY') {
                   10877:             my @stats = split('&',$listref->[0]);
                   10878: 	    shift(@stats); #filename is first
                   10879: 	    return @stats;
                   10880:         }
1.712     albertel 10881:     }
                   10882:     return ();
                   10883: }
                   10884: 
1.1313    raeburn  10885: # --------------------------------------------------------- recursedirs
                   10886: # Recursive function to traverse either a specific user's Authoring Space
                   10887: # or corresponding Published Resource Space, and populate the hash ref:
                   10888: # $dirhashref with URLs of all directories, and if $filehashref hash
                   10889: # ref arg is provided, the URLs of any files, excluding versioned, .meta,
                   10890: # or .rights files in resource space, and .meta, .save, .log, and .bak
                   10891: # files in Authoring Space.
                   10892: #
                   10893: # Inputs:
                   10894: #
                   10895: # $is_home - true if current server is home server for user's space
                   10896: # $context - either: priv, or res respectively for Authoring or Resource Space.
                   10897: # $docroot - Document root (i.e., /home/httpd/html
                   10898: # $toppath - Top level directory (i.e., /res/$dom/$uname or /priv/$dom/$uname
                   10899: # $relpath - Current path (relative to top level).
                   10900: # $dirhashref - reference to hash to populate with URLs of directories (Required)
                   10901: # $filehashref - reference to hash to populate with URLs of files (Optional)
                   10902: #
                   10903: # Returns: nothing
                   10904: #
                   10905: # Side Effects: populates $dirhashref, and $filehashref (if provided).
                   10906: #
                   10907: # Currently used by interface/londocs.pm to create linked select boxes for
                   10908: # directory and filename to import a Course "Author" resource into a course, and
                   10909: # also to create linked select boxes for Authoring Space and Directory to choose
                   10910: # save location for creation of a new "standard" problem from the Course Editor.
                   10911: #
                   10912: 
                   10913: sub recursedirs {
                   10914:     my ($is_home,$context,$docroot,$toppath,$relpath,$dirhashref,$filehashref) = @_;
                   10915:     return unless (ref($dirhashref) eq 'HASH');
                   10916:     my $currpath = $docroot.$toppath;
                   10917:     if ($relpath) {
                   10918:         $currpath .= "/$relpath";
                   10919:     }
                   10920:     my $savefile;
                   10921:     if (ref($filehashref)) {
                   10922:         $savefile = 1;
                   10923:     }
                   10924:     if ($is_home) {
                   10925:         if (opendir(my $dirh,$currpath)) {
                   10926:             foreach my $item (sort { lc($a) cmp lc($b) } grep(!/^\.+$/,readdir($dirh))) {
                   10927:                 next if ($item eq '');
                   10928:                 if (-d "$currpath/$item") {
                   10929:                     my $newpath;
                   10930:                     if ($relpath) {
                   10931:                         $newpath = "$relpath/$item";
                   10932:                     } else {
                   10933:                         $newpath = $item;
                   10934:                     }
                   10935:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10936:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10937:                 } elsif ($savefile) {
                   10938:                     if ($context eq 'priv') {
                   10939:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10940:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10941:                         }
                   10942:                     } else {
                   10943:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/) || ($item =~ /\.rights$/)) {
                   10944:                             $filehashref->{&Apache::lonlocal::js_escape($relpath)}{$item} = 1;
                   10945:                         }
                   10946:                     }
                   10947:                 }
                   10948:             }
                   10949:             closedir($dirh);
                   10950:         }
                   10951:     } else {
                   10952:         my ($dirlistref,$listerror) =
                   10953:             &dirlist($toppath.$relpath);
                   10954:         my @dir_lines;
                   10955:         my $dirptr=16384;
                   10956:         if (ref($dirlistref) eq 'ARRAY') {
                   10957:             foreach my $dir_line (sort
                   10958:                               {
                   10959:                                   my ($afile)=split('&',$a,2);
                   10960:                                   my ($bfile)=split('&',$b,2);
                   10961:                                   return (lc($afile) cmp lc($bfile));
                   10962:                               } (@{$dirlistref})) {
                   10963:                 my ($item,$dom,undef,$testdir,undef,undef,undef,undef,$size,undef,$mtime,undef,undef,undef,$obs,undef) =
                   10964:                     split(/\&/,$dir_line,16);
                   10965:                 $item =~ s/\s+$//;
                   10966:                 next if (($item =~ /^\.\.?$/) || ($obs));
                   10967:                 if ($dirptr&$testdir) {
                   10968:                     my $newpath;
                   10969:                     if ($relpath) {
                   10970:                         $newpath = "$relpath/$item";
                   10971:                     } else {
                   10972:                         $relpath = '/';
                   10973:                         $newpath = $item;
                   10974:                     }
                   10975:                     $dirhashref->{&Apache::lonlocal::js_escape($newpath)} = 1;
                   10976:                     &recursedirs($is_home,$context,$docroot,$toppath,$newpath,$dirhashref,$filehashref);
                   10977:                 } elsif ($savefile) {
                   10978:                     if ($context eq 'priv') {
                   10979:                         unless ($item =~ /\.(meta|save|log|bak|DS_Store)$/) {
                   10980:                             $filehashref->{$relpath}{$item} = 1;
                   10981:                         }
                   10982:                     } else {
                   10983:                         unless (($item =~ /\.meta$/) || ($item =~ /\.\d+\.\w+$/)) {
                   10984:                             $filehashref->{$relpath}{$item} = 1;
                   10985:                         }
                   10986:                     }
                   10987:                 }
                   10988:             }
                   10989:         }
                   10990:     }
                   10991:     return;
                   10992: }
                   10993: 
1.26      www      10994: # -------------------------------------------------------- Value of a Condition
                   10995: 
1.713     albertel 10996: # gets the value of a specific preevaluated condition
                   10997: #    stored in the string  $env{user.state.<cid>}
                   10998: # or looks up a condition reference in the bighash and if if hasn't
                   10999: # already been evaluated recurses into docondval to get the value of
                   11000: # the condition, then memoizing it to 
                   11001: #   $env{user.state.<cid>.<condition>}
1.40      www      11002: sub directcondval {
                   11003:     my $number=shift;
1.620     albertel 11004:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 11005: 	&Apache::lonuserstate::evalstate();
                   11006:     }
1.713     albertel 11007:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   11008: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   11009:     } elsif ($number =~ /^_/) {
                   11010: 	my $sub_condition;
                   11011: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   11012: 		&GDBM_READER(),0640)) {
                   11013: 	    $sub_condition=$bighash{'conditions'.$number};
                   11014: 	    untie(%bighash);
                   11015: 	}
                   11016: 	my $value = &docondval($sub_condition);
1.949     raeburn  11017: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 11018: 	return $value;
                   11019:     }
1.620     albertel 11020:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   11021:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      11022:     } else {
                   11023:        return 2;
                   11024:     }
                   11025: }
                   11026: 
1.713     albertel 11027: # get the collection of conditions for this resource
1.26      www      11028: sub condval {
                   11029:     my $condidx=shift;
1.54      www      11030:     my $allpathcond='';
1.713     albertel 11031:     foreach my $cond (split(/\|/,$condidx)) {
                   11032: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   11033: 	    $allpathcond.=
                   11034: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   11035: 	}
1.191     harris41 11036:     }
1.54      www      11037:     $allpathcond=~s/\|$//;
1.713     albertel 11038:     return &docondval($allpathcond);
                   11039: }
                   11040: 
                   11041: #evaluates an expression of conditions
                   11042: sub docondval {
                   11043:     my ($allpathcond) = @_;
                   11044:     my $result=0;
                   11045:     if ($env{'request.course.id'}
                   11046: 	&& defined($allpathcond)) {
                   11047: 	my $operand='|';
                   11048: 	my @stack;
                   11049: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   11050: 	    if ($chunk eq '(') {
                   11051: 		push @stack,($operand,$result);
                   11052: 	    } elsif ($chunk eq ')') {
                   11053: 		my $before=pop @stack;
                   11054: 		if (pop @stack eq '&') {
                   11055: 		    $result=$result>$before?$before:$result;
                   11056: 		} else {
                   11057: 		    $result=$result>$before?$result:$before;
                   11058: 		}
                   11059: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   11060: 		$operand=$chunk;
                   11061: 	    } else {
                   11062: 		my $new=directcondval($chunk);
                   11063: 		if ($operand eq '&') {
                   11064: 		    $result=$result>$new?$new:$result;
                   11065: 		} else {
                   11066: 		    $result=$result>$new?$result:$new;
                   11067: 		}
                   11068: 	    }
                   11069: 	}
1.26      www      11070:     }
                   11071:     return $result;
1.421     albertel 11072: }
                   11073: 
                   11074: # ---------------------------------------------------- Devalidate courseresdata
                   11075: 
                   11076: sub devalidatecourseresdata {
                   11077:     my ($coursenum,$coursedomain)=@_;
                   11078:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11079:     &devalidate_cache_new('courseres',$hashid);
1.28      www      11080: }
                   11081: 
1.763     www      11082: 
1.200     www      11083: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     11084: #
                   11085: #  Parameters:
                   11086: #      $coursenum    - Number of the course.
                   11087: #      $coursedomain - Domain at which the course was created.
                   11088: #  Returns:
                   11089: #     A hash of the course parameters along (I think) with timestamps
                   11090: #     and version info.
1.877     foxr     11091: 
1.624     albertel 11092: sub get_courseresdata {
                   11093:     my ($coursenum,$coursedomain)=@_;
1.200     www      11094:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   11095:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 11096:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 11097:     my %dumpreply;
1.417     albertel 11098:     unless (defined($cached)) {
1.624     albertel 11099: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 11100: 	$result=\%dumpreply;
1.251     albertel 11101: 	my ($tmp) = keys(%dumpreply);
                   11102: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 11103: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 11104: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   11105: 	    return $tmp;
1.416     albertel 11106: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 11107: 	    $result=undef;
1.599     albertel 11108: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 11109: 	}
                   11110:     }
1.624     albertel 11111:     return $result;
                   11112: }
                   11113: 
1.633     albertel 11114: sub devalidateuserresdata {
                   11115:     my ($uname,$udom)=@_;
                   11116:     my $hashid="$udom:$uname";
                   11117:     &devalidate_cache_new('userres',$hashid);
                   11118: }
                   11119: 
1.624     albertel 11120: sub get_userresdata {
                   11121:     my ($uname,$udom)=@_;
                   11122:     #most student don\'t have any data set, check if there is some data
                   11123:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   11124: 
                   11125:     my $hashid="$udom:$uname";
                   11126:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   11127:     if (!defined($cached)) {
                   11128: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   11129: 	$result=\%resourcedata;
                   11130: 	&do_cache_new('userres',$hashid,$result,600);
                   11131:     }
                   11132:     my ($tmp)=keys(%$result);
                   11133:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   11134: 	return $result;
                   11135:     }
                   11136:     #error 2 occurs when the .db doesn't exist
                   11137:     if ($tmp!~/error: 2 /) {
1.1294    raeburn  11138:         if ((!defined($cached)) || ($tmp ne 'con_lost')) {
                   11139: 	    &logthis("<font color=\"blue\">WARNING:".
                   11140: 		     " Trying to get resource data for ".
                   11141: 		     $uname." at ".$udom.": ".
                   11142: 		     $tmp."</font>");
                   11143:         }
1.624     albertel 11144:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 11145: 	#&EXT_cache_set($udom,$uname);
                   11146: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 11147: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 11148:     }
                   11149:     return $tmp;
                   11150: }
1.879     foxr     11151: #----------------------------------------------- resdata - return resource data
                   11152: #  Purpose:
                   11153: #    Return resource data for either users or for a course.
                   11154: #  Parameters:
                   11155: #     $name      - Course/user name.
                   11156: #     $domain    - Name of the domain the user/course is registered on.
1.1311    raeburn  11157: #     $type      - Type of thing $name is (must be 'course' or 'user')
1.1301    raeburn  11158: #     $mapp      - decluttered URL of enclosing map  
                   11159: #     $recursed  - Ref to scalar -- set to 1, if nested maps have been recursed.
                   11160: #     $recurseup - Ref to array of map URLs, starting with map containing
                   11161: #                  $mapp up through hierarchy of nested maps to top level map.  
                   11162: #     $courseid  - CourseID (first part of param identifier).
                   11163: #     $modifier  - Middle part of param identifier.
                   11164: #     $what      - Last part of param identifier.
1.879     foxr     11165: #     @which     - Array of names of resources desired.
                   11166: #  Returns:
                   11167: #     The value of the first reasource in @which that is found in the
                   11168: #     resource hash.
                   11169: #  Exceptional Conditions:
                   11170: #     If the $type passed in is not valid (not the string 'course' or 
                   11171: #     'user', an undefined  reference is returned.
                   11172: #     If none of the resources are found, an undef is returned
1.624     albertel 11173: sub resdata {
1.1301    raeburn  11174:     my ($name,$domain,$type,$mapp,$recursed,$recurseup,$courseid,
                   11175:         $modifier,$what,@which)=@_;
1.624     albertel 11176:     my $result;
                   11177:     if ($type eq 'course') {
                   11178: 	$result=&get_courseresdata($name,$domain);
                   11179:     } elsif ($type eq 'user') {
                   11180: 	$result=&get_userresdata($name,$domain);
                   11181:     }
                   11182:     if (!ref($result)) { return $result; }    
1.251     albertel 11183:     foreach my $item (@which) {
1.1301    raeburn  11184:         if ($item->[1] eq 'course') {
                   11185:             if ((ref($recurseup) eq 'ARRAY') && (ref($recursed) eq 'SCALAR')) {
                   11186:                 unless ($$recursed) {
1.1302    raeburn  11187:                     @{$recurseup} = &get_map_hierarchy($mapp,$courseid);
1.1301    raeburn  11188:                     $$recursed = 1;
                   11189:                 }
                   11190:                 foreach my $item (@${recurseup}) {
                   11191:                     my $norecursechk=$courseid.$modifier.$item.'___(all).'.$what;
                   11192:                     last if (defined($result->{$norecursechk}));
                   11193:                     my $recursechk=$courseid.$modifier.$item.'___(rec).'.$what;
                   11194:                     if (defined($result->{$recursechk})) { return [$result->{$recursechk},'map']; }
                   11195:                 }
                   11196:             }
                   11197:         }
                   11198:         if (defined($result->{$item->[0]})) {
1.927     albertel 11199: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 11200: 	}
1.250     albertel 11201:     }
1.291     albertel 11202:     return undef;
1.200     www      11203: }
                   11204: 
1.1360    raeburn  11205: sub get_domain_lti {
                   11206:     my ($cdom,$context) = @_;
                   11207:     my ($name,%lti);
                   11208:     if ($context eq 'consumer') {
                   11209:         $name = 'ltitools';
                   11210:     } elsif ($context eq 'provider') {
                   11211:         $name = 'lti';
                   11212:     } else {
                   11213:         return %lti;
                   11214:     }
                   11215:     my ($result,$cached)=&is_cached_new($name,$cdom);
1.1298    raeburn  11216:     if (defined($cached)) {
                   11217:         if (ref($result) eq 'HASH') {
1.1360    raeburn  11218:             %lti = %{$result};
1.1298    raeburn  11219:         }
                   11220:     } else {
1.1360    raeburn  11221:         my %domconfig = &get_dom('configuration',[$name],$cdom);
                   11222:         if (ref($domconfig{$name}) eq 'HASH') {
                   11223:             %lti = %{$domconfig{$name}};
                   11224:             my %encdomconfig = &get_dom('encconfig',[$name],$cdom);
                   11225:             if (ref($encdomconfig{$name}) eq 'HASH') {
                   11226:                 foreach my $id (keys(%lti)) {
                   11227:                     if (ref($encdomconfig{$name}{$id}) eq 'HASH') {
1.1344    raeburn  11228:                         foreach my $item ('key','secret') {
1.1360    raeburn  11229:                             $lti{$id}{$item} = $encdomconfig{$name}{$id}{$item};
1.1344    raeburn  11230:                         }
                   11231:                     }
                   11232:                 }
                   11233:             }
1.1298    raeburn  11234:         }
                   11235:         my $cachetime = 24*60*60;
1.1360    raeburn  11236:         &do_cache_new($name,$cdom,\%lti,$cachetime);
1.1298    raeburn  11237:     }
1.1360    raeburn  11238:     return %lti;
1.1298    raeburn  11239: }
                   11240: 
1.1236    raeburn  11241: sub get_numsuppfiles {
                   11242:     my ($cnum,$cdom,$ignorecache)=@_;
                   11243:     my $hashid=$cnum.':'.$cdom;
                   11244:     my ($suppcount,$cached);
                   11245:     unless ($ignorecache) {
                   11246:         ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
                   11247:     }
                   11248:     unless (defined($cached)) {
                   11249:         my $chome=&homeserver($cnum,$cdom);
                   11250:         unless ($chome eq 'no_host') {
1.1366    raeburn  11251:             ($suppcount,my $supptools,my $errors) = (0,0,0);
1.1236    raeburn  11252:             my $suppmap = 'supplemental.sequence';
1.1366    raeburn  11253:             ($suppcount,$supptools,$errors) =
                   11254:                 &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,
                   11255:                                                          $supptools,$errors);
1.1236    raeburn  11256:         }
                   11257:         &do_cache_new('suppcount',$hashid,$suppcount,600);
                   11258:     }
                   11259:     return $suppcount;
                   11260: }
                   11261: 
1.379     matthew  11262: #
                   11263: # EXT resource caching routines
                   11264: #
                   11265: 
1.1302    raeburn  11266: {
                   11267: # Cache (5 seconds) of map hierarchy for speedup of navmaps display
                   11268: #
                   11269: # The course for which we cache
                   11270: my $cachedmapkey='';
                   11271: # The cached recursive maps for this course
                   11272: my %cachedmaps=();
                   11273: # When this was last done
                   11274: my $cachedmaptime='';
                   11275: 
1.379     matthew  11276: sub clear_EXT_cache_status {
1.383     albertel 11277:     &delenv('cache.EXT.');
1.379     matthew  11278: }
                   11279: 
                   11280: sub EXT_cache_status {
                   11281:     my ($target_domain,$target_user) = @_;
1.383     albertel 11282:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 11283:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  11284:         # We know already the user has no data
                   11285:         return 1;
                   11286:     } else {
                   11287:         return 0;
                   11288:     }
                   11289: }
                   11290: 
                   11291: sub EXT_cache_set {
                   11292:     my ($target_domain,$target_user) = @_;
1.383     albertel 11293:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  11294:     #&appenv({$cachename => time});
1.379     matthew  11295: }
                   11296: 
1.28      www      11297: # --------------------------------------------------------- Value of a Variable
1.58      www      11298: sub EXT {
1.715     albertel 11299: 
1.1228    raeburn  11300:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
1.68      www      11301:     unless ($varname) { return ''; }
1.218     albertel 11302:     #get real user name/domain, courseid and symb
                   11303:     my $courseid;
1.359     albertel 11304:     my $publicuser;
1.427     www      11305:     if ($symbparm) {
                   11306: 	$symbparm=&get_symb_from_alias($symbparm);
                   11307:     }
1.218     albertel 11308:     if (!($uname && $udom)) {
1.790     albertel 11309:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 11310:       if (!$symbparm) {	$symbparm=$cursymb; }
                   11311:     } else {
1.620     albertel 11312: 	$courseid=$env{'request.course.id'};
1.218     albertel 11313:     }
1.48      www      11314:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   11315:     my $rest;
1.320     albertel 11316:     if (defined($therest[0])) {
1.48      www      11317:        $rest=join('.',@therest);
                   11318:     } else {
                   11319:        $rest='';
                   11320:     }
1.320     albertel 11321: 
1.57      www      11322:     my $qualifierrest=$qualifier;
                   11323:     if ($rest) { $qualifierrest.='.'.$rest; }
                   11324:     my $spacequalifierrest=$space;
                   11325:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      11326:     if ($realm eq 'user') {
1.48      www      11327: # --------------------------------------------------------------- user.resource
                   11328: 	if ($space eq 'resource') {
1.651     albertel 11329: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   11330: 		  || defined($Apache::lonhomework::parsing_a_task))
                   11331: 		 &&
1.744     albertel 11332: 		 ($symbparm eq &symbread()) ) {	
                   11333: 		# if we are in the middle of processing the resource the
                   11334: 		# get the value we are planning on committing
                   11335:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   11336:                     return $Apache::lonhomework::results{$qualifierrest};
                   11337:                 } else {
                   11338:                     return $Apache::lonhomework::history{$qualifierrest};
                   11339:                 }
1.335     albertel 11340: 	    } else {
1.359     albertel 11341: 		my %restored;
1.620     albertel 11342: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 11343: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   11344: 		} else {
                   11345: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   11346: 		}
1.335     albertel 11347: 		return $restored{$qualifierrest};
                   11348: 	    }
1.48      www      11349: # ----------------------------------------------------------------- user.access
                   11350:         } elsif ($space eq 'access') {
1.218     albertel 11351: 	    # FIXME - not supporting calls for a specific user
1.48      www      11352:             return &allowed($qualifier,$rest);
                   11353: # ------------------------------------------ user.preferences, user.environment
                   11354:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 11355: 	    if (($uname eq $env{'user.name'}) &&
                   11356: 		($udom eq $env{'user.domain'})) {
                   11357: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 11358: 	    } else {
1.359     albertel 11359: 		my %returnhash;
                   11360: 		if (!$publicuser) {
                   11361: 		    %returnhash=&userenvironment($udom,$uname,
                   11362: 						 $qualifierrest);
                   11363: 		}
1.218     albertel 11364: 		return $returnhash{$qualifierrest};
                   11365: 	    }
1.48      www      11366: # ----------------------------------------------------------------- user.course
                   11367:         } elsif ($space eq 'course') {
1.218     albertel 11368: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11369:             return $env{join('.',('request.course',$qualifier))};
1.48      www      11370: # ------------------------------------------------------------------- user.role
                   11371:         } elsif ($space eq 'role') {
1.218     albertel 11372: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 11373:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      11374:             if ($qualifier eq 'value') {
                   11375: 		return $role;
                   11376:             } elsif ($qualifier eq 'extent') {
                   11377:                 return $where;
                   11378:             }
                   11379: # ----------------------------------------------------------------- user.domain
                   11380:         } elsif ($space eq 'domain') {
1.218     albertel 11381:             return $udom;
1.48      www      11382: # ------------------------------------------------------------------- user.name
                   11383:         } elsif ($space eq 'name') {
1.218     albertel 11384:             return $uname;
1.48      www      11385: # ---------------------------------------------------- Any other user namespace
1.29      www      11386:         } else {
1.359     albertel 11387: 	    my %reply;
                   11388: 	    if (!$publicuser) {
                   11389: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   11390: 	    }
                   11391: 	    return $reply{$qualifierrest};
1.48      www      11392:         }
1.236     www      11393:     } elsif ($realm eq 'query') {
                   11394: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 11395:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   11396: 						[$spacequalifierrest]);
1.620     albertel 11397: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      11398:    } elsif ($realm eq 'request') {
1.48      www      11399: # ------------------------------------------------------------- request.browser
                   11400:         if ($space eq 'browser') {
1.1145    bisitz   11401:             return $env{'browser.'.$qualifier};
1.57      www      11402: # ------------------------------------------------------------ request.filename
                   11403:         } else {
1.620     albertel 11404:             return $env{'request.'.$spacequalifierrest};
1.29      www      11405:         }
1.28      www      11406:     } elsif ($realm eq 'course') {
1.48      www      11407: # ---------------------------------------------------------- course.description
1.620     albertel 11408:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      11409:     } elsif ($realm eq 'resource') {
1.165     www      11410: 
1.620     albertel 11411: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 11412: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   11413: 	}
1.693     albertel 11414: 
1.1232    raeburn  11415:         if ($qualifier eq '') {
                   11416: 	    if ($space eq 'title') {
                   11417: 	        if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   11418: 	        return &gettitle($symbparm);
                   11419: 	    }
1.693     albertel 11420: 	
1.1232    raeburn  11421: 	    if ($space eq 'map') {
                   11422: 	        my ($map) = &decode_symb($symbparm);
                   11423: 	        return &symbread($map);
                   11424: 	    }
                   11425:             if ($space eq 'maptitle') {
                   11426:                 my ($map) = &decode_symb($symbparm);
                   11427:                 return &gettitle($map);
                   11428:             }
                   11429: 	    if ($space eq 'filename') {
                   11430: 	        if ($symbparm) {
                   11431: 		    return &clutter((&decode_symb($symbparm))[2]);
                   11432: 	        }
                   11433: 	        return &hreflocation('',$env{'request.filename'});
1.905     albertel 11434: 	    }
1.1232    raeburn  11435: 
1.1233    raeburn  11436:             if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
                   11437:                 if ($space eq 'visibleparts') {
                   11438:                     my $navmap = Apache::lonnavmaps::navmap->new();
                   11439:                     my $item;
                   11440:                     if (ref($navmap)) {
                   11441:                         my $res = $navmap->getBySymb($symbparm);
                   11442:                         my $parts = $res->parts();
                   11443:                         if (ref($parts) eq 'ARRAY') {
                   11444:                             $item = join(',',@{$parts});
                   11445:                         }
                   11446:                         undef($navmap);
1.1232    raeburn  11447:                     }
1.1233    raeburn  11448:                     return $item;
1.1232    raeburn  11449:                 }
                   11450:             }
                   11451:         }
1.693     albertel 11452: 
1.1301    raeburn  11453: 	my ($section, $group, @groups, @recurseup, $recursed);
                   11454: 	my ($courselevelm,$courseleveli,$courselevel,$mapp);
1.1228    raeburn  11455:         if (($courseid eq '') && ($cid)) {
                   11456:             $courseid = $cid;
                   11457:         }
                   11458: 	if (($symbparm && $courseid) && 
                   11459: 	    (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid)))  {
1.165     www      11460: 
1.218     albertel 11461: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      11462: 
1.60      www      11463: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 11464: 	    my $symbp=$symbparm;
1.1301    raeburn  11465: 	    $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 11466: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
1.1301    raeburn  11467:             my $recurseparm=$mapp.'___(rec).'.$spacequalifierrest;
1.218     albertel 11468: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
1.620     albertel 11469: 	    if (($env{'user.name'} eq $uname) &&
                   11470: 		($env{'user.domain'} eq $udom)) {
                   11471: 		$section=$env{'request.course.sec'};
1.733     raeburn  11472:                 @groups = split(/:/,$env{'request.course.groups'});  
                   11473:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 11474: 	    } else {
1.539     albertel 11475: 		if (! defined($usection)) {
1.551     albertel 11476: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 11477: 		} else {
                   11478: 		    $section = $usection;
                   11479: 		}
1.733     raeburn  11480:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 11481: 	    }
                   11482: 
                   11483: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   11484: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
1.1301    raeburn  11485:             my $secleveli=$courseid.'.['.$section.'].'.$recurseparm;
1.218     albertel 11486: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   11487: 
1.593     albertel 11488: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 11489: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.1301    raeburn  11490:             $courseleveli=$courseid.'.'.$recurseparm;
1.593     albertel 11491: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      11492: 
1.60      www      11493: # ----------------------------------------------------------- first, check user
1.624     albertel 11494: 
1.1301    raeburn  11495: 	    my $userreply=&resdata($uname,$udom,'user',$mapp,\$recursed,
                   11496:                                    \@recurseup,$courseid,'.',$spacequalifierrest, 
1.927     albertel 11497: 				       ([$courselevelr,'resource'],
                   11498: 					[$courselevelm,'map'     ],
1.1301    raeburn  11499:                                         [$courseleveli,'map'     ],
1.927     albertel 11500: 					[$courselevel, 'course'  ]));
1.931     albertel 11501: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      11502: 
1.594     albertel 11503: # ------------------------------------------------ second, check some of course
1.684     raeburn  11504:             my $coursereply;
1.691     raeburn  11505:             if (@groups > 0) {
                   11506:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
1.1301    raeburn  11507:                                        $recurseparm,$mapparm,$spacequalifierrest,
                   11508:                                        $mapp,\$recursed,\@recurseup);
                   11509:                 if (defined($coursereply)) { return &get_reply($coursereply); } 
1.684     raeburn  11510:             }
1.96      www      11511: 
1.684     raeburn  11512: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 11513: 				  $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11514: 				  'course',$mapp,\$recursed,\@recurseup,
                   11515:                                   $courseid,'.['.$section.'].',$spacequalifierrest,
1.927     albertel 11516: 				  ([$seclevelr,   'resource'],
                   11517: 				   [$seclevelm,   'map'     ],
1.1301    raeburn  11518:                                    [$secleveli,   'map'     ],
1.927     albertel 11519: 				   [$seclevel,    'course'  ],
                   11520: 				   [$courselevelr,'resource']));
                   11521: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      11522: 
1.60      www      11523: # ------------------------------------------------------ third, check map parms
1.218     albertel 11524: 	    my %parmhash=();
                   11525: 	    my $thisparm='';
                   11526: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 11527: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 11528: 		    &GDBM_READER(),0640)) {
1.218     albertel 11529: 		$thisparm=$parmhash{$symbparm};
                   11530: 		untie(%parmhash);
                   11531: 	    }
1.927     albertel 11532: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 11533: 	}
1.594     albertel 11534: # ------------------------------------------ fourth, look in resource metadata
1.1301    raeburn  11535:  
                   11536:         my $what = $spacequalifierrest;
                   11537: 	$what=~s/\./\_/;
1.282     albertel 11538: 	my $filename;
                   11539: 	if (!$symbparm) { $symbparm=&symbread(); }
                   11540: 	if ($symbparm) {
1.409     www      11541: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 11542: 	} else {
1.620     albertel 11543: 	    $filename=$env{'request.filename'};
1.282     albertel 11544: 	}
1.1362    raeburn  11545:         my $toolsymb;
                   11546:         if (($filename =~ /ext\.tool$/) && ($what ne '0_gradable')) {
                   11547:             $toolsymb = $symbparm;
                   11548:         }
                   11549: 	my $metadata=&metadata($filename,$what,$toolsymb);
1.927     albertel 11550: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.1362    raeburn  11551: 	$metadata=&metadata($filename,'parameter_'.$what,$toolsymb);
1.927     albertel 11552: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      11553: 
1.1301    raeburn  11554: # ----------------------------------------------- fifth, look in rest of course
1.593     albertel 11555: 	if ($symbparm && defined($courseid) && 
1.620     albertel 11556: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 11557: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   11558: 				     $env{'course.'.$courseid.'.domain'},
1.1301    raeburn  11559: 				     'course',$mapp,\$recursed,\@recurseup,
                   11560:                                      $courseid,'.',$spacequalifierrest,
1.927     albertel 11561: 				     ([$courselevelm,'map'   ],
1.1301    raeburn  11562:                                       [$courseleveli,'map'   ],
1.927     albertel 11563: 				      [$courselevel, 'course']));
                   11564: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 11565: 	}
1.145     www      11566: # ------------------------------------------------------------------ Cascade up
1.218     albertel 11567: 	unless ($space eq '0') {
1.336     albertel 11568: 	    my @parts=split(/_/,$space);
                   11569: 	    my $id=pop(@parts);
                   11570: 	    my $part=join('_',@parts);
                   11571: 	    if ($part eq '') { $part='0'; }
1.927     albertel 11572: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 11573: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  11574: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 11575: 	}
1.395     albertel 11576: 	if ($recurse) { return undef; }
1.1362    raeburn  11577: 	my $pack_def=&packages_tab_default($filename,$varname,$toolsymb);
1.927     albertel 11578: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      11579: # ---------------------------------------------------- Any other user namespace
                   11580:     } elsif ($realm eq 'environment') {
                   11581: # ----------------------------------------------------------------- environment
1.620     albertel 11582: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   11583: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 11584: 	} else {
1.770     albertel 11585: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   11586: 		return '';
                   11587: 	    }
1.219     albertel 11588: 	    my %returnhash=&userenvironment($udom,$uname,
                   11589: 					    $spacequalifierrest);
                   11590: 	    return $returnhash{$spacequalifierrest};
                   11591: 	}
1.28      www      11592:     } elsif ($realm eq 'system') {
1.48      www      11593: # ----------------------------------------------------------------- system.time
                   11594: 	if ($space eq 'time') {
                   11595: 	    return time;
                   11596:         }
1.696     albertel 11597:     } elsif ($realm eq 'server') {
                   11598: # ----------------------------------------------------------------- system.time
                   11599: 	if ($space eq 'name') {
                   11600: 	    return $ENV{'SERVER_NAME'};
                   11601:         }
1.28      www      11602:     }
1.48      www      11603:     return '';
1.61      www      11604: }
                   11605: 
1.927     albertel 11606: sub get_reply {
                   11607:     my ($reply_value) = @_;
1.940     raeburn  11608:     if (ref($reply_value) eq 'ARRAY') {
                   11609:         if (wantarray) {
                   11610: 	    return @$reply_value;
                   11611:         }
                   11612:         return $reply_value->[0];
                   11613:     } else {
                   11614:         return $reply_value;
1.927     albertel 11615:     }
                   11616: }
                   11617: 
1.691     raeburn  11618: sub check_group_parms {
1.1301    raeburn  11619:     my ($courseid,$groups,$symbparm,$recurseparm,$mapparm,$what,$mapp,
                   11620:         $recursed,$recurseupref) = @_;
                   11621:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$recurseparm,'map'],
                   11622:                   [$what,'course']);
                   11623:     my $coursereply;
1.691     raeburn  11624:     foreach my $group (@{$groups}) {
1.1301    raeburn  11625:         my @groupitems = ();
1.691     raeburn  11626:         foreach my $level (@levels) {
1.927     albertel 11627:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   11628:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  11629:         }
1.1301    raeburn  11630:         my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   11631:                                    $env{'course.'.$courseid.'.domain'},
                   11632:                                    'course',$mapp,$recursed,$recurseupref,
                   11633:                                    $courseid,'.['.$group.'].',$what,
                   11634:                                    @groupitems);
                   11635:         last if (defined($coursereply));
1.691     raeburn  11636:     }
                   11637:     return $coursereply;
                   11638: }
                   11639: 
1.1301    raeburn  11640: sub get_map_hierarchy {
1.1302    raeburn  11641:     my ($mapname,$courseid) = @_;
                   11642:     my @recurseup = ();
1.1301    raeburn  11643:     if ($mapname) {
1.1302    raeburn  11644:         if (($cachedmapkey eq $courseid) &&
                   11645:             (abs($cachedmaptime-time)<5)) {
                   11646:             if (ref($cachedmaps{$mapname}) eq 'ARRAY') {
                   11647:                 return @{$cachedmaps{$mapname}};
                   11648:             }
                   11649:         }
1.1301    raeburn  11650:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11651:         if (ref($navmap)) {
                   11652:             @recurseup = $navmap->recurseup_maps($mapname);
                   11653:             undef($navmap);
1.1302    raeburn  11654:             $cachedmaps{$mapname} = \@recurseup;
                   11655:             $cachedmaptime=time;
                   11656:             $cachedmapkey=$courseid;
1.1301    raeburn  11657:         }
                   11658:     }
                   11659:     return @recurseup;
                   11660: }
                   11661: 
1.1302    raeburn  11662: }
                   11663: 
1.691     raeburn  11664: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  11665:     my ($courseid,@groups) = @_;
                   11666:     @groups = sort(@groups);
1.691     raeburn  11667:     return @groups;
                   11668: }
                   11669: 
1.395     albertel 11670: sub packages_tab_default {
1.1362    raeburn  11671:     my ($uri,$varname,$toolsymb)=@_;
1.395     albertel 11672:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 11673: 
                   11674:     my (@extension,@specifics,$do_default);
1.1362    raeburn  11675:     foreach my $package (split(/,/,&metadata($uri,'packages',$toolsymb))) {
1.395     albertel 11676: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 11677: 	if ($pack_type eq 'default') {
                   11678: 	    $do_default=1;
                   11679: 	} elsif ($pack_type eq 'extension') {
                   11680: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 11681: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 11682: 	    # only look at packages defaults for packages that this id is
1.738     albertel 11683: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   11684: 	}
                   11685:     }
                   11686:     # first look for a package that matches the requested part id
                   11687:     foreach my $package (@specifics) {
                   11688: 	my (undef,$pack_type,$pack_part)=@{$package};
                   11689: 	next if ($pack_part ne $part);
                   11690: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11691: 	    return $packagetab{"$pack_type&$name&default"};
                   11692: 	}
                   11693:     }
                   11694:     # look for any possible matching non extension_ package
                   11695:     foreach my $package (@specifics) {
                   11696: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 11697: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11698: 	    return $packagetab{"$pack_type&$name&default"};
                   11699: 	}
1.585     albertel 11700: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 11701: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   11702: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 11703: 	}
                   11704:     }
1.738     albertel 11705:     # look for any posible extension_ match
                   11706:     foreach my $package (@extension) {
                   11707: 	my ($package,$pack_type)=@{$package};
                   11708: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   11709: 	    return $packagetab{"$pack_type&$name&default"};
                   11710: 	}
                   11711: 	if (defined($packagetab{$package."&$name&default"})) {
                   11712: 	    return $packagetab{$package."&$name&default"};
                   11713: 	}
                   11714:     }
                   11715:     # look for a global default setting
                   11716:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   11717: 	return $packagetab{"default&$name&default"};
                   11718:     }
1.395     albertel 11719:     return undef;
                   11720: }
                   11721: 
1.334     albertel 11722: sub add_prefix_and_part {
                   11723:     my ($prefix,$part)=@_;
                   11724:     my $keyroot;
                   11725:     if (defined($prefix) && $prefix !~ /^__/) {
                   11726: 	# prefix that has a part already
                   11727: 	$keyroot=$prefix;
                   11728:     } elsif (defined($prefix)) {
                   11729: 	# prefix that is missing a part
                   11730: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   11731:     } else {
                   11732: 	# no prefix at all
                   11733: 	if (defined($part)) { $keyroot='_'.$part; }
                   11734:     }
                   11735:     return $keyroot;
                   11736: }
                   11737: 
1.71      www      11738: # ---------------------------------------------------------------- Get metadata
                   11739: 
1.599     albertel 11740: my %metaentry;
1.1070    www      11741: my %importedpartids;
1.1369    raeburn  11742: my %importedrespids;
1.71      www      11743: sub metadata {
1.1362    raeburn  11744:     my ($uri,$what,$toolsymb,$liburi,$prefix,$depthcount)=@_;
1.71      www      11745:     $uri=&declutter($uri);
1.288     albertel 11746:     # if it is a non metadata possible uri return quickly
1.529     albertel 11747:     if (($uri eq '') || 
                   11748: 	(($uri =~ m|^/*adm/|) && 
1.1343    raeburn  11749: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard|ext\.tool)$})) ||
1.1108    raeburn  11750:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 11751: 	return undef;
                   11752:     }
1.1261    raeburn  11753:     if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv}) 
1.924     albertel 11754: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 11755: 	return undef;
1.288     albertel 11756:     }
1.73      www      11757:     my $filename=$uri;
                   11758:     $uri=~s/\.meta$//;
1.172     www      11759: #
                   11760: # Is the metadata already cached?
1.177     www      11761: # Look at timestamp of caching
1.172     www      11762: # Everything is cached by the main uri, libraries are never directly cached
                   11763: #
1.428     albertel 11764:     if (!defined($liburi)) {
1.599     albertel 11765: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 11766: 	if (defined($cached)) { return $result->{':'.$what}; }
                   11767:     }
1.1362    raeburn  11768: 
                   11769: #
                   11770: # If the uri is for an external tool the file from
                   11771: # which metadata should be retrieved depends on whether
                   11772: # the tool had been configured to be gradable (set in the Course
                   11773: # Editor or Resource Editor).
                   11774: #
                   11775: # If a valid symb has been included as the third arg in the call
                   11776: # to &metadata() that can be used to retrieve the value of
                   11777: # parameter_0_gradable set for the resource, and included in the
                   11778: # uploaded map containing the tool. The value is retrieved via
                   11779: # &EXT(), if a valid symb is available.  Otherwise the value of
                   11780: # gradable in the exttool_$marker.db file for the tool instance
1.1364    raeburn  11781: # is retrieved via &get().
                   11782: #
                   11783: # When lonuserstate::traceroute() calls lonnet::EXT() for 
                   11784: # hiddenresource and encrypturl (during course initialization)
                   11785: # the map-level parameter for resource.0.gradable included in the 
                   11786: # uploaded map containing the tool will not yet have been stored
                   11787: # in the user_course_parms.db file for the user's session, so in 
                   11788: # this case fall back to retrieving gradable status from the
                   11789: # exttool_$marker.db file.
1.1362    raeburn  11790: #
                   11791: # In order to avoid an infinite loop, &metadata() will return
                   11792: # before a call to &EXT(), if the uri is for an external tool
                   11793: # and the $what for which metadata is being requested is
                   11794: # parameter_0_gradable or 0_gradable.
                   11795: #
                   11796: 
                   11797:     if ($uri =~ /ext\.tool$/) {
                   11798:         if (($what eq 'parameter_0_gradable') || ($what eq '0_gradable')) {
                   11799:             return;
                   11800:         } else {
                   11801:             my ($checked,$use_passback);
                   11802:             if ($toolsymb ne '') {
                   11803:                 (undef,undef,my $tooluri) = &decode_symb($toolsymb);
1.1364    raeburn  11804:                 if (($tooluri eq $uri) && (&EXT('resource.0.gradable',$toolsymb))) {
1.1362    raeburn  11805:                     $checked = 1;
                   11806:                     if (&EXT('resource.0.gradable',$toolsymb) =~ /^yes$/i) {
                   11807:                         $use_passback = 1;
                   11808:                     }
                   11809:                 }
                   11810:             }
                   11811:             unless ($checked) {
                   11812:                 my ($ignore,$cdom,$cnum,$marker) = split(m{/},$uri);
                   11813:                 $marker=~s/\D//g;
1.1363    raeburn  11814:                 if ($marker) {
1.1362    raeburn  11815:                     my %toolsettings=&get('exttool_'.$marker,['gradable'],$cdom,$cnum);
                   11816:                     $use_passback = $toolsettings{'gradable'};
                   11817:                 }
                   11818:             }
                   11819:             if ($use_passback) {
                   11820:                 $filename = '/home/httpd/html/res/lib/templates/LTIpassback.tool';
                   11821:             } else {
                   11822:                 $filename = '/home/httpd/html/res/lib/templates/LTIstandard.tool';
                   11823:             }
                   11824:         }
                   11825:     }
                   11826: 
1.428     albertel 11827:     {
1.1069    www      11828: # Imported parts would go here
1.1369    raeburn  11829:         my @origfiletagids=();
1.1069    www      11830:         my $importedparts=0;
1.1369    raeburn  11831: 
                   11832: # Imported responseids would go here
                   11833:         my $importedresponses=0;
1.172     www      11834: #
                   11835: # Is this a recursive call for a library?
                   11836: #
1.599     albertel 11837: #	if (! exists($metacache{$uri})) {
                   11838: #	    $metacache{$uri}={};
                   11839: #	}
1.924     albertel 11840: 	my $cachetime = 60*60;
1.171     www      11841:         if ($liburi) {
                   11842: 	    $liburi=&declutter($liburi);
                   11843:             $filename=$liburi;
1.401     bowersj2 11844:         } else {
1.599     albertel 11845: 	    &devalidate_cache_new('meta',$uri);
                   11846: 	    undef(%metaentry);
1.401     bowersj2 11847: 	}
1.140     www      11848:         my %metathesekeys=();
1.73      www      11849:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 11850: 	my $metastring;
1.1140    www      11851: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 11852: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 11853: 	    $metastring = 
1.929     albertel 11854: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 11855: 					  ('grade_target' => 'meta'));
                   11856: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  11857: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   11858:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 11859: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 11860: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 11861: 	    $metastring=&getfile($file);
1.489     albertel 11862: 	}
1.208     albertel 11863:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      11864:         my $token;
1.140     www      11865:         undef %metathesekeys;
1.71      www      11866:         while ($token=$parser->get_token) {
1.339     albertel 11867: 	    if ($token->[0] eq 'S') {
                   11868: 		if (defined($token->[2]->{'package'})) {
1.172     www      11869: #
                   11870: # This is a package - get package info
                   11871: #
1.339     albertel 11872: 		    my $package=$token->[2]->{'package'};
                   11873: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   11874: 		    if (defined($token->[2]->{'id'})) { 
                   11875: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   11876: 		    }
1.599     albertel 11877: 		    if ($metaentry{':packages'}) {
                   11878: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 11879: 		    } else {
1.599     albertel 11880: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 11881: 		    }
1.736     albertel 11882: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 11883: 			my $part=$keyroot;
                   11884: 			$part=~s/^\_//;
1.736     albertel 11885: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   11886: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   11887: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 11888: 			    # ignore package.tab specified default values
                   11889:                             # here &package_tab_default() will fetch those
                   11890: 			    if ($subp eq 'default') { next; }
1.736     albertel 11891: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 11892: 			    my $unikey;
                   11893: 			    if ($pack =~ /_0$/) {
                   11894: 				$unikey='parameter_0_'.$name;
                   11895: 				$part=0;
                   11896: 			    } else {
                   11897: 				$unikey='parameter'.$keyroot.'_'.$name;
                   11898: 			    }
1.339     albertel 11899: 			    if ($subp eq 'display') {
                   11900: 				$value.=' [Part: '.$part.']';
                   11901: 			    }
1.599     albertel 11902: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 11903: 			    $metathesekeys{$unikey}=1;
1.599     albertel 11904: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   11905: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 11906: 			    }
1.599     albertel 11907: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   11908: 				$metaentry{':'.$unikey}=
                   11909: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 11910: 			    }
1.339     albertel 11911: 			}
                   11912: 		    }
                   11913: 		} else {
1.172     www      11914: #
                   11915: # This is not a package - some other kind of start tag
1.339     albertel 11916: #
                   11917: 		    my $entry=$token->[1];
1.1068    www      11918: 		    my $unikey='';
1.175     www      11919: 
1.339     albertel 11920: 		    if ($entry eq 'import') {
1.175     www      11921: #
                   11922: # Importing a library here
1.339     albertel 11923: #
1.1067    www      11924:                         my $location=$parser->get_text('/import');
                   11925:                         my $dir=$filename;
                   11926:                         $dir=~s|[^/]*$||;
                   11927:                         $location=&filelocation($dir,$location);
1.1369    raeburn  11928: 
                   11929:                         my $importid=$token->[2]->{'id'};
1.1068    www      11930:                         my $importmode=$token->[2]->{'importmode'};
1.1369    raeburn  11931: #
                   11932: # Check metadata for imported file to
                   11933: # see if it contained response items
                   11934: #
1.1372    raeburn  11935:                         my ($origfile,@libfilekeys);
1.1370    raeburn  11936:                         my %currmetaentry = %metaentry;
1.1372    raeburn  11937:                         @libfilekeys = split(/,/,&metadata($location,'keys',undef,undef,undef,
                   11938:                                                            $depthcount+1));
                   11939:                         if (grep(/^responseorder$/,@libfilekeys)) {
                   11940:                             my $libresponseorder = &metadata($location,'responseorder',undef,undef,
                   11941:                                                              undef,$depthcount+1);
                   11942:                             if ($libresponseorder ne '') {
                   11943:                                 if ($#origfiletagids<0) {
                   11944:                                     undef(%importedrespids);
                   11945:                                     undef(%importedpartids);
                   11946:                                 }
1.1373    raeburn  11947:                                 my @respids = split(/\s*,\s*/,$libresponseorder);
                   11948:                                 if (@respids) {
                   11949:                                     $importedrespids{$importid} = join(',',map { $importid.'_'.$_ } @respids);
                   11950:                                 }
                   11951:                                 if ($importedrespids{$importid} ne '') {
1.1372    raeburn  11952:                                     $importedresponses = 1;
1.1369    raeburn  11953: # We need to get the original file and the imported file to get the response order correct
                   11954: # Load and inspect original file
1.1372    raeburn  11955:                                     if ($#origfiletagids<0) {
                   11956:                                         my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11957:                                         $origfile=&getfile($origfilelocation);
                   11958:                                         @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11959:                                     }
1.1369    raeburn  11960:                                 }
                   11961:                             }
                   11962:                         }
1.1370    raeburn  11963: # Do not overwrite contents of %metaentry hash for resource itself with 
                   11964: # hash populated for imported library file
                   11965:                         %metaentry = %currmetaentry;
                   11966:                         undef(%currmetaentry);
1.1374    raeburn  11967:                         if ($importmode eq 'part') {
1.1068    www      11968: # Import as part(s)
1.1069    www      11969:                            $importedparts=1;
                   11970: # We need to get the original file and the imported file to get the part order correct
                   11971: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
1.1369    raeburn  11972: # Load and inspect original file if we didn't do that already
                   11973:                            if ($#origfiletagids<0) {
                   11974:                                undef(%importedrespids);
                   11975:                                undef(%importedpartids);
                   11976:                                if ($origfile eq '') {
                   11977:                                    my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   11978:                                    $origfile=&getfile($origfilelocation);
                   11979:                                    @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11980:                                }
1.1070    www      11981:                            }
1.1372    raeburn  11982:                            my @impfilepartids;
                   11983: # If <partorder> tag is included in metadata for the imported file
                   11984: # get the parts in the imported file from that.
                   11985:                            if (grep(/^partorder$/,@libfilekeys)) {
                   11986:                                %currmetaentry = %metaentry;
                   11987:                                my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   11988:                                                             $depthcount+1);
                   11989:                                %metaentry = %currmetaentry;
                   11990:                                undef(%currmetaentry);
                   11991:                                if ($libpartorder ne '') {
                   11992:                                    @impfilepartids=split(/\s*,\s*/,$libpartorder);
                   11993:                                }
                   11994:                            } else {
                   11995: # If no <partorder> tag available, load and inspect imported file
                   11996:                                my $impfile=&getfile($location);
                   11997:                                @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   11998:                            }
1.1069    www      11999:                            if ($#impfilepartids>=0) {
                   12000: # This problem had parts
1.1070    www      12001:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      12002:                            } else {
                   12003: # Importing by turning a single problem into a problem part
                   12004: # It gets the import-tags ID as part-ID
                   12005:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      12006:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      12007:                            }
1.1068    www      12008:                         } else {
1.1374    raeburn  12009: # Import as problem or as normal import
                   12010:                             $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12011:                             unless ($importmode eq 'problem') {
1.1068    www      12012: # Normal import
1.1374    raeburn  12013:                                 if (defined($token->[2]->{'id'})) {
                   12014:                                     $unikey.='_'.$token->[2]->{'id'};
                   12015:                                 }
                   12016:                             }
                   12017: # Check metadata for imported file to
                   12018: # see if it contained parts
                   12019:                             if (grep(/^partorder$/,@libfilekeys)) {
                   12020:                                 %currmetaentry = %metaentry;
                   12021:                                 my $libpartorder = &metadata($location,'partorder',undef,undef,undef,
                   12022:                                                              $depthcount+1);
                   12023:                                 %metaentry = %currmetaentry;
                   12024:                                 undef(%currmetaentry);
                   12025:                                 if ($libpartorder ne '') {
                   12026:                                     $importedparts = 1;
                   12027:                                     $importedpartids{$token->[2]->{'id'}}=$libpartorder;
                   12028:                                 }
                   12029:                             }
1.1067    www      12030:                         }
1.339     albertel 12031: 			if ($depthcount<20) {
1.736     albertel 12032: 			    my $metadata = 
1.1362    raeburn  12033: 				&metadata($uri,'keys',$toolsymb,$location,$unikey,
1.736     albertel 12034: 					  $depthcount+1);
                   12035: 			    foreach my $meta (split(',',$metadata)) {
                   12036: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   12037: 				$metathesekeys{$meta}=1;
1.339     albertel 12038: 			    }
1.1068    www      12039:                         }
1.1067    www      12040: 		    } else {
                   12041: #
                   12042: # Not importing, some other kind of non-package, non-library start tag
                   12043: # 
                   12044:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   12045:                         if (defined($token->[2]->{'id'})) {
                   12046:                             $unikey.='_'.$token->[2]->{'id'};
                   12047:                         }
1.339     albertel 12048: 			if (defined($token->[2]->{'name'})) { 
                   12049: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   12050: 			}
                   12051: 			$metathesekeys{$unikey}=1;
1.736     albertel 12052: 			foreach my $param (@{$token->[3]}) {
                   12053: 			    $metaentry{':'.$unikey.'.'.$param} =
                   12054: 				$token->[2]->{$param};
1.339     albertel 12055: 			}
                   12056: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 12057: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 12058: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   12059: 		 # only ws inside the tag, and not in default, so use default
                   12060: 		 # as value
1.599     albertel 12061: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 12062: 			} elsif ( $internaltext =~ /\S/ ) {
                   12063: 		  # something interesting inside the tag
                   12064: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 12065: 			} else {
1.908     albertel 12066: 		  # no interesting values, don't set a default
1.339     albertel 12067: 			}
1.172     www      12068: # end of not-a-package not-a-library import
1.339     albertel 12069: 		    }
1.172     www      12070: # end of not-a-package start tag
1.339     albertel 12071: 		}
1.172     www      12072: # the next is the end of "start tag"
1.339     albertel 12073: 	    }
                   12074: 	}
1.483     albertel 12075: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 12076: 	$extension = lc($extension);
                   12077: 	if ($extension eq 'htm') { $extension='html'; }
                   12078: 
1.737     albertel 12079: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 12080: 	    #no specific packages #how's our extension
                   12081: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 12082: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 12083: 					 \%metathesekeys);
                   12084: 	}
1.883     albertel 12085: 
                   12086: 	if (!exists($metaentry{':packages'})
                   12087: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 12088: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 12089: 		#no specific packages well let's get default then
                   12090: 		if ($key!~/^default&/) { next; }
1.488     albertel 12091: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 12092: 					     \%metathesekeys);
                   12093: 	    }
                   12094: 	}
1.338     www      12095: # are there custom rights to evaluate
1.599     albertel 12096: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 12097: 
1.338     www      12098:     #
                   12099:     # Importing a rights file here
1.339     albertel 12100:     #
                   12101: 	    unless ($depthcount) {
1.599     albertel 12102: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 12103: 		my $dir=$filename;
                   12104: 		$dir=~s|[^/]*$||;
                   12105: 		$location=&filelocation($dir,$location);
1.736     albertel 12106: 		my $rights_metadata =
1.1362    raeburn  12107: 		    &metadata($uri,'keys',$toolsymb,$location,'_rights',
1.736     albertel 12108: 			      $depthcount+1);
                   12109: 		foreach my $rights (split(',',$rights_metadata)) {
                   12110: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   12111: 		    $metathesekeys{$rights}=1;
1.339     albertel 12112: 		}
                   12113: 	    }
                   12114: 	}
1.737     albertel 12115: 	# uniqifiy package listing
                   12116: 	my %seen;
                   12117: 	my @uniq_packages =
                   12118: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   12119: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   12120: 
1.1369    raeburn  12121:         if (($importedresponses) || ($importedparts)) {
                   12122:             if ($importedparts) {
1.1070    www      12123: # We had imported parts and need to rebuild partorder
1.1369    raeburn  12124:                 $metaentry{':partorder'}='';
                   12125:                 $metathesekeys{'partorder'}=1;
                   12126:             }
                   12127:             if ($importedresponses) {
                   12128: # We had imported responses and need to rebuil responseorder
                   12129:                 $metaentry{':responseorder'}='';
                   12130:                 $metathesekeys{'responseorder'}=1;
                   12131:             }
                   12132:             for (my $index=0;$index<$#origfiletagids;$index+=2) {
                   12133:                 my $origid = $origfiletagids[$index+1];
                   12134:                 if ($origfiletagids[$index] eq 'part') {
                   12135: # Original part, part of the problem
                   12136:                     if ($importedparts) {
                   12137:                         $metaentry{':partorder'}.=','.$origid;
                   12138:                     }
                   12139:                 } elsif ($origfiletagids[$index] eq 'import') {
                   12140:                     if ($importedparts) {
                   12141: # We have imported parts at this position
1.1373    raeburn  12142:                         if ($importedpartids{$origid} ne '') {
                   12143:                             $metaentry{':partorder'}.=','.$importedpartids{$origid};
                   12144:                         }
1.1369    raeburn  12145:                     }
                   12146:                     if ($importedresponses) {
                   12147: # We have imported responses at this position
1.1373    raeburn  12148:                         if ($importedrespids{$origid} ne '') {
                   12149:                             $metaentry{':responseorder'}.=','.$importedrespids{$origid};
1.1369    raeburn  12150:                         }
                   12151:                     }
                   12152:                 } else {
                   12153: # Original response item, part of the problem
                   12154:                     if ($importedresponses) {
                   12155:                         $metaentry{':responseorder'}.=','.$origid;
                   12156:                     }
                   12157:                 }
                   12158:             }
                   12159:             if ($importedparts) {
                   12160:                 $metaentry{':partorder'}=~s/^\,//;
                   12161:             }
                   12162:             if ($importedresponses) {
                   12163:                 $metaentry{':responseorder'}=~s/^\,//;
                   12164:             }
1.1070    www      12165:         }
1.737     albertel 12166: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 12167: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
1.1274    raeburn  12168: 	$metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
1.1371    raeburn  12169:         unless ($liburi) {
                   12170: 	    &do_cache_new('meta',$uri,\%metaentry,$cachetime);
                   12171:         }
1.177     www      12172: # this is the end of "was not already recently cached
1.71      www      12173:     }
1.599     albertel 12174:     return $metaentry{':'.$what};
1.261     albertel 12175: }
                   12176: 
1.488     albertel 12177: sub metadata_create_package_def {
1.483     albertel 12178:     my ($uri,$key,$package,$metathesekeys)=@_;
                   12179:     my ($pack,$name,$subp)=split(/\&/,$key);
                   12180:     if ($subp eq 'default') { next; }
                   12181:     
1.599     albertel 12182:     if (defined($metaentry{':packages'})) {
                   12183: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 12184:     } else {
1.599     albertel 12185: 	$metaentry{':packages'}=$package;
1.483     albertel 12186:     }
                   12187:     my $value=$packagetab{$key};
                   12188:     my $unikey;
                   12189:     $unikey='parameter_0_'.$name;
1.599     albertel 12190:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 12191:     $$metathesekeys{$unikey}=1;
1.599     albertel 12192:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   12193: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 12194:     }
1.599     albertel 12195:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   12196: 	$metaentry{':'.$unikey}=
                   12197: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 12198:     }
                   12199: }
                   12200: 
1.261     albertel 12201: sub metadata_generate_part0 {
                   12202:     my ($metadata,$metacache,$uri) = @_;
                   12203:     my %allnames;
1.737     albertel 12204:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 12205: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 12206: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   12207: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 12208: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 12209: 	    $allnames{$name}=$part;
                   12210: 	  }
                   12211: 	}
                   12212:     }
                   12213:     foreach my $name (keys(%allnames)) {
                   12214:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 12215:       my $key=":parameter_0_$name";
1.261     albertel 12216:       $$metacache{"$key.part"}='0';
                   12217:       $$metacache{"$key.name"}=$name;
1.428     albertel 12218:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 12219: 					   $allnames{$name}.'_'.$name.
                   12220: 					   '.type'};
1.428     albertel 12221:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 12222: 			     '.display'};
1.644     www      12223:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 12224:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 12225:       $$metacache{"$key.display"}=$olddis;
                   12226:     }
1.71      www      12227: }
                   12228: 
1.764     albertel 12229: # ------------------------------------------------------ Devalidate title cache
                   12230: 
                   12231: sub devalidate_title_cache {
                   12232:     my ($url)=@_;
                   12233:     if (!$env{'request.course.id'}) { return; }
                   12234:     my $symb=&symbread($url);
                   12235:     if (!$symb) { return; }
                   12236:     my $key=$env{'request.course.id'}."\0".$symb;
                   12237:     &devalidate_cache_new('title',$key);
                   12238: }
                   12239: 
1.1014    droeschl 12240: # ------------------------------------------------- Get the title of a course
                   12241: 
                   12242: sub current_course_title {
                   12243:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   12244: }
1.301     www      12245: # ------------------------------------------------- Get the title of a resource
                   12246: 
                   12247: sub gettitle {
                   12248:     my $urlsymb=shift;
                   12249:     my $symb=&symbread($urlsymb);
1.534     albertel 12250:     if ($symb) {
1.620     albertel 12251: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 12252: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 12253: 	if (defined($cached)) { 
                   12254: 	    return $result;
                   12255: 	}
1.534     albertel 12256: 	my ($map,$resid,$url)=&decode_symb($symb);
                   12257: 	my $title='';
1.907     albertel 12258: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   12259: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   12260: 	} else {
                   12261: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   12262: 		    &GDBM_READER(),0640)) {
                   12263: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   12264: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   12265: 		untie(%bighash);
                   12266: 	    }
1.534     albertel 12267: 	}
                   12268: 	$title=~s/\&colon\;/\:/gs;
                   12269: 	if ($title) {
1.1159    www      12270: # Remember both $symb and $title for dynamic metadata
                   12271:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      12272:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      12273: # Cache this title and then return it
1.599     albertel 12274: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 12275: 	}
                   12276: 	$urlsymb=$url;
                   12277:     }
                   12278:     my $title=&metadata($urlsymb,'title');
                   12279:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   12280:     return $title;
1.301     www      12281: }
1.613     albertel 12282: 
1.614     albertel 12283: sub get_slot {
                   12284:     my ($which,$cnum,$cdom)=@_;
                   12285:     if (!$cnum || !$cdom) {
1.790     albertel 12286: 	(undef,my $courseid)=&whichuser();
1.620     albertel 12287: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   12288: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 12289:     }
1.703     albertel 12290:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   12291:     my %slotinfo;
                   12292:     if (exists($remembered{$key})) {
                   12293: 	$slotinfo{$which} = $remembered{$key};
                   12294:     } else {
                   12295: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   12296: 	&Apache::lonhomework::showhash(%slotinfo);
                   12297: 	my ($tmp)=keys(%slotinfo);
                   12298: 	if ($tmp=~/^error:/) { return (); }
                   12299: 	$remembered{$key} = $slotinfo{$which};
                   12300:     }
1.616     albertel 12301:     if (ref($slotinfo{$which}) eq 'HASH') {
                   12302: 	return %{$slotinfo{$which}};
                   12303:     }
                   12304:     return $slotinfo{$which};
1.614     albertel 12305: }
1.1150    raeburn  12306: 
                   12307: sub get_reservable_slots {
                   12308:     my ($cnum,$cdom,$uname,$udom) = @_;
                   12309:     my $now = time;
                   12310:     my $reservable_info;
                   12311:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   12312:     if (exists($remembered{$key})) {
                   12313:         $reservable_info = $remembered{$key};
                   12314:     } else {
                   12315:         my %resv;
                   12316:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   12317:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   12318:         $reservable_info = \%resv;
                   12319:         $remembered{$key} = $reservable_info;
                   12320:     }
                   12321:     return $reservable_info;
                   12322: }
                   12323: 
                   12324: sub get_course_slots {
                   12325:     my ($cnum,$cdom) = @_;
                   12326:     my $hashid=$cnum.':'.$cdom;
                   12327:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   12328:     if (defined($cached)) {
                   12329:         if (ref($result) eq 'HASH') {
                   12330:             return %{$result};
                   12331:         }
                   12332:     } else {
                   12333:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   12334:         my ($tmp) = keys(%slots);
                   12335:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.1219    raeburn  12336:             &do_cache_new('allslots',$hashid,\%slots,600);
1.1150    raeburn  12337:             return %slots;
                   12338:         }
                   12339:     }
                   12340:     return;
                   12341: }
                   12342: 
                   12343: sub devalidate_slots_cache {
                   12344:     my ($cnum,$cdom)=@_;
                   12345:     my $hashid=$cnum.':'.$cdom;
                   12346:     &devalidate_cache_new('allslots',$hashid);
                   12347: }
                   12348: 
1.1181    raeburn  12349: sub get_coursechange {
                   12350:     my ($cdom,$cnum) = @_;
                   12351:     if ($cdom eq '' || $cnum eq '') {
                   12352:         return unless ($env{'request.course.id'});
                   12353:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   12354:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   12355:     }
                   12356:     my $hashid=$cdom.'_'.$cnum;
                   12357:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
                   12358:     if ((defined($cached)) && ($change ne '')) {
                   12359:         return $change;
                   12360:     } else {
                   12361:         my %crshash;
                   12362:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
                   12363:         if ($crshash{'internal.contentchange'} eq '') {
                   12364:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
                   12365:             if ($change eq '') {
                   12366:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
                   12367:                 $change = $crshash{'internal.created'};
                   12368:             }
                   12369:         } else {
                   12370:             $change = $crshash{'internal.contentchange'};
                   12371:         }
                   12372:         my $cachetime = 600;
                   12373:         &do_cache_new('crschange',$hashid,$change,$cachetime);
                   12374:     }
                   12375:     return $change;
                   12376: }
                   12377: 
                   12378: sub devalidate_coursechange_cache {
                   12379:     my ($cnum,$cdom)=@_;
                   12380:     my $hashid=$cnum.':'.$cdom;
                   12381:     &devalidate_cache_new('crschange',$hashid);
                   12382: }
                   12383: 
1.31      www      12384: # ------------------------------------------------- Update symbolic store links
                   12385: 
                   12386: sub symblist {
                   12387:     my ($mapname,%newhash)=@_;
1.438     www      12388:     $mapname=&deversion(&declutter($mapname));
1.31      www      12389:     my %hash;
1.620     albertel 12390:     if (($env{'request.course.fn'}) && (%newhash)) {
                   12391:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12392:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  12393: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 12394: 		next if ($url eq 'last_known'
                   12395: 			 && $env{'form.no_update_last_known'});
                   12396: 		$hash{declutter($url)}=&encode_symb($mapname,
                   12397: 						    $newhash{$url}->[1],
                   12398: 						    $newhash{$url}->[0]);
1.191     harris41 12399:             }
1.31      www      12400:             if (untie(%hash)) {
                   12401: 		return 'ok';
                   12402:             }
                   12403:         }
                   12404:     }
                   12405:     return 'error';
1.212     www      12406: }
                   12407: 
                   12408: # --------------------------------------------------------------- Verify a symb
                   12409: 
                   12410: sub symbverify {
1.1190    raeburn  12411:     my ($symb,$thisurl,$encstate)=@_;
1.510     www      12412:     my $thisfn=$thisurl;
1.439     www      12413:     $thisfn=&declutter($thisfn);
1.215     www      12414: # direct jump to resource in page or to a sequence - will construct own symbs
                   12415:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   12416: # check URL part
1.409     www      12417:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      12418: 
1.431     www      12419:     unless ($url eq $thisfn) { return 0; }
1.213     www      12420: 
1.216     www      12421:     $symb=&symbclean($symb);
1.510     www      12422:     $thisurl=&deversion($thisurl);
1.439     www      12423:     $thisfn=&deversion($thisfn);
1.213     www      12424: 
                   12425:     my %bighash;
                   12426:     my $okay=0;
1.431     www      12427: 
1.620     albertel 12428:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12429:                             &GDBM_READER(),0640)) {
1.1204    raeburn  12430:         my $noclutter;
1.1032    raeburn  12431:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   12432:             $thisurl =~ s/\?.+$//;
1.1204    raeburn  12433:             if ($map =~ m{^uploaded/.+\.page$}) {
                   12434:                 $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
                   12435:                 $thisurl =~ s{^\Qhttp://https://\E}{https://};
                   12436:                 $noclutter = 1;
                   12437:             }
                   12438:         }
                   12439:         my $ids;
                   12440:         if ($noclutter) {
                   12441:             $ids=$bighash{'ids_'.$thisurl};
                   12442:         } else {
                   12443:             $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1032    raeburn  12444:         }
1.1102    raeburn  12445:         unless ($ids) {
                   12446:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   12447:             $ids=$bighash{$idkey};
1.216     www      12448:         }
                   12449:         if ($ids) {
                   12450: # ------------------------------------------------------------------- Has ID(s)
1.1202    raeburn  12451:             if ($thisfn =~ m{^/adm/wrapper/ext/}) {
1.1203    raeburn  12452:                 $symb =~ s/\?.+$//;
1.1202    raeburn  12453:             }
1.800     albertel 12454: 	    foreach my $id (split(/\,/,$ids)) {
                   12455: 	       my ($mapid,$resid)=split(/\./,$id);
1.216     www      12456:                if (
                   12457:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
1.1190    raeburn  12458:    eq $symb) {
                   12459:                    if (ref($encstate)) {
                   12460:                        $$encstate = $bighash{'encrypted_'.$id};
                   12461:                    }
1.620     albertel 12462: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  12463: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   12464:                        ($thisurl eq '/adm/navmaps')) {
1.1190    raeburn  12465: 		       $okay=1;
1.1202    raeburn  12466:                        last;
1.582     albertel 12467: 		   }
                   12468: 	       }
1.216     www      12469: 	   }
                   12470:         }
1.213     www      12471: 	untie(%bighash);
                   12472:     }
                   12473:     return $okay;
1.31      www      12474: }
                   12475: 
1.210     www      12476: # --------------------------------------------------------------- Clean-up symb
                   12477: 
                   12478: sub symbclean {
                   12479:     my $symb=shift;
1.568     albertel 12480:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      12481: # remove version from map
                   12482:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      12483: 
1.210     www      12484: # remove version from URL
                   12485:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      12486: 
1.507     www      12487: # remove wrapper
                   12488: 
1.510     www      12489:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 12490:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      12491:     return $symb;
1.409     www      12492: }
                   12493: 
                   12494: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 12495: 
                   12496: sub encode_symb {
                   12497:     my ($map,$resid,$url)=@_;
                   12498:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   12499: }
1.409     www      12500: 
                   12501: sub decode_symb {
1.568     albertel 12502:     my $symb=shift;
                   12503:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   12504:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      12505:     return (&fixversion($map),$resid,&fixversion($url));
                   12506: }
                   12507: 
                   12508: sub fixversion {
                   12509:     my $fn=shift;
1.609     banghart 12510:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      12511:     my %bighash;
                   12512:     my $uri=&clutter($fn);
1.620     albertel 12513:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      12514: # is this cached?
1.599     albertel 12515:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      12516:     if (defined($cached)) { return $result; }
                   12517: # unfortunately not cached, or expired
1.620     albertel 12518:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      12519: 	    &GDBM_READER(),0640)) {
                   12520:  	if ($bighash{'version_'.$uri}) {
                   12521:  	    my $version=$bighash{'version_'.$uri};
1.444     www      12522:  	    unless (($version eq 'mostrecent') || 
                   12523: 		    ($version==&getversion($uri))) {
1.440     www      12524:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   12525:  	    }
                   12526:  	}
                   12527:  	untie %bighash;
1.413     www      12528:     }
1.599     albertel 12529:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      12530: }
                   12531: 
                   12532: sub deversion {
                   12533:     my $url=shift;
                   12534:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   12535:     return $url;
1.210     www      12536: }
                   12537: 
1.31      www      12538: # ------------------------------------------------------ Return symb list entry
                   12539: 
                   12540: sub symbread {
1.1282    raeburn  12541:     my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
1.1265    raeburn  12542:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1282    raeburn  12543:     if (defined($env{$cache_str})) {
                   12544:         if ($ignorecachednull) {
                   12545:             return $env{$cache_str} unless ($env{$cache_str} eq '');
                   12546:         } else {
                   12547:             return $env{$cache_str};
                   12548:         }
                   12549:     }
1.242     www      12550: # no filename provided? try from environment
1.1265    raeburn  12551:     unless ($thisfn) {
1.620     albertel 12552:         if ($env{'request.symb'}) {
                   12553: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 12554: 	}
1.620     albertel 12555: 	$thisfn=$env{'request.filename'};
1.44      www      12556:     }
1.569     albertel 12557:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      12558: # is that filename actually a symb? Verify, clean, and return
                   12559:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 12560: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 12561: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 12562: 	}
1.242     www      12563:     }
1.44      www      12564:     $thisfn=declutter($thisfn);
1.31      www      12565:     my %hash;
1.37      www      12566:     my %bighash;
                   12567:     my $syval='';
1.620     albertel 12568:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  12569:         my $targetfn = $thisfn;
1.609     banghart 12570:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  12571:             $targetfn = 'adm/wrapper/'.$thisfn;
                   12572:         }
1.687     albertel 12573: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   12574: 	    $targetfn=$1;
                   12575: 	}
1.620     albertel 12576:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 12577:                       &GDBM_READER(),0640)) {
1.481     raeburn  12578: 	    $syval=$hash{$targetfn};
1.37      www      12579:             untie(%hash);
                   12580:         }
                   12581: # ---------------------------------------------------------- There was an entry
                   12582:         if ($syval) {
1.601     albertel 12583: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 12584: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  12585: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12586: 		    #return $env{$cache_str}='';
1.601     albertel 12587: 		#}    
                   12588: 		#$syval.=$1;
                   12589: 	    #}
1.37      www      12590:         } else {
                   12591: # ------------------------------------------------------- Was not in symb table
1.620     albertel 12592:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 12593:                             &GDBM_READER(),0640)) {
1.37      www      12594: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      12595:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      12596:               unless ($ids) { 
                   12597:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      12598:               }
                   12599:               unless ($ids) {
                   12600: # alias?
                   12601: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      12602:               }
1.37      www      12603:               if ($ids) {
                   12604: # ------------------------------------------------------------------- Has ID(s)
                   12605:                  my @possibilities=split(/\,/,$ids);
1.39      www      12606:                  if ($#possibilities==0) {
                   12607: # ----------------------------------------------- There is only one possibility
1.37      www      12608: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 12609: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12610: 						    $resid,$thisfn);
1.1282    raeburn  12611:                      if (ref($possibles) eq 'HASH') {
                   12612:                          $possibles->{$syval} = 1;    
                   12613:                      }
                   12614:                      if ($checkforblock) {
                   12615:                          my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
                   12616:                          if (@blockers) {
                   12617:                              $syval = '';
                   12618:                              return;
                   12619:                          }
                   12620:                      }
                   12621:                  } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) { 
1.39      www      12622: # ------------------------------------------ There is more than one possibility
                   12623:                      my $realpossible=0;
1.800     albertel 12624:                      foreach my $id (@possibilities) {
                   12625: 			 my $file=$bighash{'src_'.$id};
1.1282    raeburn  12626:                          my $canaccess;
                   12627:                          if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
                   12628:                              $canaccess = 1;
                   12629:                          } else { 
                   12630:                              $canaccess = &allowed('bre',$file);
                   12631:                          }
                   12632:                          if ($canaccess) {
                   12633:          		     my ($mapid,$resid)=split(/\./,$id);
                   12634:                              if ($bighash{'map_type_'.$mapid} ne 'page') {
                   12635:                                  my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
                   12636: 						             $resid,$thisfn);
                   12637:                                  if (ref($possibles) eq 'HASH') {
                   12638:                                      $possibles->{$syval} = 1;
                   12639:                                  }
                   12640:                                  if ($checkforblock) {
                   12641:                                      my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
                   12642:                                      unless (@blockers > 0) {
                   12643:                                          $syval = $poss_syval;
                   12644:                                          $realpossible++;
                   12645:                                      }
                   12646:                                  } else {
                   12647:                                      $syval = $poss_syval;
                   12648:                                      $realpossible++;
                   12649:                                  }
                   12650:                              }
1.39      www      12651: 			 }
1.191     harris41 12652:                      }
1.39      www      12653: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      12654:                  } else {
                   12655:                      $syval='';
1.37      www      12656:                  }
                   12657: 	      }
1.1282    raeburn  12658:               untie(%bighash);
1.481     raeburn  12659:            }
1.31      www      12660:         }
1.62      www      12661:         if ($syval) {
1.620     albertel 12662: 	    return $env{$cache_str}=$syval;
1.62      www      12663:         }
1.31      www      12664:     }
1.949     raeburn  12665:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 12666:     return $env{$cache_str}='';
1.31      www      12667: }
                   12668: 
                   12669: # ---------------------------------------------------------- Return random seed
                   12670: 
1.32      www      12671: sub numval {
                   12672:     my $txt=shift;
                   12673:     $txt=~tr/A-J/0-9/;
                   12674:     $txt=~tr/a-j/0-9/;
                   12675:     $txt=~tr/K-T/0-9/;
                   12676:     $txt=~tr/k-t/0-9/;
                   12677:     $txt=~tr/U-Z/0-5/;
                   12678:     $txt=~tr/u-z/0-5/;
                   12679:     $txt=~s/\D//g;
1.564     albertel 12680:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      12681:     return int($txt);
1.368     albertel 12682: }
                   12683: 
1.484     albertel 12684: sub numval2 {
                   12685:     my $txt=shift;
                   12686:     $txt=~tr/A-J/0-9/;
                   12687:     $txt=~tr/a-j/0-9/;
                   12688:     $txt=~tr/K-T/0-9/;
                   12689:     $txt=~tr/k-t/0-9/;
                   12690:     $txt=~tr/U-Z/0-5/;
                   12691:     $txt=~tr/u-z/0-5/;
                   12692:     $txt=~s/\D//g;
                   12693:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12694:     my $total;
                   12695:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 12696:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 12697:     return int($total);
                   12698: }
                   12699: 
1.575     albertel 12700: sub numval3 {
                   12701:     use integer;
                   12702:     my $txt=shift;
                   12703:     $txt=~tr/A-J/0-9/;
                   12704:     $txt=~tr/a-j/0-9/;
                   12705:     $txt=~tr/K-T/0-9/;
                   12706:     $txt=~tr/k-t/0-9/;
                   12707:     $txt=~tr/U-Z/0-5/;
                   12708:     $txt=~tr/u-z/0-5/;
                   12709:     $txt=~s/\D//g;
                   12710:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   12711:     my $total;
                   12712:     foreach my $val (@txts) { $total+=$val; }
                   12713:     if ($_64bit) { $total=(($total<<32)>>32); }
                   12714:     return $total;
                   12715: }
                   12716: 
1.675     albertel 12717: sub digest {
                   12718:     my ($data)=@_;
                   12719:     my $digest=&Digest::MD5::md5($data);
                   12720:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   12721:     my ($e,$f);
                   12722:     {
                   12723:         use integer;
                   12724:         $e=($a+$b);
                   12725:         $f=($c+$d);
                   12726:         if ($_64bit) {
                   12727:             $e=(($e<<32)>>32);
                   12728:             $f=(($f<<32)>>32);
                   12729:         }
                   12730:     }
                   12731:     if (wantarray) {
                   12732: 	return ($e,$f);
                   12733:     } else {
                   12734: 	my $g;
                   12735: 	{
                   12736: 	    use integer;
                   12737: 	    $g=($e+$f);
                   12738: 	    if ($_64bit) {
                   12739: 		$g=(($g<<32)>>32);
                   12740: 	    }
                   12741: 	}
                   12742: 	return $g;
                   12743:     }
                   12744: }
                   12745: 
1.368     albertel 12746: sub latest_rnd_algorithm_id {
1.675     albertel 12747:     return '64bit5';
1.366     albertel 12748: }
1.32      www      12749: 
1.503     albertel 12750: sub get_rand_alg {
                   12751:     my ($courseid)=@_;
1.790     albertel 12752:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 12753:     if ($courseid) {
1.620     albertel 12754: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 12755:     }
                   12756:     return &latest_rnd_algorithm_id();
                   12757: }
                   12758: 
1.562     albertel 12759: sub validCODE {
                   12760:     my ($CODE)=@_;
                   12761:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   12762:     return 0;
                   12763: }
                   12764: 
1.491     albertel 12765: sub getCODE {
1.620     albertel 12766:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 12767:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   12768: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   12769: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 12770: 	return $Apache::lonhomework::history{'resource.CODE'};
                   12771:     }
                   12772:     return undef;
                   12773: }
1.1133    foxr     12774: #
                   12775: #  Determines the random seed for a specific context:
                   12776: #
                   12777: # parameters:
                   12778: #   symb      - in course context the symb for the seed.
                   12779: #   course_id - The course id of the form domain_coursenum.
                   12780: #   domain    - Domain for the user.
                   12781: #   course    - Course for the user.
                   12782: #   cenv      - environment of the course.
                   12783: #
                   12784: # NOTE:
                   12785: #   All parameters are picked out of the environment if missing
                   12786: #   or not defined.
                   12787: #   If a symb cannot be determined the current time is used instead.
                   12788: #
                   12789: #  For a given well defined symb, courside, domain, username,
                   12790: #  and course environment, the seed is reproducible.
                   12791: #
1.31      www      12792: sub rndseed {
1.1133    foxr     12793:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 12794:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 12795:     if (!defined($symb)) {
1.366     albertel 12796: 	unless ($symb=$wsymb) { return time; }
                   12797:     }
1.1146    foxr     12798:     if (!defined $courseid) { 
                   12799: 	$courseid=$wcourseid; 
                   12800:     }
                   12801:     if (!defined $domain) { $domain=$wdomain; }
                   12802:     if (!defined $username) { $username=$wusername }
1.1133    foxr     12803: 
                   12804:     my $which;
                   12805:     if (defined($cenv->{'rndseed'})) {
                   12806: 	$which = $cenv->{'rndseed'};
                   12807:     } else {
                   12808: 	$which =&get_rand_alg($courseid);
                   12809:     }
1.491     albertel 12810:     if (defined(&getCODE())) {
1.1133    foxr     12811: 
1.675     albertel 12812: 	if ($which eq '64bit5') {
                   12813: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   12814: 	} elsif ($which eq '64bit4') {
1.575     albertel 12815: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   12816: 	} else {
                   12817: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   12818: 	}
1.675     albertel 12819:     } elsif ($which eq '64bit5') {
                   12820: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 12821:     } elsif ($which eq '64bit4') {
                   12822: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 12823:     } elsif ($which eq '64bit3') {
                   12824: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 12825:     } elsif ($which eq '64bit2') {
                   12826: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 12827:     } elsif ($which eq '64bit') {
                   12828: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   12829:     }
                   12830:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   12831: }
                   12832: 
                   12833: sub rndseed_32bit {
                   12834:     my ($symb,$courseid,$domain,$username)=@_;
                   12835:     {
                   12836: 	use integer;
                   12837: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   12838: 	my $symbseed=numval($symb) << 22;
                   12839: 	my $namechck=unpack("%32C*",$username) << 17;
                   12840: 	my $nameseed=numval($username) << 12;
                   12841: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   12842: 	my $courseseed=unpack("%32C*",$courseid);
                   12843: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 12844: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12845: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12846: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 12847: 	return $num;
                   12848:     }
                   12849: }
                   12850: 
                   12851: sub rndseed_64bit {
                   12852:     my ($symb,$courseid,$domain,$username)=@_;
                   12853:     {
                   12854: 	use integer;
                   12855: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   12856: 	my $symbseed=numval($symb) << 10;
                   12857: 	my $namechck=unpack("%32S*",$username);
                   12858: 	
                   12859: 	my $nameseed=numval($username) << 21;
                   12860: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   12861: 	my $courseseed=unpack("%32S*",$courseid);
                   12862: 	
                   12863: 	my $num1=$symbchck+$symbseed+$namechck;
                   12864: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12865: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12866: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 12867: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 12868: 	return "$num1,$num2";
1.155     albertel 12869:     }
1.366     albertel 12870: }
                   12871: 
1.443     albertel 12872: sub rndseed_64bit2 {
                   12873:     my ($symb,$courseid,$domain,$username)=@_;
                   12874:     {
                   12875: 	use integer;
                   12876: 	# strings need to be an even # of cahracters long, it it is odd the
                   12877:         # last characters gets thrown away
                   12878: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12879: 	my $symbseed=numval($symb) << 10;
                   12880: 	my $namechck=unpack("%32S*",$username.' ');
                   12881: 	
                   12882: 	my $nameseed=numval($username) << 21;
1.501     albertel 12883: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12884: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12885: 	
                   12886: 	my $num1=$symbchck+$symbseed+$namechck;
                   12887: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12888: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12889: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 12890: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 12891: 	return "$num1,$num2";
                   12892:     }
                   12893: }
                   12894: 
                   12895: sub rndseed_64bit3 {
                   12896:     my ($symb,$courseid,$domain,$username)=@_;
                   12897:     {
                   12898: 	use integer;
                   12899: 	# strings need to be an even # of cahracters long, it it is odd the
                   12900:         # last characters gets thrown away
                   12901: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12902: 	my $symbseed=numval2($symb) << 10;
                   12903: 	my $namechck=unpack("%32S*",$username.' ');
                   12904: 	
                   12905: 	my $nameseed=numval2($username) << 21;
1.443     albertel 12906: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12907: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12908: 	
                   12909: 	my $num1=$symbchck+$symbseed+$namechck;
                   12910: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12911: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12912: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 12913: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12914: 	
1.503     albertel 12915: 	return "$num1:$num2";
1.443     albertel 12916:     }
                   12917: }
                   12918: 
1.575     albertel 12919: sub rndseed_64bit4 {
                   12920:     my ($symb,$courseid,$domain,$username)=@_;
                   12921:     {
                   12922: 	use integer;
                   12923: 	# strings need to be an even # of cahracters long, it it is odd the
                   12924:         # last characters gets thrown away
                   12925: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   12926: 	my $symbseed=numval3($symb) << 10;
                   12927: 	my $namechck=unpack("%32S*",$username.' ');
                   12928: 	
                   12929: 	my $nameseed=numval3($username) << 21;
                   12930: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   12931: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12932: 	
                   12933: 	my $num1=$symbchck+$symbseed+$namechck;
                   12934: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 12935: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   12936: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 12937: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      12938: 	
1.575     albertel 12939: 	return "$num1:$num2";
                   12940:     }
                   12941: }
                   12942: 
1.675     albertel 12943: sub rndseed_64bit5 {
                   12944:     my ($symb,$courseid,$domain,$username)=@_;
                   12945:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   12946:     return "$num1:$num2";
                   12947: }
                   12948: 
1.366     albertel 12949: sub rndseed_CODE_64bit {
                   12950:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 12951:     {
1.366     albertel 12952: 	use integer;
1.443     albertel 12953: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 12954: 	my $symbseed=numval2($symb);
1.491     albertel 12955: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12956: 	my $CODEseed=numval(&getCODE());
1.443     albertel 12957: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 12958: 	my $num1=$symbseed+$CODEchck;
                   12959: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12960: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12961: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 12962: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12963: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 12964: 	return "$num1:$num2";
1.366     albertel 12965:     }
                   12966: }
                   12967: 
1.575     albertel 12968: sub rndseed_CODE_64bit4 {
                   12969:     my ($symb,$courseid,$domain,$username)=@_;
                   12970:     {
                   12971: 	use integer;
                   12972: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   12973: 	my $symbseed=numval3($symb);
                   12974: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   12975: 	my $CODEseed=numval3(&getCODE());
                   12976: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   12977: 	my $num1=$symbseed+$CODEchck;
                   12978: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 12979: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   12980: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 12981: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   12982: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   12983: 	return "$num1:$num2";
                   12984:     }
                   12985: }
                   12986: 
1.675     albertel 12987: sub rndseed_CODE_64bit5 {
                   12988:     my ($symb,$courseid,$domain,$username)=@_;
                   12989:     my $code = &getCODE();
                   12990:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   12991:     return "$num1:$num2";
                   12992: }
                   12993: 
1.366     albertel 12994: sub setup_random_from_rndseed {
                   12995:     my ($rndseed)=@_;
1.503     albertel 12996:     if ($rndseed =~/([,:])/) {
1.1262    raeburn  12997:         my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
                   12998:         if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
                   12999:             &Math::Random::random_set_seed_from_phrase($rndseed);
                   13000:         } else {
                   13001:             &Math::Random::random_set_seed($num1,$num2);
                   13002:         }
1.366     albertel 13003:     } else {
                   13004: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 13005:     }
1.36      albertel 13006: }
                   13007: 
1.474     albertel 13008: sub latest_receipt_algorithm_id {
1.835     albertel 13009:     return 'receipt3';
1.474     albertel 13010: }
                   13011: 
1.480     www      13012: sub recunique {
                   13013:     my $fucourseid=shift;
                   13014:     my $unique;
1.835     albertel 13015:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   13016: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13017: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      13018:     } else {
                   13019: 	$unique=$perlvar{'lonReceipt'};
                   13020:     }
                   13021:     return unpack("%32C*",$unique);
                   13022: }
                   13023: 
                   13024: sub recprefix {
                   13025:     my $fucourseid=shift;
                   13026:     my $prefix;
1.835     albertel 13027:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   13028: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 13029: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      13030:     } else {
                   13031: 	$prefix=$perlvar{'lonHostID'};
                   13032:     }
                   13033:     return unpack("%32C*",$prefix);
                   13034: }
                   13035: 
1.76      www      13036: sub ireceipt {
1.474     albertel 13037:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 13038: 
                   13039:     my $return =&recprefix($fucourseid).'-';
                   13040: 
                   13041:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   13042: 	$env{'request.state'} eq 'construct') {
                   13043: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   13044: 	return $return;
                   13045:     }
                   13046: 
1.76      www      13047:     my $cuname=unpack("%32C*",$funame);
                   13048:     my $cudom=unpack("%32C*",$fudom);
                   13049:     my $cucourseid=unpack("%32C*",$fucourseid);
                   13050:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      13051:     my $cunique=&recunique($fucourseid);
1.474     albertel 13052:     my $cpart=unpack("%32S*",$part);
1.835     albertel 13053:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   13054: 
1.790     albertel 13055: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 13056: 			       
                   13057: 	$return.= ($cunique%$cuname+
                   13058: 		   $cunique%$cudom+
                   13059: 		   $cusymb%$cuname+
                   13060: 		   $cusymb%$cudom+
                   13061: 		   $cucourseid%$cuname+
                   13062: 		   $cucourseid%$cudom+
                   13063: 		   $cpart%$cuname+
                   13064: 		   $cpart%$cudom);
                   13065:     } else {
                   13066: 	$return.= ($cunique%$cuname+
                   13067: 		   $cunique%$cudom+
                   13068: 		   $cusymb%$cuname+
                   13069: 		   $cusymb%$cudom+
                   13070: 		   $cucourseid%$cuname+
                   13071: 		   $cucourseid%$cudom);
                   13072:     }
                   13073:     return $return;
1.76      www      13074: }
                   13075: 
                   13076: sub receipt {
1.474     albertel 13077:     my ($part)=@_;
1.790     albertel 13078:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 13079:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      13080: }
1.260     ng       13081: 
1.790     albertel 13082: sub whichuser {
                   13083:     my ($passedsymb)=@_;
                   13084:     my ($symb,$courseid,$domain,$name,$publicuser);
                   13085:     if (defined($env{'form.grade_symb'})) {
                   13086: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   13087: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   13088: 	if (!$allowed &&
                   13089: 	    exists($env{'request.course.sec'}) &&
                   13090: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   13091: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   13092: 			      '/'.$env{'request.course.sec'});
                   13093: 	}
                   13094: 	if ($allowed) {
                   13095: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   13096: 	    $courseid=$tmp_courseid;
                   13097: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   13098: 	    ($name)=&get_env_multiple('form.grade_username');
                   13099: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   13100: 	}
                   13101:     }
                   13102:     if (!$passedsymb) {
                   13103: 	$symb=&symbread();
                   13104:     } else {
                   13105: 	$symb=$passedsymb;
                   13106:     }
                   13107:     $courseid=$env{'request.course.id'};
                   13108:     $domain=$env{'user.domain'};
                   13109:     $name=$env{'user.name'};
                   13110:     if ($name eq 'public' && $domain eq 'public') {
                   13111: 	if (!defined($env{'form.username'})) {
                   13112: 	    $env{'form.username'}.=time.rand(10000000);
                   13113: 	}
                   13114: 	$name.=$env{'form.username'};
                   13115:     }
                   13116:     return ($symb,$courseid,$domain,$name,$publicuser);
                   13117: 
                   13118: }
                   13119: 
1.36      albertel 13120: # ------------------------------------------------------------ Serves up a file
1.472     albertel 13121: # returns either the contents of the file or 
                   13122: # -1 if the file doesn't exist
1.481     raeburn  13123: #
                   13124: # if the target is a file that was uploaded via DOCS, 
                   13125: # a check will be made to see if a current copy exists on the local server,
                   13126: # if it does this will be served, otherwise a copy will be retrieved from
                   13127: # the home server for the course and stored in /home/httpd/html/userfiles on
                   13128: # the local server.   
1.472     albertel 13129: 
1.36      albertel 13130: sub getfile {
1.538     albertel 13131:     my ($file) = @_;
1.609     banghart 13132:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 13133:     &repcopy($file);
                   13134:     return &readfile($file);
                   13135: }
                   13136: 
                   13137: sub repcopy_userfile {
                   13138:     my ($file)=@_;
1.1142    raeburn  13139:     my $londocroot = $perlvar{'lonDocRoot'};
                   13140:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  13141:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 13142:     my ($cdom,$cnum,$filename) = 
1.811     albertel 13143: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 13144:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   13145:     if (-e "$file") {
1.828     www      13146: # we already have a local copy, check it out
1.538     albertel 13147: 	my @fileinfo = stat($file);
1.828     www      13148: 	my $rtncode;
                   13149: 	my $info;
1.538     albertel 13150: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 13151: 	if ($lwpresp ne 'ok') {
1.828     www      13152: # there is no such file anymore, even though we had a local copy
1.482     albertel 13153: 	    if ($rtncode eq '404') {
1.538     albertel 13154: 		unlink($file);
1.482     albertel 13155: 	    }
                   13156: 	    return -1;
                   13157: 	}
                   13158: 	if ($info < $fileinfo[9]) {
1.828     www      13159: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  13160: 	    return 'ok';
1.828     www      13161: 	} else {
                   13162: # the file is outdated, get rid of it
                   13163: 	    unlink($file);
1.482     albertel 13164: 	}
1.828     www      13165:     }
                   13166: # one way or the other, at this point, we don't have the file
                   13167: # construct the correct path for the file
                   13168:     my @parts = ($cdom,$cnum); 
                   13169:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   13170: 	push @parts, split(/\//,$1);
                   13171:     }
                   13172:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   13173:     foreach my $part (@parts) {
                   13174: 	$path .= '/'.$part;
                   13175: 	if (!-e $path) {
                   13176: 	    mkdir($path,0770);
1.482     albertel 13177: 	}
                   13178:     }
1.828     www      13179: # now the path exists for sure
                   13180: # get a user agent
                   13181:     my $transferfile=$file.'.in.transfer';
                   13182: # FIXME: this should flock
                   13183:     if (-e $transferfile) { return 'ok'; }
                   13184:     my $request;
                   13185:     $uri=~s/^\///;
1.980     raeburn  13186:     my $homeserver = &homeserver($cnum,$cdom);
                   13187:     my $protocol = $protocol{$homeserver};
                   13188:     $protocol = 'http' if ($protocol ne 'https');
                   13189:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.1345    raeburn  13190:     my $response = &LONCAPA::LWPReq::makerequest($homeserver,$request,$transferfile,\%perlvar,'',0,1);
1.828     www      13191: # did it work?
                   13192:     if ($response->is_error()) {
                   13193: 	unlink($transferfile);
                   13194: 	&logthis("Userfile repcopy failed for $uri");
                   13195: 	return -1;
                   13196:     }
                   13197: # worked, rename the transfer file
                   13198:     rename($transferfile,$file);
1.607     raeburn  13199:     return 'ok';
1.481     raeburn  13200: }
                   13201: 
1.517     albertel 13202: sub tokenwrapper {
                   13203:     my $uri=shift;
1.980     raeburn  13204:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 13205:     $uri=~s|^/||;
1.620     albertel 13206:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 13207:     my $token=$1;
1.552     albertel 13208:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   13209:     if ($udom && $uname && $file) {
                   13210: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  13211:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  13212:         my $homeserver = &homeserver($uname,$udom);
                   13213:         my $protocol = $protocol{$homeserver};
                   13214:         $protocol = 'http' if ($protocol ne 'https');
                   13215:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 13216:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   13217:                                '&tokenissued='.$perlvar{'lonHostID'};
                   13218:     } else {
                   13219:         return '/adm/notfound.html';
                   13220:     }
                   13221: }
                   13222: 
1.828     www      13223: # call with reqtype HEAD: get last modification time
                   13224: # call with reqtype GET: get the file contents
                   13225: # Do not call this with reqtype GET for large files! It loads everything into memory
                   13226: #
1.481     raeburn  13227: sub getuploaded {
                   13228:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   13229:     $uri=~s/^\///;
1.980     raeburn  13230:     my $homeserver = &homeserver($cnum,$cdom);
                   13231:     my $protocol = $protocol{$homeserver};
                   13232:     $protocol = 'http' if ($protocol ne 'https');
                   13233:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  13234:     my $request=new HTTP::Request($reqtype,$uri);
1.1345    raeburn  13235:     my $response=&LONCAPA::LWPReq::makerequest($homeserver,$request,'',\%perlvar,'',0,1);
1.481     raeburn  13236:     $$rtncode = $response->code;
1.482     albertel 13237:     if (! $response->is_success()) {
                   13238: 	return 'failed';
                   13239:     }      
                   13240:     if ($reqtype eq 'HEAD') {
1.486     www      13241: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 13242:     } elsif ($reqtype eq 'GET') {
                   13243: 	$$info = $response->content;
1.472     albertel 13244:     }
1.482     albertel 13245:     return 'ok';
1.36      albertel 13246: }
                   13247: 
1.481     raeburn  13248: sub readfile {
                   13249:     my $file = shift;
                   13250:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   13251:     my $fh;
1.1359    raeburn  13252:     open($fh,"<",$file);
1.481     raeburn  13253:     my $a='';
1.800     albertel 13254:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  13255:     return $a;
                   13256: }
                   13257: 
1.36      albertel 13258: sub filelocation {
1.590     banghart 13259:     my ($dir,$file) = @_;
                   13260:     my $location;
                   13261:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 13262: 
                   13263:     if ($file =~ m-^/adm/-) {
                   13264: 	$file=~s-^/adm/wrapper/-/-;
                   13265: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   13266:     }
1.882     albertel 13267: 
1.1139    www      13268:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  13269:         $location = $file;
1.609     banghart 13270:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 13271:         my ($udom,$uname,$filename)=
1.811     albertel 13272:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 13273:         my $home=&homeserver($uname,$udom);
                   13274:         my $is_me=0;
                   13275:         my @ids=&current_machine_ids();
                   13276:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   13277:         if ($is_me) {
1.1117    foxr     13278:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 13279:         } else {
                   13280:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   13281:   	      $udom.'/'.$uname.'/'.$filename;
                   13282:         }
1.882     albertel 13283:     } elsif ($file =~ m-^/adm/-) {
                   13284: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 13285:     } else {
                   13286:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      13287:         $file=~s:^/(res|priv)/:/:;
                   13288:         my $space=$1;
1.590     banghart 13289:         if ( !( $file =~ m:^/:) ) {
                   13290:             $location = $dir. '/'.$file;
                   13291:         } else {
1.1142    raeburn  13292:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 13293:         }
1.59      albertel 13294:     }
1.590     banghart 13295:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 13296:     while ($location=~m{/\.\./}) {
                   13297: 	if ($location =~ m{/[^/]+/\.\./}) {
                   13298: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   13299: 	} else {
                   13300: 	    $location=~ s{/\.\./}{/}g;
                   13301: 	}
                   13302:     } #remove dir/..
1.590     banghart 13303:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   13304:     return $location;
1.46      www      13305: }
1.36      albertel 13306: 
1.46      www      13307: sub hreflocation {
                   13308:     my ($dir,$file)=@_;
1.980     raeburn  13309:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 13310: 	$file=filelocation($dir,$file);
1.700     albertel 13311:     } elsif ($file=~m-^/adm/-) {
                   13312: 	$file=~s-^/adm/wrapper/-/-;
                   13313: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 13314:     }
                   13315:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   13316: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   13317:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  13318: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   13319: 	        {/uploaded/$1/$2/}x;
1.46      www      13320:     }
1.913     albertel 13321:     if ($file=~ m{^/userfiles/}) {
                   13322: 	$file =~ s{^/userfiles/}{/uploaded/};
                   13323:     }
1.462     albertel 13324:     return $file;
1.465     albertel 13325: }
                   13326: 
1.1139    www      13327: 
                   13328: 
                   13329: 
                   13330: 
1.465     albertel 13331: sub current_machine_domains {
1.853     albertel 13332:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   13333: }
                   13334: 
                   13335: sub machine_domains {
                   13336:     my ($hostname) = @_;
1.465     albertel 13337:     my @domains;
1.838     albertel 13338:     my %hostname = &all_hostnames();
1.465     albertel 13339:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  13340: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 13341: 	if ($hostname eq $name) {
1.844     albertel 13342: 	    push(@domains,&host_domain($id));
1.465     albertel 13343: 	}
                   13344:     }
                   13345:     return @domains;
                   13346: }
                   13347: 
                   13348: sub current_machine_ids {
1.853     albertel 13349:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   13350: }
                   13351: 
                   13352: sub machine_ids {
                   13353:     my ($hostname) = @_;
                   13354:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 13355:     my @ids;
1.888     albertel 13356:     my %name_to_host = &all_names();
1.889     albertel 13357:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   13358: 	return @{ $name_to_host{$hostname} };
                   13359:     }
                   13360:     return;
1.31      www      13361: }
                   13362: 
1.824     raeburn  13363: sub additional_machine_domains {
                   13364:     my @domains;
1.1359    raeburn  13365:     open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
1.824     raeburn  13366:     while( my $line = <$fh>) {
                   13367:         $line =~ s/\s//g;
                   13368:         push(@domains,$line);
                   13369:     }
                   13370:     return @domains;
                   13371: }
                   13372: 
                   13373: sub default_login_domain {
                   13374:     my $domain = $perlvar{'lonDefDomain'};
                   13375:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   13376:     foreach my $posdom (&current_machine_domains(),
                   13377:                         &additional_machine_domains()) {
                   13378:         if (lc($posdom) eq lc($testdomain)) {
                   13379:             $domain=$posdom;
                   13380:             last;
                   13381:         }
                   13382:     }
                   13383:     return $domain;
                   13384: }
                   13385: 
1.31      www      13386: # ------------------------------------------------------------- Declutters URLs
                   13387: 
                   13388: sub declutter {
                   13389:     my $thisfn=shift;
1.569     albertel 13390:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.1261    raeburn  13391:     unless ($thisfn=~m{^/home/httpd/html/priv/}) {
                   13392:         $thisfn=~s{^/home/httpd/html}{};
                   13393:     }
1.31      www      13394:     $thisfn=~s/^\///;
1.697     albertel 13395:     $thisfn=~s|^adm/wrapper/||;
                   13396:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      13397:     $thisfn=~s/^res\///;
1.1172    bisitz   13398:     $thisfn=~s/^priv\///;
1.1032    raeburn  13399:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   13400:         $thisfn=~s/\?.+$//;
                   13401:     }
1.268     www      13402:     return $thisfn;
                   13403: }
                   13404: 
                   13405: # ------------------------------------------------------------- Clutter up URLs
                   13406: 
                   13407: sub clutter {
                   13408:     my $thisfn='/'.&declutter(shift);
1.887     albertel 13409:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 13410: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      13411:        $thisfn='/res'.$thisfn; 
                   13412:     }
1.1031    raeburn  13413:     if ($thisfn !~m|^/adm|) {
                   13414: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 13415: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 13416: 	} else {
                   13417: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   13418: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 13419: 	    if ($embstyle eq 'ssi'
                   13420: 		|| ($embstyle eq 'hdn')
                   13421: 		|| ($embstyle eq 'rat')
                   13422: 		|| ($embstyle eq 'prv')
                   13423: 		|| ($embstyle eq 'ign')) {
                   13424: 		#do nothing with these
                   13425: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 13426: 		|| ($embstyle eq 'emb')
                   13427: 		|| ($embstyle eq 'wrp')) {
                   13428: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 13429: 	    } elsif ($embstyle eq 'unk'
                   13430: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 13431: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 13432: 	    } else {
1.718     www      13433: #		&logthis("Got a blank emb style");
1.695     albertel 13434: 	    }
1.694     albertel 13435: 	}
1.1343    raeburn  13436:     } elsif ($thisfn =~ m{^/adm/$match_domain/$match_courseid/\d+/ext\.tool$}) {
1.1298    raeburn  13437:         $thisfn='/adm/wrapper'.$thisfn;
1.694     albertel 13438:     }
1.31      www      13439:     return $thisfn;
1.12      www      13440: }
                   13441: 
1.787     albertel 13442: sub clutter_with_no_wrapper {
                   13443:     my $uri = &clutter(shift);
                   13444:     if ($uri =~ m-^/adm/-) {
                   13445: 	$uri =~ s-^/adm/wrapper/-/-;
                   13446: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   13447:     }
                   13448:     return $uri;
                   13449: }
                   13450: 
1.557     albertel 13451: sub freeze_escape {
                   13452:     my ($value)=@_;
                   13453:     if (ref($value)) {
                   13454: 	$value=&nfreeze($value);
                   13455: 	return '__FROZEN__'.&escape($value);
                   13456:     }
                   13457:     return &escape($value);
                   13458: }
                   13459: 
1.11      www      13460: 
1.557     albertel 13461: sub thaw_unescape {
                   13462:     my ($value)=@_;
                   13463:     if ($value =~ /^__FROZEN__/) {
                   13464: 	substr($value,0,10,undef);
                   13465: 	$value=&unescape($value);
                   13466: 	return &thaw($value);
                   13467:     }
                   13468:     return &unescape($value);
                   13469: }
                   13470: 
1.436     albertel 13471: sub correct_line_ends {
                   13472:     my ($result)=@_;
                   13473:     $$result =~s/\r\n/\n/mg;
                   13474:     $$result =~s/\r/\n/mg;
1.415     albertel 13475: }
1.1       albertel 13476: # ================================================================ Main Program
                   13477: 
1.184     www      13478: sub goodbye {
1.204     albertel 13479:    &logthis("Starting Shut down");
1.443     albertel 13480: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 13481:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 13482: #converted
1.599     albertel 13483: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 13484:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   13485: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   13486: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 13487: #1.1 only
1.870     albertel 13488: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   13489: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   13490: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   13491: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   13492:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 13493:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   13494:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      13495:    &flushcourselogs();
                   13496:    &logthis("Shutting down");
                   13497: }
                   13498: 
1.852     albertel 13499: sub get_dns {
1.1210    raeburn  13500:     my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
1.869     albertel 13501:     if (!$ignore_cache) {
                   13502: 	my ($content,$cached)=
                   13503: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   13504: 	if ($cached) {
1.1210    raeburn  13505: 	    &$func($content,$hashref);
1.869     albertel 13506: 	    return;
                   13507: 	}
                   13508:     }
                   13509: 
                   13510:     my %alldns;
1.1359    raeburn  13511:     open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13512:     foreach my $dns (<$config>) {
                   13513: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  13514:         my $line = $1;
                   13515:         my ($host,$protocol) = split(/:/,$line);
                   13516:         if ($protocol ne 'https') {
                   13517:             $protocol = 'http';
                   13518:         }
                   13519: 	$alldns{$host} = $protocol;
1.869     albertel 13520:     }
                   13521:     while (%alldns) {
1.1263    raeburn  13522: 	my ($dns) = sort { $b cmp $a } keys(%alldns);
1.979     raeburn  13523: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.1345    raeburn  13524:         my $response = &LONCAPA::LWPReq::makerequest('',$request,'',\%perlvar,30,0);
1.979     raeburn  13525:         delete($alldns{$dns});
1.852     albertel 13526: 	next if ($response->is_error());
                   13527: 	my @content = split("\n",$response->content);
1.1210    raeburn  13528: 	unless ($nocache) {
1.1219    raeburn  13529: 	    &do_cache_new('dns',$url,\@content,30*24*60*60);
1.1210    raeburn  13530: 	}
                   13531: 	&$func(\@content,$hashref);
1.869     albertel 13532: 	return;
1.852     albertel 13533:     }
                   13534:     close($config);
1.871     albertel 13535:     my $which = (split('/',$url))[3];
                   13536:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
1.1359    raeburn  13537:     open($config,"<","$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 13538:     my @content = <$config>;
1.1210    raeburn  13539:     &$func(\@content,$hashref);
                   13540:     return;
                   13541: }
                   13542: 
                   13543: # ------------------------------------------------------Get DNS checksums file
1.1211    raeburn  13544: sub parse_dns_checksums_tab {
1.1210    raeburn  13545:     my ($lines,$hashref) = @_;
1.1264    raeburn  13546:     my $lonhost = $perlvar{'lonHostID'};
                   13547:     my $machine_dom = &Apache::lonnet::host_domain($lonhost);
1.1210    raeburn  13548:     my $loncaparev = &get_server_loncaparev($machine_dom);
1.1264    raeburn  13549:     my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
                   13550:     my $webconfdir = '/etc/httpd/conf';
                   13551:     if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
                   13552:         $webconfdir = '/etc/apache2';
                   13553:     } elsif ($distro =~ /^sles(\d+)$/) {
                   13554:         if ($1 >= 10) {
                   13555:             $webconfdir = '/etc/apache2';
                   13556:         }
                   13557:     } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
                   13558:         if ($1 >= 10.0) {
                   13559:             $webconfdir = '/etc/apache2';
                   13560:         }
                   13561:     }
1.1210    raeburn  13562:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13563:     my (%chksum,%revnum);
                   13564:     if (ref($lines) eq 'ARRAY') {
                   13565:         chomp(@{$lines});
1.1238    raeburn  13566:         my $version = shift(@{$lines});
                   13567:         if ($version eq $release) {  
1.1210    raeburn  13568:             foreach my $line (@{$lines}) {
1.1238    raeburn  13569:                 my ($file,$version,$shasum) = split(/,/,$line);
1.1264    raeburn  13570:                 if ($file =~ m{^/etc/httpd/conf}) {
                   13571:                     if ($webconfdir eq '/etc/apache2') {
                   13572:                         $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
                   13573:                     }
                   13574:                 }
1.1238    raeburn  13575:                 $chksum{$file} = $shasum;
                   13576:                 $revnum{$file} = $version;
1.1210    raeburn  13577:             }
                   13578:             if (ref($hashref) eq 'HASH') {
                   13579:                 %{$hashref} = (
                   13580:                                 sums     => \%chksum,
                   13581:                                 versions => \%revnum,
                   13582:                               );
                   13583:             }
                   13584:         }
                   13585:     }
1.869     albertel 13586:     return;
1.852     albertel 13587: }
1.1210    raeburn  13588: 
                   13589: sub fetch_dns_checksums {
1.1238    raeburn  13590:     my %checksums;
                   13591:     my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
1.1260    raeburn  13592:     my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
1.1238    raeburn  13593:     my ($release,$timestamp) = split(/\-/,$loncaparev);
                   13594:     &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
1.1211    raeburn  13595:              \%checksums);
1.1210    raeburn  13596:     return \%checksums;
                   13597: }
                   13598: 
1.327     albertel 13599: # ------------------------------------------------------------ Read domain file
                   13600: {
1.852     albertel 13601:     my $loaded;
1.846     albertel 13602:     my %domain;
                   13603: 
1.852     albertel 13604:     sub parse_domain_tab {
                   13605: 	my ($lines) = @_;
                   13606: 	foreach my $line (@$lines) {
                   13607: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      13608: 
1.846     albertel 13609: 	    chomp($line);
1.852     albertel 13610: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 13611: 	    my %this_domain;
                   13612: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   13613: 			       'lang_def', 'city', 'longi', 'lati',
                   13614: 			       'primary') {
                   13615: 		$this_domain{$field} = shift(@elements);
                   13616: 	    }
                   13617: 	    $domain{$name} = \%this_domain;
1.852     albertel 13618: 	}
                   13619:     }
1.864     albertel 13620: 
                   13621:     sub reset_domain_info {
                   13622: 	undef($loaded);
                   13623: 	undef(%domain);
                   13624:     }
                   13625: 
1.852     albertel 13626:     sub load_domain_tab {
1.1293    raeburn  13627: 	my ($ignore_cache,$nocache) = @_;
                   13628: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
1.852     albertel 13629: 	my $fh;
1.1359    raeburn  13630: 	if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
1.852     albertel 13631: 	    my @lines = <$fh>;
                   13632: 	    &parse_domain_tab(\@lines);
1.448     albertel 13633: 	}
1.852     albertel 13634: 	close($fh);
                   13635: 	$loaded = 1;
1.327     albertel 13636:     }
1.846     albertel 13637: 
                   13638:     sub domain {
1.852     albertel 13639: 	&load_domain_tab() if (!$loaded);
                   13640: 
1.846     albertel 13641: 	my ($name,$what) = @_;
                   13642: 	return if ( !exists($domain{$name}) );
                   13643: 
                   13644: 	if (!$what) {
                   13645: 	    return $domain{$name}{'description'};
                   13646: 	}
                   13647: 	return $domain{$name}{$what};
                   13648:     }
1.974     raeburn  13649: 
                   13650:     sub domain_info {
                   13651:         &load_domain_tab() if (!$loaded);
                   13652:         return %domain;
                   13653:     }
                   13654: 
1.327     albertel 13655: }
                   13656: 
                   13657: 
1.1       albertel 13658: # ------------------------------------------------------------- Read hosts file
                   13659: {
1.838     albertel 13660:     my %hostname;
1.844     albertel 13661:     my %hostdom;
1.845     albertel 13662:     my %libserv;
1.852     albertel 13663:     my $loaded;
1.888     albertel 13664:     my %name_to_host;
1.1074    raeburn  13665:     my %internetdom;
1.1107    raeburn  13666:     my %LC_dns_serv;
1.852     albertel 13667: 
                   13668:     sub parse_hosts_tab {
                   13669: 	my ($file) = @_;
                   13670: 	foreach my $configline (@$file) {
                   13671: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  13672:             chomp($configline);
                   13673: 	    if ($configline =~ /^\^/) {
                   13674:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   13675:                     $LC_dns_serv{$1} = 1;
                   13676:                 }
                   13677:                 next;
                   13678:             }
1.1074    raeburn  13679: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 13680: 	    $name=~s/\s//g;
                   13681: 	    if ($id && $domain && $role && $name) {
1.1351    raeburn  13682:                 if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
                   13683:                     my $curr = $hostname{$id};
                   13684:                     my $skip;
                   13685:                     if (ref($name_to_host{$curr}) eq 'ARRAY') {
                   13686:                         if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
                   13687:                             $skip = 1;
                   13688:                         } else {
                   13689:                             @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
                   13690:                         }
                   13691:                     }
                   13692:                     unless ($skip) {
                   13693:                         push(@{$name_to_host{$name}},$id);
                   13694:                     }
                   13695:                 } else {
                   13696:                     push(@{$name_to_host{$name}},$id);
                   13697:                 }
1.852     albertel 13698: 		$hostname{$id}=$name;
                   13699: 		$hostdom{$id}=$domain;
                   13700: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  13701:                 if (defined($protocol)) {
                   13702:                     if ($protocol eq 'https') {
                   13703:                         $protocol{$id} = $protocol;
                   13704:                     } else {
                   13705:                         $protocol{$id} = 'http'; 
                   13706:                     }
1.968     raeburn  13707:                 } else {
1.969     raeburn  13708:                     $protocol{$id} = 'http';
1.968     raeburn  13709:                 }
1.1074    raeburn  13710:                 if (defined($intdom)) {
                   13711:                     $internetdom{$id} = $intdom;
                   13712:                 }
1.852     albertel 13713: 	    }
                   13714: 	}
                   13715:     }
1.864     albertel 13716:     
                   13717:     sub reset_hosts_info {
1.897     albertel 13718: 	&purge_remembered();
1.864     albertel 13719: 	&reset_domain_info();
                   13720: 	&reset_hosts_ip_info();
1.1339    raeburn  13721:         undef(%internetdom);
1.892     albertel 13722: 	undef(%name_to_host);
1.864     albertel 13723: 	undef(%hostname);
                   13724: 	undef(%hostdom);
                   13725: 	undef(%libserv);
                   13726: 	undef($loaded);
                   13727:     }
1.1       albertel 13728: 
1.852     albertel 13729:     sub load_hosts_tab {
1.1293    raeburn  13730: 	my ($ignore_cache,$nocache) = @_;
                   13731: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
1.1359    raeburn  13732: 	open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
1.852     albertel 13733: 	my @config = <$config>;
                   13734: 	&parse_hosts_tab(\@config);
                   13735: 	close($config);
                   13736: 	$loaded=1;
1.1       albertel 13737:     }
1.852     albertel 13738: 
1.838     albertel 13739:     sub hostname {
1.852     albertel 13740: 	&load_hosts_tab() if (!$loaded);
                   13741: 
1.838     albertel 13742: 	my ($lonid) = @_;
                   13743: 	return $hostname{$lonid};
                   13744:     }
1.845     albertel 13745: 
1.838     albertel 13746:     sub all_hostnames {
1.852     albertel 13747: 	&load_hosts_tab() if (!$loaded);
                   13748: 
1.838     albertel 13749: 	return %hostname;
                   13750:     }
1.845     albertel 13751: 
1.888     albertel 13752:     sub all_names {
1.1293    raeburn  13753:         my ($ignore_cache,$nocache) = @_;
                   13754: 	&load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
1.888     albertel 13755: 
                   13756: 	return %name_to_host;
                   13757:     }
                   13758: 
1.974     raeburn  13759:     sub all_host_domain {
                   13760:         &load_hosts_tab() if (!$loaded);
                   13761:         return %hostdom;
                   13762:     }
                   13763: 
1.1339    raeburn  13764:     sub all_host_intdom {
                   13765:         &load_hosts_tab() if (!$loaded);
                   13766:         return %internetdom;
                   13767:     }
                   13768: 
1.845     albertel 13769:     sub is_library {
1.852     albertel 13770: 	&load_hosts_tab() if (!$loaded);
                   13771: 
1.845     albertel 13772: 	return exists($libserv{$_[0]});
                   13773:     }
                   13774: 
                   13775:     sub all_library {
1.852     albertel 13776: 	&load_hosts_tab() if (!$loaded);
                   13777: 
1.845     albertel 13778: 	return %libserv;
                   13779:     }
                   13780: 
1.1062    droeschl 13781:     sub unique_library {
                   13782: 	#2x reverse removes all hostnames that appear more than once
                   13783:         my %unique = reverse &all_library();
                   13784:         return reverse %unique;
                   13785:     }
                   13786: 
1.841     albertel 13787:     sub get_servers {
1.852     albertel 13788: 	&load_hosts_tab() if (!$loaded);
                   13789: 
1.841     albertel 13790: 	my ($domain,$type) = @_;
                   13791: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   13792: 	                                          : %hostname;
                   13793: 	my %result;
1.842     albertel 13794: 	if (ref($domain) eq 'ARRAY') {
                   13795: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 13796: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 13797: 		    $result{$host} = $hostname;
                   13798: 		}
                   13799: 	    }
                   13800: 	} else {
                   13801: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   13802: 		if ($hostdom{$host} eq $domain) {
                   13803: 		    $result{$host} = $hostname;
                   13804: 		}
1.841     albertel 13805: 	    }
                   13806: 	}
                   13807: 	return %result;
                   13808:     }
1.845     albertel 13809: 
1.1062    droeschl 13810:     sub get_unique_servers {
                   13811:         my %unique = reverse &get_servers(@_);
                   13812: 	return reverse %unique;
                   13813:     }
                   13814: 
1.844     albertel 13815:     sub host_domain {
1.852     albertel 13816: 	&load_hosts_tab() if (!$loaded);
                   13817: 
1.844     albertel 13818: 	my ($lonid) = @_;
                   13819: 	return $hostdom{$lonid};
                   13820:     }
                   13821: 
1.841     albertel 13822:     sub all_domains {
1.852     albertel 13823: 	&load_hosts_tab() if (!$loaded);
                   13824: 
1.841     albertel 13825: 	my %seen;
                   13826: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   13827: 	return @uniq;
                   13828:     }
1.1074    raeburn  13829: 
                   13830:     sub internet_dom {
                   13831:         &load_hosts_tab() if (!$loaded);
                   13832: 
                   13833:         my ($lonid) = @_;
                   13834:         return $internetdom{$lonid};
                   13835:     }
1.1107    raeburn  13836: 
                   13837:     sub is_LC_dns {
                   13838:         &load_hosts_tab() if (!$loaded);
                   13839: 
                   13840:         my ($hostname) = @_;
                   13841:         return exists($LC_dns_serv{$hostname});
                   13842:     }
                   13843: 
1.1       albertel 13844: }
                   13845: 
1.847     albertel 13846: { 
                   13847:     my %iphost;
1.856     albertel 13848:     my %name_to_ip;
                   13849:     my %lonid_to_ip;
1.869     albertel 13850: 
1.847     albertel 13851:     sub get_hosts_from_ip {
                   13852: 	my ($ip) = @_;
                   13853: 	my %iphosts = &get_iphost();
                   13854: 	if (ref($iphosts{$ip})) {
                   13855: 	    return @{$iphosts{$ip}};
                   13856: 	}
                   13857: 	return;
1.839     albertel 13858:     }
1.864     albertel 13859:     
                   13860:     sub reset_hosts_ip_info {
                   13861: 	undef(%iphost);
                   13862: 	undef(%name_to_ip);
                   13863: 	undef(%lonid_to_ip);
                   13864:     }
1.856     albertel 13865: 
                   13866:     sub get_host_ip {
                   13867: 	my ($lonid) = @_;
                   13868: 	if (exists($lonid_to_ip{$lonid})) {
                   13869: 	    return $lonid_to_ip{$lonid};
                   13870: 	}
                   13871: 	my $name=&hostname($lonid);
                   13872:    	my $ip = gethostbyname($name);
                   13873: 	return if (!$ip || length($ip) ne 4);
                   13874: 	$ip=inet_ntoa($ip);
                   13875: 	$name_to_ip{$name}   = $ip;
                   13876: 	$lonid_to_ip{$lonid} = $ip;
                   13877: 	return $ip;
                   13878:     }
1.847     albertel 13879:     
                   13880:     sub get_iphost {
1.1293    raeburn  13881: 	my ($ignore_cache,$nocache) = @_;
1.894     albertel 13882: 
1.869     albertel 13883: 	if (!$ignore_cache) {
                   13884: 	    if (%iphost) {
                   13885: 		return %iphost;
                   13886: 	    }
                   13887: 	    my ($ip_info,$cached)=
                   13888: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   13889: 	    if ($cached) {
                   13890: 		%iphost      = %{$ip_info->[0]};
                   13891: 		%name_to_ip  = %{$ip_info->[1]};
                   13892: 		%lonid_to_ip = %{$ip_info->[2]};
                   13893: 		return %iphost;
                   13894: 	    }
                   13895: 	}
1.894     albertel 13896: 
                   13897: 	# get yesterday's info for fallback
                   13898: 	my %old_name_to_ip;
                   13899: 	my ($ip_info,$cached)=
                   13900: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   13901: 	if ($cached) {
                   13902: 	    %old_name_to_ip = %{$ip_info->[1]};
                   13903: 	}
                   13904: 
1.1293    raeburn  13905: 	my %name_to_host = &all_names($ignore_cache,$nocache);
1.888     albertel 13906: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 13907: 	    my $ip;
                   13908: 	    if (!exists($name_to_ip{$name})) {
                   13909: 		$ip = gethostbyname($name);
                   13910: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 13911: 		    if (defined($old_name_to_ip{$name})) {
                   13912: 			$ip = $old_name_to_ip{$name};
                   13913: 			&logthis("Can't find $name defaulting to old $ip");
                   13914: 		    } else {
                   13915: 			&logthis("Name $name no IP found");
                   13916: 			next;
                   13917: 		    }
                   13918: 		} else {
                   13919: 		    $ip=inet_ntoa($ip);
1.847     albertel 13920: 		}
                   13921: 		$name_to_ip{$name} = $ip;
                   13922: 	    } else {
                   13923: 		$ip = $name_to_ip{$name};
1.653     albertel 13924: 	    }
1.888     albertel 13925: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   13926: 		$lonid_to_ip{$id} = $ip;
                   13927: 	    }
                   13928: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 13929: 	}
1.1293    raeburn  13930:         unless ($nocache) {
                   13931: 	    &do_cache_new('iphost','iphost',
                   13932: 		          [\%iphost,\%name_to_ip,\%lonid_to_ip],
                   13933: 		          48*60*60);
                   13934:         }
1.869     albertel 13935: 
1.847     albertel 13936: 	return %iphost;
1.598     albertel 13937:     }
                   13938: 
1.992     raeburn  13939:     #
                   13940:     #  Given a DNS returns the loncapa host name for that DNS 
                   13941:     # 
                   13942:     sub host_from_dns {
                   13943:         my ($dns) = @_;
                   13944:         my @hosts;
                   13945:         my $ip;
                   13946: 
1.993     raeburn  13947:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  13948:             $ip = $name_to_ip{$dns};
                   13949:         }
                   13950:         if (!$ip) {
                   13951:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   13952:             if (length($ip) == 4) { 
                   13953: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   13954:             }
                   13955:         }
                   13956:         if ($ip) {
                   13957: 	    @hosts = get_hosts_from_ip($ip);
                   13958: 	    return $hosts[0];
                   13959:         }
                   13960:         return undef;
1.986     foxr     13961:     }
1.992     raeburn  13962: 
1.1074    raeburn  13963:     sub get_internet_names {
                   13964:         my ($lonid) = @_;
                   13965:         return if ($lonid eq '');
                   13966:         my ($idnref,$cached)=
                   13967:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   13968:         if ($cached) {
                   13969:             return $idnref;
                   13970:         }
                   13971:         my $ip = &get_host_ip($lonid);
                   13972:         my @hosts = &get_hosts_from_ip($ip);
                   13973:         my %iphost = &get_iphost();
                   13974:         my (@idns,%seen);
                   13975:         foreach my $id (@hosts) {
                   13976:             my $dom = &host_domain($id);
                   13977:             my $prim_id = &domain($dom,'primary');
                   13978:             my $prim_ip = &get_host_ip($prim_id);
                   13979:             next if ($seen{$prim_ip});
                   13980:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   13981:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   13982:                     my $intdom = &internet_dom($id);
                   13983:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   13984:                         push(@idns,$intdom);
                   13985:                     }
                   13986:                 }
                   13987:             }
                   13988:             $seen{$prim_ip} = 1;
                   13989:         }
1.1219    raeburn  13990:         return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
1.1074    raeburn  13991:     }
                   13992: 
1.986     foxr     13993: }
                   13994: 
1.1079    raeburn  13995: sub all_loncaparevs {
1.1249    raeburn  13996:     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  13997: }
                   13998: 
1.1227    raeburn  13999: # ---------------------------------------------------------- Read loncaparev table
                   14000: {
                   14001:     sub load_loncaparevs { 
                   14002:         if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
1.1359    raeburn  14003:             if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
1.1227    raeburn  14004:                 while (my $configline=<$config>) {
                   14005:                     chomp($configline);
                   14006:                     my ($hostid,$loncaparev)=split(/:/,$configline);
                   14007:                     $loncaparevs{$hostid}=$loncaparev;
                   14008:                 }
                   14009:                 close($config);
                   14010:             }
                   14011:         }
                   14012:     }
                   14013: }
                   14014: 
                   14015: # ---------------------------------------------------------- Read serverhostID table
                   14016: {
                   14017:     sub load_serverhomeIDs {
                   14018:         if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
1.1359    raeburn  14019:             if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
1.1227    raeburn  14020:                 while (my $configline=<$config>) {
                   14021:                     chomp($configline);
                   14022:                     my ($name,$id)=split(/:/,$configline);
                   14023:                     $serverhomeIDs{$name}=$id;
                   14024:                 }
                   14025:                 close($config);
                   14026:             }
                   14027:         }
                   14028:     }
                   14029: }
                   14030: 
                   14031: 
1.862     albertel 14032: BEGIN {
                   14033: 
                   14034: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   14035:     unless ($readit) {
                   14036: {
                   14037:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   14038:     %perlvar = (%perlvar,%{$configvars});
                   14039: }
                   14040: 
                   14041: 
1.1       albertel 14042: # ------------------------------------------------------ Read spare server file
                   14043: {
1.1359    raeburn  14044:     open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 14045: 
                   14046:     while (my $configline=<$config>) {
                   14047:        chomp($configline);
1.284     matthew  14048:        if ($configline) {
1.784     albertel 14049: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 14050: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 14051: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 14052:        }
                   14053:     }
1.448     albertel 14054:     close($config);
1.1       albertel 14055: }
1.11      www      14056: # ------------------------------------------------------------ Read permissions
                   14057: {
1.1359    raeburn  14058:     open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
1.11      www      14059: 
                   14060:     while (my $configline=<$config>) {
1.448     albertel 14061: 	chomp($configline);
                   14062: 	if ($configline) {
                   14063: 	    my ($role,$perm)=split(/ /,$configline);
                   14064: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   14065: 	}
1.11      www      14066:     }
1.448     albertel 14067:     close($config);
1.11      www      14068: }
                   14069: 
                   14070: # -------------------------------------------- Read plain texts for permissions
                   14071: {
1.1359    raeburn  14072:     open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      14073: 
                   14074:     while (my $configline=<$config>) {
1.448     albertel 14075: 	chomp($configline);
                   14076: 	if ($configline) {
1.742     raeburn  14077: 	    my ($short,@plain)=split(/:/,$configline);
                   14078:             %{$prp{$short}} = ();
                   14079: 	    if (@plain > 0) {
                   14080:                 $prp{$short}{'std'} = $plain[0];
                   14081:                 for (my $i=1; $i<@plain; $i++) {
                   14082:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   14083:                 }
                   14084:             }
1.448     albertel 14085: 	}
1.135     www      14086:     }
1.448     albertel 14087:     close($config);
1.135     www      14088: }
                   14089: 
                   14090: # ---------------------------------------------------------- Read package table
                   14091: {
1.1359    raeburn  14092:     open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
1.135     www      14093: 
                   14094:     while (my $configline=<$config>) {
1.483     albertel 14095: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 14096: 	chomp($configline);
                   14097: 	my ($short,$plain)=split(/:/,$configline);
                   14098: 	my ($pack,$name)=split(/\&/,$short);
                   14099: 	if ($plain ne '') {
                   14100: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   14101: 	    $packagetab{$short}=$plain; 
                   14102: 	}
1.11      www      14103:     }
1.448     albertel 14104:     close($config);
1.329     matthew  14105: }
                   14106: 
1.1073    raeburn  14107: # ---------------------------------------------------------- Read loncaparev table
1.1227    raeburn  14108: 
                   14109: &load_loncaparevs();
1.1073    raeburn  14110: 
1.1074    raeburn  14111: # ---------------------------------------------------------- Read serverhostID table
                   14112: 
1.1227    raeburn  14113: &load_serverhomeIDs();
                   14114: 
                   14115: # ---------------------------------------------------------- Read releaseslist XML
1.1079    raeburn  14116: {
                   14117:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   14118:     if (-e $file) {
                   14119:         my $parser = HTML::LCParser->new($file);
                   14120:         while (my $token = $parser->get_token()) {
                   14121:             if ($token->[0] eq 'S') {
                   14122:                 my $item = $token->[1];
                   14123:                 my $name = $token->[2]{'name'};
                   14124:                 my $value = $token->[2]{'value'};
1.1285    raeburn  14125:                 my $valuematch = $token->[2]{'valuematch'};
1.1303    raeburn  14126:                 my $namematch = $token->[2]{'namematch'};
                   14127:                 if ($item eq 'parameter') {
                   14128:                     if (($namematch ne '') || (($name ne '') && ($value ne '' || $valuematch ne ''))) {
                   14129:                         my $release = $parser->get_text();
                   14130:                         $release =~ s/(^\s*|\s*$ )//gx;
                   14131:                         $needsrelease{$item.':'.$name.':'.$value.':'.$valuematch.':'.$namematch} = $release;
                   14132:                     }
                   14133:                 } elsif ($item ne '' && $name ne '') {
1.1079    raeburn  14134:                     my $release = $parser->get_text();
                   14135:                     $release =~ s/(^\s*|\s*$ )//gx;
1.1303    raeburn  14136:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
1.1079    raeburn  14137:                 }
                   14138:             }
                   14139:         }
                   14140:     }
1.1073    raeburn  14141: }
                   14142: 
1.1138    raeburn  14143: # ---------------------------------------------------------- Read managers table
                   14144: {
                   14145:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
1.1359    raeburn  14146:         if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
1.1138    raeburn  14147:             while (my $configline=<$config>) {
                   14148:                 chomp($configline);
                   14149:                 next if ($configline =~ /^\#/);
                   14150:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   14151:                     $managerstab{$configline} = 1;
                   14152:                 }
                   14153:             }
                   14154:             close($config);
                   14155:         }
                   14156:     }
                   14157: }
                   14158: 
1.329     matthew  14159: # ------------- set up temporary directory
                   14160: {
1.1117    foxr     14161:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  14162: 
1.11      www      14163: }
                   14164: 
1.794     albertel 14165: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   14166: 				'compress_threshold'=> 20_000,
                   14167:  			        });
1.185     www      14168: 
1.281     www      14169: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      14170: $dumpcount=0;
1.958     www      14171: $locknum=0;
1.22      www      14172: 
1.163     harris41 14173: &logtouch();
1.672     albertel 14174: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      14175: $readit=1;
1.564     albertel 14176:     {
                   14177: 	use integer;
                   14178: 	my $test=(2**32)+1;
1.568     albertel 14179: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 14180: 	&logthis(" Detected 64bit platform ($_64bit)");
                   14181:     }
1.195     www      14182: }
1.1       albertel 14183: }
1.179     www      14184: 
1.1       albertel 14185: 1;
1.191     harris41 14186: __END__
                   14187: 
1.243     albertel 14188: =pod
                   14189: 
1.191     harris41 14190: =head1 NAME
                   14191: 
1.243     albertel 14192: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 14193: 
                   14194: =head1 SYNOPSIS
                   14195: 
1.243     albertel 14196: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 14197: 
                   14198:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   14199: 
1.243     albertel 14200: Common parameters:
                   14201: 
                   14202: =over 4
                   14203: 
                   14204: =item *
                   14205: 
                   14206: $uname : an internal username (if $cname expecting a course Id specifically)
                   14207: 
                   14208: =item *
                   14209: 
                   14210: $udom : a domain (if $cdom expecting a course's domain specifically)
                   14211: 
                   14212: =item *
                   14213: 
                   14214: $symb : a resource instance identifier
                   14215: 
                   14216: =item *
                   14217: 
                   14218: $namespace : the name of a .db file that contains the data needed or
                   14219: being set.
                   14220: 
                   14221: =back
                   14222: 
1.394     bowersj2 14223: =head1 OVERVIEW
1.191     harris41 14224: 
1.394     bowersj2 14225: lonnet provides subroutines which interact with the
                   14226: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   14227: about classes, users, and resources.
1.243     albertel 14228: 
                   14229: For many of these objects you can also use this to store data about
                   14230: them or modify them in various ways.
1.191     harris41 14231: 
1.394     bowersj2 14232: =head2 Symbs
1.191     harris41 14233: 
1.394     bowersj2 14234: To identify a specific instance of a resource, LON-CAPA uses symbols
                   14235: or "symbs"X<symb>. These identifiers are built from the URL of the
                   14236: map, the resource number of the resource in the map, and the URL of
                   14237: the resource itself. The latter is somewhat redundant, but might help
                   14238: if maps change.
                   14239: 
                   14240: An example is
                   14241: 
                   14242:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   14243: 
                   14244: The respective map entry is
                   14245: 
                   14246:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   14247:   title="Problem 2">
                   14248:  </resource>
                   14249: 
                   14250: Symbs are used by the random number generator, as well as to store and
                   14251: restore data specific to a certain instance of for example a problem.
                   14252: 
                   14253: =head2 Storing And Retrieving Data
                   14254: 
                   14255: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   14256: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   14257: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   14258: is is the non-critical message twin of cstore. These functions are for
                   14259: handlers to store a perl hash to a user's permanent data space in an
                   14260: easy manner, and to retrieve it again on another call. It is expected
                   14261: that a handler would use this once at the beginning to retrieve data,
                   14262: and then again once at the end to send only the new data back.
                   14263: 
                   14264: The data is stored in the user's data directory on the user's
                   14265: homeserver under the ID of the course.
                   14266: 
                   14267: The hash that is returned by restore will have all of the previous
                   14268: value for all of the elements of the hash.
                   14269: 
                   14270: Example:
                   14271: 
                   14272:  #creating a hash
                   14273:  my %hash;
                   14274:  $hash{'foo'}='bar';
                   14275: 
                   14276:  #storing it
                   14277:  &Apache::lonnet::cstore(\%hash);
                   14278: 
                   14279:  #changing a value
                   14280:  $hash{'foo'}='notbar';
                   14281: 
                   14282:  #adding a new value
                   14283:  $hash{'bar'}='foo';
                   14284:  &Apache::lonnet::cstore(\%hash);
                   14285: 
                   14286:  #retrieving the hash
                   14287:  my %history=&Apache::lonnet::restore();
                   14288: 
                   14289:  #print the hash
                   14290:  foreach my $key (sort(keys(%history))) {
                   14291:    print("\%history{$key} = $history{$key}");
                   14292:  }
                   14293: 
                   14294: Will print out:
1.191     harris41 14295: 
1.394     bowersj2 14296:  %history{1:foo} = bar
                   14297:  %history{1:keys} = foo:timestamp
                   14298:  %history{1:timestamp} = 990455579
                   14299:  %history{2:bar} = foo
                   14300:  %history{2:foo} = notbar
                   14301:  %history{2:keys} = foo:bar:timestamp
                   14302:  %history{2:timestamp} = 990455580
                   14303:  %history{bar} = foo
                   14304:  %history{foo} = notbar
                   14305:  %history{timestamp} = 990455580
                   14306:  %history{version} = 2
                   14307: 
                   14308: Note that the special hash entries C<keys>, C<version> and
                   14309: C<timestamp> were added to the hash. C<version> will be equal to the
                   14310: total number of versions of the data that have been stored. The
                   14311: C<timestamp> attribute will be the UNIX time the hash was
                   14312: stored. C<keys> is available in every historical section to list which
                   14313: keys were added or changed at a specific historical revision of a
                   14314: hash.
                   14315: 
                   14316: B<Warning>: do not store the hash that restore returns directly. This
                   14317: will cause a mess since it will restore the historical keys as if the
                   14318: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 14319: 
1.394     bowersj2 14320: Calling convention:
1.191     harris41 14321: 
1.1225    raeburn  14322:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
1.1269    raeburn  14323:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
1.191     harris41 14324: 
1.394     bowersj2 14325: For more detailed information, see lonnet specific documentation.
1.191     harris41 14326: 
1.394     bowersj2 14327: =head1 RETURN MESSAGES
1.191     harris41 14328: 
1.394     bowersj2 14329: =over 4
1.191     harris41 14330: 
1.394     bowersj2 14331: =item * B<con_lost>: unable to contact remote host
1.191     harris41 14332: 
1.394     bowersj2 14333: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   14334: when the connection is brought back up
1.191     harris41 14335: 
1.394     bowersj2 14336: =item * B<con_failed>: unable to contact remote host and unable to save message
                   14337: for later delivery
1.191     harris41 14338: 
1.967     bisitz   14339: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 14340: 
1.394     bowersj2 14341: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 14342: that was requested
1.191     harris41 14343: 
1.243     albertel 14344: =back
1.191     harris41 14345: 
1.243     albertel 14346: =head1 PUBLIC SUBROUTINES
1.191     harris41 14347: 
1.243     albertel 14348: =head2 Session Environment Functions
1.191     harris41 14349: 
1.243     albertel 14350: =over 4
1.191     harris41 14351: 
1.394     bowersj2 14352: =item * 
                   14353: X<appenv()>
1.949     raeburn  14354: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 14355: the user envirnoment file, and will be restored for each access this
1.620     albertel 14356: user makes during this session, also modifies the %env for the current
1.949     raeburn  14357: process. Optional rolesarrayref - if defined contains a reference to an array
                   14358: of roles which are exempt from the restriction on modifying user.role entries 
                   14359: in the user's environment.db and in %env.    
1.191     harris41 14360: 
                   14361: =item *
1.394     bowersj2 14362: X<delenv()>
1.987     raeburn  14363: B<delenv($delthis,$regexp)>: removes all items from the session
                   14364: environment file that begin with $delthis. If the 
                   14365: optional second arg - $regexp - is true, $delthis is treated as a 
                   14366: regular expression, otherwise \Q$delthis\E is used. 
                   14367: The values are also deleted from the current processes %env.
1.191     harris41 14368: 
1.795     albertel 14369: =item * get_env_multiple($name) 
                   14370: 
                   14371: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   14372: values may be defined and end up as an array ref.
                   14373: 
                   14374: returns an array of values
                   14375: 
1.243     albertel 14376: =back
                   14377: 
                   14378: =head2 User Information
1.191     harris41 14379: 
1.243     albertel 14380: =over 4
1.191     harris41 14381: 
                   14382: =item *
1.394     bowersj2 14383: X<queryauthenticate()>
                   14384: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 14385: authentication scheme
                   14386: 
                   14387: =item *
1.394     bowersj2 14388: X<authenticate()>
1.1073    raeburn  14389: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 14390: authenticate user from domain's lib servers (first use the current
                   14391: one). C<$upass> should be the users password.
1.1073    raeburn  14392: $checkdefauth is optional (value is 1 if a check should be made to
                   14393:    authenticate user using default authentication method, and allow
                   14394:    account creation if username does not have account in the domain).
                   14395: $clientcancheckhost is optional (value is 1 if checking whether the
                   14396:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 14397: 
                   14398: =item *
1.394     bowersj2 14399: X<homeserver()>
                   14400: B<homeserver($uname,$udom)>: find the server which has
                   14401: the user's directory and files (there must be only one), this caches
                   14402: the answer, and also caches if there is a borken connection.
1.191     harris41 14403: 
                   14404: =item *
1.394     bowersj2 14405: X<idget()>
1.1300    raeburn  14406: B<idget($udom,$idsref,$namespace)>: find the usernames behind either 
                   14407: a list of student/employee IDs or clicker IDs
                   14408: (student/employee IDs are a unique resource in a domain, there must be 
                   14409: only 1 ID per username, and only 1 username per ID in a specific domain).
                   14410: clickerIDs are not necessarily unique, as students might share clickers.
                   14411: (returns hash: id=>name,id=>name)
1.191     harris41 14412: 
                   14413: =item *
1.394     bowersj2 14414: X<idrget()>
                   14415: B<idrget($udom,@unames)>: find the IDs behind a list of
                   14416: usernames (returns hash: name=>id,name=>id)
1.191     harris41 14417: 
                   14418: =item *
1.394     bowersj2 14419: X<idput()>
1.1300    raeburn  14420: B<idput($udom,$idsref,$uhome,$namespace)>: store away a list of 
                   14421: names and associated student/employee IDs or clicker IDs.
                   14422: 
                   14423: =item *
                   14424: X<iddel()>
                   14425: B<iddel($udom,$idshashref,$uhome,$namespace)>: delete unwanted 
                   14426: student/employee ID or clicker ID username look-ups from domain.
                   14427: The homeserver ($uhome) and namespace ($namespace) are optional.
                   14428: If no $uhome is provided, it will be determined usig &homeserver()
                   14429: for each user.  If no $namespace is provided, the default is ids.
                   14430: 
                   14431: =item *
                   14432: X<updateclickers()>
                   14433: B<updateclickers($udom,$action,$idshashref,$uhome,$critical)>: update 
                   14434: clicker ID-to-username look-ups in clickers.db on library server.
                   14435: Permitted actions are add or del (i.e., add or delete). The 
                   14436: clickers.db contains clickerID as keys (escaped), and each corresponding
                   14437: value is an escaped comma-separated list of usernames (for whom the
                   14438: library server is the homeserver), who registered that particular ID.
                   14439: If $critical is true, the update will be sent via &critical, otherwise
                   14440: &reply() will be used.
1.191     harris41 14441: 
                   14442: =item *
1.394     bowersj2 14443: X<rolesinit()>
1.1169    droeschl 14444: B<rolesinit($udom,$username)>: get user privileges.
                   14445: returns user role, first access and timer interval hashes
1.243     albertel 14446: 
                   14447: =item *
1.1171    droeschl 14448: X<privileged()>
                   14449: B<privileged($username,$domain)>: returns a true if user has a
                   14450: privileged and active role (i.e. su or dc), false otherwise.
                   14451: 
                   14452: =item *
1.551     albertel 14453: X<getsection()>
                   14454: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 14455: course $cname, return section name/number or '' for "not in course"
                   14456: and '-1' for "no section"
                   14457: 
                   14458: =item *
1.394     bowersj2 14459: X<userenvironment()>
                   14460: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 14461: passed in @what from the requested user's environment, returns a hash
                   14462: 
1.858     raeburn  14463: =item * 
                   14464: X<userlog_query()>
1.859     albertel 14465: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   14466: activity.log file. %filters defines filters applied when parsing the
                   14467: log file. These can be start or end timestamps, or the type of action
                   14468: - log to look for Login or Logout events, check for Checkin or
                   14469: Checkout, role for role selection. The response is in the form
                   14470: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   14471: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  14472: 
1.243     albertel 14473: =back
                   14474: 
                   14475: =head2 User Roles
                   14476: 
                   14477: =over 4
                   14478: 
                   14479: =item *
                   14480: 
1.1284    raeburn  14481: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege; 
                   14482: returns codes for allowed actions.
                   14483: 
                   14484: The first argument is required, all others are optional.
                   14485: 
                   14486: $priv is the privilege being checked.
                   14487: $uri contains additional information about what is being checked for access (e.g.,
                   14488: URL, course ID etc.). 
                   14489: $symb is the unique resource instance identifier in a course; if needed,
                   14490: but not provided, it will be retrieved via a call to &symbread(). 
                   14491: $role is the role for which a priv is being checked (only used if priv is evb). 
                   14492: $clientip is the user's IP address (only used when checking for access to portfolio 
                   14493: files).
                   14494: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This 
                   14495: prevents recursive calls to &allowed.
                   14496: 
1.243     albertel 14497:  F: full access
                   14498:  U,I,K: authentication modes (cxx only)
                   14499:  '': forbidden
                   14500:  1: user needs to choose course
                   14501:  2: browse allowed
1.766     albertel 14502:  A: passphrase authentication needed
1.1284    raeburn  14503:  B: access temporarily blocked because of a blocking event in a course.
1.243     albertel 14504: 
                   14505: =item *
                   14506: 
1.1192    raeburn  14507: constructaccess($url,$setpriv) : check for access to construction space URL
                   14508: 
                   14509: See if the owner domain and name in the URL match those in the
                   14510: expected environment.  If so, return three element list
                   14511: ($ownername,$ownerdomain,$ownerhome).
                   14512: 
                   14513: Otherwise return the null string.
                   14514: 
                   14515: If second argument 'setpriv' is true, it assigns the privileges,
                   14516: and returns the same three element list, unless the owner has
                   14517: blocked "ad hoc" Domain Coordinator access to the Author Space,
                   14518: in which case the null string is returned.
                   14519: 
                   14520: =item *
                   14521: 
1.1326    raeburn  14522: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
                   14523: define a custom role rolename set privileges in format of lonTabs/roles.tab
                   14524: for system, domain, and course level. $uname and $udom are optional (current
                   14525: user's username and domain will be used when either of $uname or $udom are absent.
1.243     albertel 14526: 
                   14527: =item *
                   14528: 
1.988     raeburn  14529: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   14530: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  14531: $type is Course (default) or Community.
1.988     raeburn  14532: If $forcedefault evaluates to true, text returned will be default 
                   14533: text for $type. Otherwise, if this is a course, the text returned 
                   14534: will be a custom name for the role (if defined in the course's 
                   14535: environment).  If no custom name is defined the default is returned.
                   14536:    
1.832     raeburn  14537: =item *
                   14538: 
1.1219    raeburn  14539: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
1.858     raeburn  14540: All arguments are optional. Returns a hash of a roles, either for
                   14541: co-author/assistant author roles for a user's Construction Space
1.906     albertel 14542: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  14543: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   14544: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   14545: For each key, value is set to colon-separated start and end times for
                   14546: the role.  If no username and domain are specified, will default to
1.934     raeburn  14547: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  14548: of role statuses (active, future or previous), roles 
                   14549: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   14550: to restrict the list of roles reported. If no array ref is 
                   14551: provided for types, will default to return only active roles.
1.834     albertel 14552: 
1.1195    raeburn  14553: =item *
                   14554: 
                   14555: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
1.1196    raeburn  14556: user: $uname:$udom has a role in the course: $cdom_$cnum. 
                   14557: 
                   14558: Additional optional arguments are: $type (if role checking is to be restricted 
                   14559: to certain user status types -- previous (expired roles), active (currently
1.1195    raeburn  14560: available roles) or future (roles available in the future), and
                   14561: $hideprivileged -- if true will not report course roles for users who
1.1219    raeburn  14562: have active Domain Coordinator role in course's domain or in additional
                   14563: domains (specified in 'Domains to check for privileged users' in course
                   14564: environment -- set via:  Course Settings -> Classlists and staff listing).
                   14565: 
                   14566: =item *
                   14567: 
                   14568: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
                   14569: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
                   14570: $possdomains and $possroles are optional array refs -- to domains to check and
                   14571: roles to check.  If $possdomains is not specified, a dump will be done of the
                   14572: users' roles.db to check for a dc or su role in any domain. This can be
                   14573: time consuming if &privileged is called repeatedly (e.g., when displaying a
                   14574: classlist), so in such cases, supplying a $possdomains array is preferred, as
                   14575: this then allows &privileged_by_domain() to be used, which caches the identity
                   14576: of privileged users, eliminating the need for repeated calls to &dump().
                   14577: 
                   14578: =item *
                   14579: 
                   14580: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
                   14581: where the outer hash keys are domains specified in the $possdomains array ref,
                   14582: next inner hash keys are privileged roles specified in the $roles array ref,
                   14583: and the innermost hash contains key = value pairs for username:domain = end:start
                   14584: for active or future "privileged" users with that role in that domain. To avoid
                   14585: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
                   14586: innerhash are cached using priv_$role and $dom as the identifiers.
1.1195    raeburn  14587: 
1.243     albertel 14588: =back
                   14589: 
                   14590: =head2 User Modification
                   14591: 
                   14592: =over 4
                   14593: 
                   14594: =item *
                   14595: 
1.957     raeburn  14596: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 14597: user for the level given by URL.  Optional start and end dates (leave empty
                   14598: string or zero for "no date")
1.191     harris41 14599: 
                   14600: =item *
                   14601: 
1.243     albertel 14602: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   14603: change a users, password, possible return values are: ok,
                   14604: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   14605: refused
1.191     harris41 14606: 
                   14607: =item *
                   14608: 
1.243     albertel 14609: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 14610: 
                   14611: =item *
                   14612: 
1.1058    raeburn  14613: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   14614:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   14615: 
                   14616: will update user information (firstname,middlename,lastname,generation,
                   14617: permanentemail), and if forceid is true, student/employee ID also.
                   14618: A user's institutional affiliation(s) can also be updated.
                   14619: User information fields will not be overwritten with empty entries 
                   14620: unless the field is included in the $candelete array reference.
                   14621: This array is included when a single user is modified via "Manage Users",
                   14622: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 14623: 
                   14624: =item *
                   14625: 
1.286     matthew  14626: modifystudent
                   14627: 
1.957     raeburn  14628: modify a student's enrollment and identification information.
1.1235    raeburn  14629: The course id is resolved based on the current user's environment.  
                   14630: This means the invoking user must be a course coordinator or otherwise
1.286     matthew  14631: associated with a course.
                   14632: 
1.297     matthew  14633: This call is essentially a wrapper for lonnet::modifyuser and
                   14634: lonnet::modify_student_enrollment
1.286     matthew  14635: 
                   14636: Inputs: 
                   14637: 
                   14638: =over 4
                   14639: 
1.957     raeburn  14640: =item B<$udom> Student's loncapa domain
1.286     matthew  14641: 
1.957     raeburn  14642: =item B<$uname> Student's loncapa login name
1.286     matthew  14643: 
1.964     bisitz   14644: =item B<$uid> Student/Employee ID
1.286     matthew  14645: 
1.957     raeburn  14646: =item B<$umode> Student's authentication mode
1.286     matthew  14647: 
1.957     raeburn  14648: =item B<$upass> Student's password
1.286     matthew  14649: 
1.957     raeburn  14650: =item B<$first> Student's first name
1.286     matthew  14651: 
1.957     raeburn  14652: =item B<$middle> Student's middle name
1.286     matthew  14653: 
1.957     raeburn  14654: =item B<$last> Student's last name
1.286     matthew  14655: 
1.957     raeburn  14656: =item B<$gene> Student's generation
1.286     matthew  14657: 
1.957     raeburn  14658: =item B<$usec> Student's section in course
1.286     matthew  14659: 
                   14660: =item B<$end> Unix time of the roles expiration
                   14661: 
                   14662: =item B<$start> Unix time of the roles start date
                   14663: 
                   14664: =item B<$forceid> If defined, allow $uid to be changed
                   14665: 
                   14666: =item B<$desiredhome> server to use as home server for student
                   14667: 
1.957     raeburn  14668: =item B<$email> Student's permanent e-mail address
                   14669: 
                   14670: =item B<$type> Type of enrollment (auto or manual)
                   14671: 
1.963     raeburn  14672: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   14673: 
                   14674: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  14675: 
1.963     raeburn  14676: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  14677: 
1.963     raeburn  14678: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  14679: 
1.1216    raeburn  14680: =item B<$inststatus> institutional status of user - : separated string of escaped status types
                   14681: 
                   14682: =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  14683: 
1.286     matthew  14684: =back
1.297     matthew  14685: 
                   14686: =item *
                   14687: 
                   14688: modify_student_enrollment
                   14689: 
1.1235    raeburn  14690: Change a student's enrollment status in a class.  The environment variable
1.297     matthew  14691: 'role.request.course' must be defined for this function to proceed.
                   14692: 
                   14693: Inputs:
                   14694: 
                   14695: =over 4
                   14696: 
1.1235    raeburn  14697: =item $udom, student's domain
1.297     matthew  14698: 
1.1235    raeburn  14699: =item $uname, student's name
1.297     matthew  14700: 
1.1235    raeburn  14701: =item $uid, student's user id
1.297     matthew  14702: 
1.1235    raeburn  14703: =item $first, student's first name
1.297     matthew  14704: 
                   14705: =item $middle
                   14706: 
                   14707: =item $last
                   14708: 
                   14709: =item $gene
                   14710: 
                   14711: =item $usec
                   14712: 
                   14713: =item $end
                   14714: 
                   14715: =item $start
                   14716: 
1.957     raeburn  14717: =item $type
                   14718: 
                   14719: =item $locktype
                   14720: 
                   14721: =item $cid
                   14722: 
                   14723: =item $selfenroll
                   14724: 
                   14725: =item $context
                   14726: 
1.1216    raeburn  14727: =item $credits, number of credits student will earn from this class
                   14728: 
1.1314    raeburn  14729: =item $instsec, institutional course section code for student
                   14730: 
1.297     matthew  14731: =back
                   14732: 
1.191     harris41 14733: 
                   14734: =item *
                   14735: 
1.243     albertel 14736: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   14737: custom role; give a custom role to a user for the level given by URL.  Specify
                   14738: name and domain of role author, and role name
1.191     harris41 14739: 
                   14740: =item *
                   14741: 
1.243     albertel 14742: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 14743: 
                   14744: =item *
                   14745: 
1.243     albertel 14746: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   14747: 
                   14748: =back
                   14749: 
                   14750: =head2 Course Infomation
                   14751: 
                   14752: =over 4
1.191     harris41 14753: 
                   14754: =item *
                   14755: 
1.1118    foxr     14756: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 14757: specified course id, including all environment settings for the
                   14758: course, the description of the course will be in the hash under the
                   14759: key 'description'
1.191     harris41 14760: 
1.1118    foxr     14761: $options is an optional parameter that if supplied is a hash reference that controls
                   14762: what how this function works.  It has the following key/values:
                   14763: 
                   14764: =over 4
                   14765: 
                   14766: =item freshen_cache
                   14767: 
                   14768: If defined, and the environment cache for the course is valid, it is 
                   14769: returned in the returned hash.
                   14770: 
                   14771: =item one_time
                   14772: 
                   14773: If defined, the last cache time is set to _now_
                   14774: 
                   14775: =item user
                   14776: 
                   14777: If defined, the supplied username is used instead of the current user.
                   14778: 
                   14779: 
                   14780: =back
                   14781: 
1.191     harris41 14782: =item *
                   14783: 
1.624     albertel 14784: resdata($name,$domain,$type,@which) : request for current parameter
                   14785: setting for a specific $type, where $type is either 'course' or 'user',
                   14786: @what should be a list of parameters to ask about. This routine caches
1.1235    raeburn  14787: answers for 10 minutes.
1.243     albertel 14788: 
1.877     foxr     14789: =item *
                   14790: 
                   14791: get_courseresdata($courseid, $domain) : dump the entire course resource
                   14792: data base, returning a hash that is keyed by the resource name and has
                   14793: values that are the resource value.  I believe that the timestamps and
                   14794: versions are also returned.
                   14795: 
1.1236    raeburn  14796: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
                   14797: supplemental content area. This routine caches the number of files for 
                   14798: 10 minutes.
                   14799: 
1.243     albertel 14800: =back
                   14801: 
                   14802: =head2 Course Modification
                   14803: 
                   14804: =over 4
1.191     harris41 14805: 
                   14806: =item *
                   14807: 
1.243     albertel 14808: writecoursepref($courseid,%prefs) : write preferences (environment
                   14809: database) for a course
1.191     harris41 14810: 
                   14811: =item *
                   14812: 
1.1011    raeburn  14813: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   14814: 
                   14815: =item *
                   14816: 
1.1038    raeburn  14817: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 14818: 
1.1167    droeschl 14819: =item *
                   14820: 
                   14821: is_course($courseid), is_course($cdom, $cnum)
                   14822: 
                   14823: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   14824: two component version $cdom, $cnum. It checks if the specified course exists.
                   14825: 
                   14826: Returns:
                   14827:     undef if the course doesn't exist, otherwise
                   14828:     in scalar context the combined courseid.
                   14829:     in list context the two components of the course identifier, domain and 
                   14830:     courseid.    
                   14831: 
1.243     albertel 14832: =back
                   14833: 
                   14834: =head2 Resource Subroutines
                   14835: 
                   14836: =over 4
1.191     harris41 14837: 
                   14838: =item *
                   14839: 
1.243     albertel 14840: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 14841: 
                   14842: =item *
                   14843: 
1.243     albertel 14844: repcopy($filename) : subscribes to the requested file, and attempts to
                   14845: replicate from the owning library server, Might return
1.607     raeburn  14846: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   14847: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 14848: resource. Expects the local filesystem pathname
                   14849: (/home/httpd/html/res/....)
                   14850: 
                   14851: =back
                   14852: 
                   14853: =head2 Resource Information
                   14854: 
                   14855: =over 4
1.191     harris41 14856: 
                   14857: =item *
                   14858: 
1.1228    raeburn  14859: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates 
                   14860: and returns the value of a variety of different possible values,
                   14861: $varname should be a request string, and the other parameters can be
                   14862: used to specify who and what one is asking about. Ordinarily, $cid 
                   14863: does not need to be specified, as it is retrived from 
                   14864: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
                   14865: within lonuserstate::loadmap() when initializing a course, before
                   14866: $env{'request.course.id'} has been set, so it needs to be provided
                   14867: in that one case.
1.243     albertel 14868: 
                   14869: Possible values for $varname are environment.lastname (or other item
                   14870: from the envirnment hash), user.name (or someother aspect about the
                   14871: user), resource.0.maxtries (or some other part and parameter of a
                   14872: resource)
1.204     albertel 14873: 
                   14874: =item *
                   14875: 
1.243     albertel 14876: directcondval($number) : get current value of a condition; reads from a state
                   14877: string
1.204     albertel 14878: 
                   14879: =item *
                   14880: 
1.243     albertel 14881: condval($condidx) : value of condition index based on state
1.204     albertel 14882: 
                   14883: =item *
                   14884: 
1.1362    raeburn  14885: metadata($uri,$what,$toolsymb,$liburi,$prefix,$depthcount) : request a
1.243     albertel 14886: resource's metadata, $what should be either a specific key, or either
                   14887: 'keys' (to get a list of possible keys) or 'packages' to get a list of
1.1362    raeburn  14888: packages that this resource currently uses, the last 3 arguments are 
                   14889: only used internally for recursive metadata.
                   14890: 
                   14891: the toolsymb is only used where the uri is for an external tool (for which
                   14892: the uri as well as the symb are guaranteed to be unique).
1.243     albertel 14893: 
1.1371    raeburn  14894: this function automatically caches all requests except any made recursively
                   14895: to retrieve a list of metadata keys for an imported library file ($liburi is 
                   14896: defined).
1.191     harris41 14897: 
                   14898: =item *
                   14899: 
1.243     albertel 14900: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   14901: network of library servers; returns file handle of where SQL and regex results
                   14902: will be stored for query
1.191     harris41 14903: 
                   14904: =item *
                   14905: 
1.1282    raeburn  14906: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) : 
                   14907: return symbolic list entry (all arguments optional). 
                   14908: 
                   14909: Args: filename is the filename (including path) for the file for which a symb 
                   14910: is required; donotrecurse, if true will prevent calls to allowed() being made 
                   14911: to check access status if more than one resource was found in the bighash 
                   14912: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of 
                   14913: a randompick); ignorecachednull, if true will prevent a symb of '' being 
                   14914: returned if $env{$cache_str} is defined as ''; checkforblock if true will
                   14915: cause possible symbs to be checked to determine if they are subject to content
                   14916: blocking, if so they will not be included as possible symbs; possibles is a
                   14917: ref to a hash, which, as a side effect, will be populated with all possible 
                   14918: symbs (content blocking not tested).
                   14919:  
1.243     albertel 14920: returns the data handle
1.191     harris41 14921: 
                   14922: =item *
                   14923: 
1.1190    raeburn  14924: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
                   14925: and is a possible symb for the URL in $thisfn, and if is an encrypted
1.582     albertel 14926: resource that the user accessed using /enc/ returns a 1 on success, 0
1.1190    raeburn  14927: on failure, user must be in a course, as it assumes the existence of
                   14928: the course initial hash, and uses $env('request.course.id'}.  The third
                   14929: arg is an optional reference to a scalar.  If this arg is passed in the 
                   14930: call to symbverify, it will be set to 1 if the symb has been set to be 
                   14931: encrypted; otherwise it will be null.  
1.191     harris41 14932: 
                   14933: =item *
                   14934: 
1.243     albertel 14935: symbclean($symb) : removes versions numbers from a symb, returns the
                   14936: cleaned symb
1.191     harris41 14937: 
                   14938: =item *
                   14939: 
1.243     albertel 14940: is_on_map($uri) : checks if the $uri is somewhere on the current
                   14941: course map, user must be in a course for it to work.
1.191     harris41 14942: 
                   14943: =item *
                   14944: 
1.243     albertel 14945: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 14946: 
                   14947: =item *
                   14948: 
1.243     albertel 14949: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   14950: a random seed, all arguments are optional, if they aren't sent it uses the
                   14951: environment to derive them. Note: if symb isn't sent and it can't get one
                   14952: from &symbread it will use the current time as its return value
1.191     harris41 14953: 
                   14954: =item *
                   14955: 
1.243     albertel 14956: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   14957: unfakeable, receipt
1.191     harris41 14958: 
                   14959: =item *
                   14960: 
1.620     albertel 14961: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 14962: 
                   14963: =item *
                   14964: 
1.243     albertel 14965: countacc($url) : count the number of accesses to a given URL
1.191     harris41 14966: 
                   14967: =item *
                   14968: 
1.243     albertel 14969: 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 14970: 
                   14971: =item *
                   14972: 
1.243     albertel 14973: 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 14974: 
                   14975: =item *
                   14976: 
1.243     albertel 14977: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 14978: 
                   14979: =item *
                   14980: 
1.243     albertel 14981: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   14982: forcing spreadsheet to reevaluate the resource scores next time.
                   14983: 
1.1195    raeburn  14984: =item * 
                   14985: 
1.1196    raeburn  14986: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
                   14987: when viewing in course context.
1.1195    raeburn  14988: 
1.1196    raeburn  14989:  input: six args -- filename (decluttered), course number, course domain,
                   14990:                     url, symb (if registered) and group (if this is a 
                   14991:                     group item -- e.g., bulletin board, group page etc.).
1.1195    raeburn  14992: 
1.1196    raeburn  14993:  output: array of five scalars --
1.1195    raeburn  14994:          $cfile -- url for file editing if editable on current server
                   14995:          $home -- homeserver of resource (i.e., for author if published,
                   14996:                                           or course if uploaded.).
                   14997:          $switchserver --  1 if server switch will be needed.
1.1196    raeburn  14998:          $forceedit -- 1 if icon/link should be to go to edit mode 
                   14999:          $forceview -- 1 if icon/link should be to go to view mode
1.1195    raeburn  15000: 
                   15001: =item *
                   15002: 
                   15003: is_course_upload($file,$cnum,$cdom)
                   15004: 
                   15005: Used in course context to determine if current file was uploaded to 
                   15006: the course (i.e., would be found in /userfiles/docs on the course's 
                   15007: homeserver.
                   15008: 
                   15009:   input: 3 args -- filename (decluttered), course number and course domain.
                   15010:   output: boolean -- 1 if file was uploaded.
                   15011: 
1.243     albertel 15012: =back
                   15013: 
                   15014: =head2 Storing/Retreiving Data
                   15015: 
                   15016: =over 4
1.191     harris41 15017: 
                   15018: =item *
                   15019: 
1.1269    raeburn  15020: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
                   15021: permanently for this url; hashref needs to be given and should be a \%hashname;
                   15022: the remaining args aren't required and if they aren't passed or are '' they will
                   15023: be derived from the env (with the exception of $laststore, which is an 
                   15024: optional arg used when a user's submission is stored in grading).
                   15025: $laststore is $version=$timestamp, where $version is the most recent version
                   15026: number retrieved for the corresponding $symb in the $namespace db file, and
                   15027: $timestamp is the timestamp for that transaction (UNIX time).
                   15028: $laststore is currently only passed when cstore() is called by 
                   15029: structuretags::finalize_storage().
1.191     harris41 15030: 
                   15031: =item *
                   15032: 
1.1269    raeburn  15033: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
                   15034: but uses critical subroutine
1.191     harris41 15035: 
                   15036: =item *
                   15037: 
1.243     albertel 15038: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   15039: all args are optional
1.191     harris41 15040: 
                   15041: =item *
                   15042: 
1.717     albertel 15043: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   15044: dumps the complete (or key matching regexp) namespace into a hash
                   15045: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   15046: normally &store()ed into
                   15047: 
                   15048: $range should be either an integer '100' (give me the first 100
                   15049:                                            matching records)
                   15050:               or be  two integers sperated by a - with no spaces
                   15051:                  '30-50' (give me the 30th through the 50th matching
                   15052:                           records)
                   15053: 
                   15054: 
                   15055: =item *
                   15056: 
1.1269    raeburn  15057: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
1.717     albertel 15058: replaces a &store() version of data with a replacement set of data
                   15059: for a particular resource in a namespace passed in the $storehash hash 
1.1269    raeburn  15060: reference. If $tolog is true, the transaction is logged in the courselog
                   15061: with an action=PUTSTORE.
1.717     albertel 15062: 
                   15063: =item *
                   15064: 
1.243     albertel 15065: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   15066: works very similar to store/cstore, but all data is stored in a
                   15067: temporary location and can be reset using tmpreset, $storehash should
                   15068: be a hash reference, returns nothing on success
1.191     harris41 15069: 
                   15070: =item *
                   15071: 
1.243     albertel 15072: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   15073: similar to restore, but all data is stored in a temporary location and
                   15074: can be reset using tmpreset. Returns a hash of values on success,
                   15075: error string otherwise.
1.191     harris41 15076: 
                   15077: =item *
                   15078: 
1.243     albertel 15079: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   15080: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 15081: 
                   15082: =item *
                   15083: 
1.243     albertel 15084: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15085: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 15086: 
                   15087: =item *
                   15088: 
1.243     albertel 15089: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   15090: namesp ($udom and $uname are optional)
1.191     harris41 15091: 
                   15092: =item *
                   15093: 
1.702     albertel 15094: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 15095: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 15096: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  15097: 
1.702     albertel 15098: $range should be either an integer '100' (give me the first 100
                   15099:                                            matching records)
                   15100:               or be  two integers sperated by a - with no spaces
                   15101:                  '30-50' (give me the 30th through the 50th matching
                   15102:                           records)
1.449     matthew  15103: =item *
                   15104: 
                   15105: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   15106: $store can be a scalar, an array reference, or if the amount to be 
                   15107: incremented is > 1, a hash reference.
                   15108: 
                   15109: ($udom and $uname are optional)
1.191     harris41 15110: 
                   15111: =item *
                   15112: 
1.243     albertel 15113: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   15114: ($udom and $uname are optional)
1.191     harris41 15115: 
                   15116: =item *
                   15117: 
1.243     albertel 15118: cput($namespace,$storehash,$udom,$uname) : critical put
                   15119: ($udom and $uname are optional)
1.191     harris41 15120: 
                   15121: =item *
                   15122: 
1.748     albertel 15123: newput($namespace,$storehash,$udom,$uname) :
                   15124: 
                   15125: Attempts to store the items in the $storehash, but only if they don't
                   15126: currently exist, if this succeeds you can be certain that you have 
                   15127: successfully created a new key value pair in the $namespace db.
                   15128: 
                   15129: 
                   15130: Args:
                   15131:  $namespace: name of database to store values to
                   15132:  $storehash: hashref to store to the db
                   15133:  $udom: (optional) domain of user containing the db
                   15134:  $uname: (optional) name of user caontaining the db
                   15135: 
                   15136: Returns:
                   15137:  'ok' -> succeeded in storing all keys of $storehash
                   15138:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   15139:                         least <key> already existed in the db (other
                   15140:                         requested keys may also already exist)
1.967     bisitz   15141:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 15142:  'con_lost' -> unable to contact request server
                   15143:  'refused' -> action was not allowed by remote machine
                   15144: 
                   15145: 
                   15146: =item *
                   15147: 
1.243     albertel 15148: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   15149: reference filled in from namesp (encrypts the return communication)
                   15150: ($udom and $uname are optional)
1.191     harris41 15151: 
                   15152: =item *
                   15153: 
1.243     albertel 15154: log($udom,$name,$home,$message) : write to permanent log for user; use
                   15155: critical subroutine
                   15156: 
1.806     raeburn  15157: =item *
                   15158: 
1.860     raeburn  15159: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   15160: array reference filled in from namespace found in domain level on either
                   15161: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  15162: 
                   15163: =item *
                   15164: 
1.860     raeburn  15165: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   15166: domain level either on specified domain server ($uhome) or primary domain 
                   15167: server ($udom and $uhome are optional)
1.806     raeburn  15168: 
1.943     raeburn  15169: =item * 
                   15170: 
1.1240    raeburn  15171: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults 
                   15172: for: authentication, language, quotas, timezone, date locale, and portal URL in
                   15173: the target domain.
                   15174: 
                   15175: May also include additional key => value pairs for the following groups:
                   15176: 
                   15177: =over
                   15178: 
                   15179: =item
                   15180: disk quotas (MB allocated by default to portfolios and authoring spaces).
                   15181: 
                   15182: =over
                   15183: 
                   15184: =item defaultquota, authorquota
                   15185: 
                   15186: =back
                   15187: 
                   15188: =item
                   15189: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
                   15190: portfolio for users).
                   15191: 
                   15192: =over
                   15193: 
                   15194: =item
                   15195: aboutme, blog, webdav, portfolio
                   15196: 
                   15197: =back
                   15198: 
                   15199: =item
                   15200: requestcourses: ability to request courses, and how requests are processed.
                   15201: 
                   15202: =over
                   15203: 
                   15204: =item
1.1305    raeburn  15205: official, unofficial, community, textbook, placement
1.1240    raeburn  15206: 
                   15207: =back
                   15208: 
                   15209: =item
                   15210: inststatus: types of institutional affiliation, and order in which they are displayed.
                   15211: 
                   15212: =over
                   15213: 
                   15214: =item
1.1256    raeburn  15215: inststatustypes, inststatusorder, inststatusguest
1.1240    raeburn  15216: 
                   15217: =back
                   15218: 
                   15219: =item
                   15220: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
                   15221: for course's uploaded content.
                   15222: 
                   15223: =over
                   15224: 
                   15225: =item
1.1246    raeburn  15226: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota, 
1.1305    raeburn  15227: communityquota, textbookquota, placementquota
1.1240    raeburn  15228: 
                   15229: =back
                   15230: 
                   15231: =item
                   15232: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
                   15233: on your servers.
                   15234: 
                   15235: =over
                   15236: 
                   15237: =item 
                   15238: remotesessions, hostedsessions
                   15239: 
                   15240: =back
                   15241: 
                   15242: =back
                   15243: 
                   15244: In cases where a domain coordinator has never used the "Set Domain Configuration"
                   15245: utility to create a configuration.db file on a domain's primary library server 
                   15246: only the following domain defaults: auth_def, auth_arg_def, lang_def
                   15247: -- corresponding values are authentication type (internal, krb4, krb5,
                   15248: or localauth), initial password or a kerberos realm, language (e.g., en-us) -- 
                   15249: will be available. Values are retrieved from cache (if current), unless the
                   15250: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
                   15251: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
                   15252: 
                   15253: Typical usage:
1.943     raeburn  15254: 
1.1240    raeburn  15255: %domdefaults = &get_domain_defaults($target_domain);
1.943     raeburn  15256: 
1.243     albertel 15257: =back
                   15258: 
                   15259: =head2 Network Status Functions
                   15260: 
                   15261: =over 4
1.191     harris41 15262: 
                   15263: =item *
                   15264: 
1.1137    raeburn  15265: dirlist() : return directory list based on URI (first arg).
                   15266: 
                   15267: Inputs: 1 required, 5 optional.
                   15268: 
                   15269: =over
                   15270: 
                   15271: =item 
                   15272: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   15273: 
                   15274: =item
                   15275: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   15276: 
                   15277: =item
                   15278: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   15279: 
                   15280: =item
                   15281: $getpropath - boolean: 1 if prepend path using &propath(). 
                   15282: 
                   15283: =item
                   15284: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   15285: 
                   15286: =item 
                   15287: $alternateRoot - path to prepend in place of path from $uri.
                   15288: 
                   15289: =back
                   15290: 
                   15291: Returns: Array of up to two items.
                   15292: 
                   15293: =over
                   15294: 
                   15295: a reference to an array of files/subdirectories
                   15296: 
                   15297: =over
                   15298: 
                   15299: Each element in the array of files/subdirectories is a & separated list of
                   15300: item name and the result of running stat on the item.  If dirlist was requested
                   15301: for a file instead of a directory, the item name will be ''. For a directory 
                   15302: listing, if the item is a metadata file, the element will end &N&M 
                   15303: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   15304: default copyright set (1).  
                   15305: 
                   15306: =back
                   15307: 
                   15308: a scalar containing error condition (if encountered).
                   15309: 
                   15310: =over
                   15311: 
                   15312: =item 
                   15313: no_host (no homeserver identified for $username:$domain).
                   15314: 
                   15315: =item 
                   15316: no_such_host (server contacted for listing not identified as valid host).
                   15317: 
                   15318: =item 
                   15319: con_lost (connection to remote server failed).
                   15320: 
                   15321: =item 
                   15322: refused (invalid $username:$domain received on lond side).
                   15323: 
                   15324: =item 
                   15325: no_such_dir (directory at specified path on lond side does not exist). 
                   15326: 
                   15327: =item 
                   15328: empty (directory at specified path on lond side is empty).
                   15329: 
                   15330: =over
                   15331: 
                   15332: This is currently not encountered because the &ls3, &ls2, 
                   15333: &ls (_handler) routines on the lond side do not filter out
                   15334: . and .. from a directory listing. 
                   15335: 
                   15336: =back
                   15337: 
                   15338: =back
                   15339: 
                   15340: =back
1.191     harris41 15341: 
                   15342: =item *
                   15343: 
1.243     albertel 15344: spareserver() : find server with least workload from spare.tab
                   15345: 
1.986     foxr     15346: 
                   15347: =item *
                   15348: 
                   15349: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   15350: if there is no corresponding loncapa host.
                   15351: 
1.243     albertel 15352: =back
                   15353: 
1.986     foxr     15354: 
1.243     albertel 15355: =head2 Apache Request
                   15356: 
                   15357: =over 4
1.191     harris41 15358: 
                   15359: =item *
                   15360: 
1.243     albertel 15361: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   15362: localhost, posts hash
                   15363: 
                   15364: =back
                   15365: 
                   15366: =head2 Data to String to Data
                   15367: 
                   15368: =over 4
1.191     harris41 15369: 
                   15370: =item *
                   15371: 
1.243     albertel 15372: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   15373: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 15374: 
                   15375: =item *
                   15376: 
1.243     albertel 15377: hashref2str($hashref) : convert a hashref into a string complete with
                   15378: escaping and '=' and '&' separators, supports elements that are
                   15379: arrayrefs and hashrefs
1.191     harris41 15380: 
                   15381: =item *
                   15382: 
1.243     albertel 15383: arrayref2str($arrayref) : convert an arrayref into a string complete
                   15384: with escaping and '&' separators, supports elements that are arrayrefs
                   15385: and hashrefs
1.191     harris41 15386: 
                   15387: =item *
                   15388: 
1.243     albertel 15389: str2hash($string) : convert string to hash using unescaping and
                   15390: splitting on '=' and '&', supports elements that are arrayrefs and
                   15391: hashrefs
1.191     harris41 15392: 
                   15393: =item *
                   15394: 
1.243     albertel 15395: str2array($string) : convert string to hash using unescaping and
                   15396: splitting on '&', supports elements that are arrayrefs and hashrefs
                   15397: 
                   15398: =back
                   15399: 
                   15400: =head2 Logging Routines
                   15401: 
                   15402: 
                   15403: These routines allow one to make log messages in the lonnet.log and
                   15404: lonnet.perm logfiles.
1.191     harris41 15405: 
1.1119    foxr     15406: =over 4
                   15407: 
1.191     harris41 15408: =item *
                   15409: 
1.243     albertel 15410: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 15411: 
                   15412: =item *
                   15413: 
1.243     albertel 15414: logthis() : append message to the normal lonnet.log file, it gets
                   15415: preiodically rolled over and deleted.
1.191     harris41 15416: 
                   15417: =item *
                   15418: 
1.243     albertel 15419: logperm() : append a permanent message to lonnet.perm.log, this log
                   15420: file never gets deleted by any automated portion of the system, only
                   15421: messages of critical importance should go in here.
                   15422: 
1.1119    foxr     15423: 
1.243     albertel 15424: =back
                   15425: 
                   15426: =head2 General File Helper Routines
                   15427: 
                   15428: =over 4
1.191     harris41 15429: 
                   15430: =item *
                   15431: 
1.481     raeburn  15432: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   15433: (a) files in /uploaded
                   15434:   (i) If a local copy of the file exists - 
                   15435:       compares modification date of local copy with last-modified date for 
                   15436:       definitive version stored on home server for course. If local copy is 
                   15437:       stale, requests a new version from the home server and stores it. 
                   15438:       If the original has been removed from the home server, then local copy 
                   15439:       is unlinked.
                   15440:   (ii) If local copy does not exist -
                   15441:       requests the file from the home server and stores it. 
                   15442:   
                   15443:   If $caller is 'uploadrep':  
                   15444:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   15445:     for request for files originally uploaded via DOCS. 
                   15446:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   15447:   
                   15448:   Otherwise:
                   15449:      This indicates a call from the content generation phase of the request.
                   15450:      -  returns the entire contents of the file or -1.
                   15451:      
                   15452: (b) files in /res
                   15453:    - returns the entire contents of a file or -1; 
                   15454:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 15455: 
1.712     albertel 15456: 
                   15457: =item *
                   15458: 
                   15459: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   15460:                   reference
                   15461: 
                   15462: returns either a stat() list of data about the file or an empty list
                   15463: if the file doesn't exist or couldn't find out about it (connection
                   15464: problems or user unknown)
                   15465: 
1.191     harris41 15466: =item *
                   15467: 
1.243     albertel 15468: filelocation($dir,$file) : returns file system location of a file
                   15469: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   15470: directory that relative $file lookups are to looked in ($dir of /a/dir
                   15471: and a file of ../bob will become /a/bob)
1.191     harris41 15472: 
                   15473: =item *
                   15474: 
                   15475: hreflocation($dir,$file) : returns file system location or a URL; same as
                   15476: filelocation except for hrefs
                   15477: 
                   15478: =item *
                   15479: 
1.1261    raeburn  15480: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
                   15481: also removes beginning /home/httpd/html unless /priv/ follows it.
1.191     harris41 15482: 
1.243     albertel 15483: =back
                   15484: 
1.608     albertel 15485: =head2 Usererfile file routines (/uploaded*)
                   15486: 
                   15487: =over 4
                   15488: 
                   15489: =item *
                   15490: 
                   15491: userfileupload(): main rotine for putting a file in a user or course's
                   15492:                   filespace, arguments are,
                   15493: 
1.620     albertel 15494:  formname - required - this is the name of the element in $env where the
1.608     albertel 15495:            filename, and the contents of the file to create/modifed exist
1.620     albertel 15496:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   15497:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  15498:  context - if coursedoc, store the file in the course of the active role
                   15499:              of the current user; 
                   15500:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   15501:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 15502:  subdir - required - subdirectory to put the file in under ../userfiles/
                   15503:          if undefined, it will be placed in "unknown"
                   15504: 
                   15505:  (This routine calls clean_filename() to remove any dangerous
                   15506:  characters from the filename, and then calls finuserfileupload() to
                   15507:  complete the transaction)
                   15508: 
                   15509:  returns either the url of the uploaded file (/uploaded/....) if successful
                   15510:  and /adm/notfound.html if unsuccessful
                   15511: 
                   15512: =item *
                   15513: 
                   15514: clean_filename(): routine for cleaing a filename up for storage in
                   15515:                  userfile space, argument is:
                   15516: 
                   15517:  filename - proposed filename
                   15518: 
                   15519: returns: the new clean filename
                   15520: 
                   15521: =item *
                   15522: 
1.1090    raeburn  15523: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 15524: userspace, probably shouldn't be called directly
                   15525: 
                   15526:   docuname: username or courseid of destination for the file
                   15527:   docudom: domain of user/course of destination for the file
                   15528:   formname: same as for userfileupload()
1.1090    raeburn  15529:   fname: filename (including subdirectories) for the file
                   15530:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   15531:   allfiles: reference to hash used to store objects found by parser
                   15532:   codebase: reference to hash used for codebases of java objects found by parser
                   15533:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   15534:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   15535:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   15536:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   15537:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   15538:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  15539:   mimetype: reference to scalar to accommodate mime type determined
                   15540:             from File::MMagic if $parser = parse.
1.608     albertel 15541: 
                   15542:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  15543:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   15544:  was 'overwrite').
                   15545:  
1.608     albertel 15546: 
                   15547: =item *
                   15548: 
                   15549: renameuserfile(): renames an existing userfile to a new name
                   15550: 
                   15551:   Args:
                   15552:    docuname: username or courseid of destination for the file
                   15553:    docudom: domain of user/course of destination for the file
                   15554:    old: current file name (including any subdirs under userfiles)
                   15555:    new: desired file name (including any subdirs under userfiles)
                   15556: 
                   15557: =item *
                   15558: 
                   15559: mkdiruserfile(): creates a directory is a userfiles dir
                   15560: 
                   15561:   Args:
                   15562:    docuname: username or courseid of destination for the file
                   15563:    docudom: domain of user/course of destination for the file
                   15564:    dir: dir to create (including any subdirs under userfiles)
                   15565: 
                   15566: =item *
                   15567: 
                   15568: removeuserfile(): removes a file that exists in userfiles
                   15569: 
                   15570:   Args:
                   15571:    docuname: username or courseid of destination for the file
                   15572:    docudom: domain of user/course of destination for the file
                   15573:    fname: filname to delete (including any subdirs under userfiles)
                   15574: 
                   15575: =item *
                   15576: 
                   15577: removeuploadedurl(): convience function for removeuserfile()
                   15578: 
                   15579:   Args:
                   15580:    url:  a full /uploaded/... url to delete
                   15581: 
1.747     albertel 15582: =item * 
                   15583: 
                   15584: get_portfile_permissions():
                   15585:   Args:
                   15586:     domain: domain of user or course contain the portfolio files
                   15587:     user: name of user or num of course contain the portfolio files
                   15588:   Returns:
                   15589:     hashref of a dump of the proper file_permissions.db
                   15590:    
                   15591: 
                   15592: =item * 
                   15593: 
                   15594: get_access_controls():
                   15595: 
                   15596: Args:
                   15597:   current_permissions: the hash ref returned from get_portfile_permissions()
                   15598:   group: (optional) the group you want the files associated with
                   15599:   file: (optional) the file you want access info on
                   15600: 
                   15601: Returns:
1.749     raeburn  15602:     a hash (keys are file names) of hashes containing
                   15603:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   15604:         values are XML containing access control settings (see below) 
1.747     albertel 15605: 
                   15606: Internal notes:
                   15607: 
1.749     raeburn  15608:  access controls are stored in file_permissions.db as key=value pairs.
                   15609:     key -> path to file/file_name\0uniqueID:scope_end_start
                   15610:         where scope -> public,guest,course,group,domains or users.
                   15611:               end -> UNIX time for end of access (0 -> no end date)
                   15612:               start -> UNIX time for start of access
                   15613: 
                   15614:     value -> XML description of access control
                   15615:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   15616:             <start></start>
                   15617:             <end></end>
                   15618: 
                   15619:             <password></password>  for scope type = guest
                   15620: 
                   15621:             <domain></domain>     for scope type = course or group
                   15622:             <number></number>
                   15623:             <roles id="">
                   15624:              <role></role>
                   15625:              <access></access>
                   15626:              <section></section>
                   15627:              <group></group>
                   15628:             </roles>
                   15629: 
                   15630:             <dom></dom>         for scope type = domains
                   15631: 
                   15632:             <users>             for scope type = users
                   15633:              <user>
                   15634:               <uname></uname>
                   15635:               <udom></udom>
                   15636:              </user>
                   15637:             </users>
                   15638:            </scope> 
                   15639:               
                   15640:  Access data is also aggregated for each file in an additional key=value pair:
                   15641:  key -> path to file/file_name\0accesscontrol 
                   15642:  value -> reference to hash
                   15643:           hash contains key = value pairs
                   15644:           where key = uniqueID:scope_end_start
                   15645:                 value = UNIX time record was last updated
                   15646: 
                   15647:           Used to improve speed of look-ups of access controls for each file.  
                   15648:  
                   15649:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   15650: 
1.1198    raeburn  15651: =item *
                   15652: 
1.749     raeburn  15653: modify_access_controls():
                   15654: 
                   15655: Modifies access controls for a portfolio file
                   15656: Args
                   15657: 1. file name
                   15658: 2. reference to hash of required changes,
                   15659: 3. domain
                   15660: 4. username
                   15661:   where domain,username are the domain of the portfolio owner 
                   15662:   (either a user or a course) 
                   15663: 
                   15664: Returns:
                   15665: 1. result of additions or updates ('ok' or 'error', with error message). 
                   15666: 2. result of deletions ('ok' or 'error', with error message).
                   15667: 3. reference to hash of any new or updated access controls.
                   15668: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   15669:    key = integer (inbound ID)
1.1198    raeburn  15670:    value = uniqueID
                   15671: 
                   15672: =item *
                   15673: 
                   15674: get_timebased_id():
                   15675: 
                   15676: Attempts to get a unique timestamp-based suffix for use with items added to a 
                   15677: course via the Course Editor (e.g., folders, composite pages, 
                   15678: group bulletin boards).
                   15679: 
                   15680: Args: (first three required; six others optional)
                   15681: 
                   15682: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
                   15683:    docssequence, or name of group
                   15684: 
                   15685: 2. keyid (alphanumeric): name of temporary locking key in hash,
                   15686:    e.g., num, boardids
                   15687: 
                   15688: 3. namespace: name of gdbm file used to store suffixes already assigned;  
                   15689:    file will be named nohist_namespace.db
                   15690: 
                   15691: 4. cdom: domain of course; default is current course domain from %env
                   15692: 
                   15693: 5. cnum: course number; default is current course number from %env
                   15694: 
                   15695: 6. idtype: set to concat if an additional digit is to be appended to the 
                   15696:    unix timestamp to form the suffix, if the plain timestamp is already
                   15697:    in use.  Default is to not do this, but simply increment the unix 
                   15698:    timestamp by 1 until a unique key is obtained.
                   15699: 
                   15700: 7. who: holder of locking key; defaults to user:domain for user.
                   15701: 
                   15702: 8. locktries: number of attempts to obtain a lock (sleep of 1s before 
                   15703:    retrying); default is 3.
                   15704: 
                   15705: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.  
                   15706: 
                   15707: Returns:
                   15708: 
                   15709: 1. suffix obtained (numeric)
                   15710: 
                   15711: 2. result of deleting locking key (ok if deleted, or lock never obtained)
                   15712: 
                   15713: 3. error: contains (localized) error message if an error occurred.
                   15714: 
1.747     albertel 15715: 
1.608     albertel 15716: =back
                   15717: 
1.243     albertel 15718: =head2 HTTP Helper Routines
                   15719: 
                   15720: =over 4
                   15721: 
1.191     harris41 15722: =item *
                   15723: 
                   15724: escape() : unpack non-word characters into CGI-compatible hex codes
                   15725: 
                   15726: =item *
                   15727: 
                   15728: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   15729: 
1.243     albertel 15730: =back
                   15731: 
                   15732: =head1 PRIVATE SUBROUTINES
                   15733: 
                   15734: =head2 Underlying communication routines (Shouldn't call)
                   15735: 
                   15736: =over 4
                   15737: 
                   15738: =item *
                   15739: 
                   15740: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   15741: 
                   15742: =item *
                   15743: 
                   15744: reply() : uses subreply to send a message to remote machine, logs all failures
                   15745: 
                   15746: =item *
                   15747: 
                   15748: critical() : passes a critical message to another server; if cannot
                   15749: get through then place message in connection buffer directory and
                   15750: returns con_delayed, if incapable of saving message, returns
                   15751: con_failed
                   15752: 
                   15753: =item *
                   15754: 
                   15755: reconlonc() : tries to reconnect lonc client processes.
                   15756: 
                   15757: =back
                   15758: 
                   15759: =head2 Resource Access Logging
                   15760: 
                   15761: =over 4
                   15762: 
                   15763: =item *
                   15764: 
                   15765: flushcourselogs() : flush (save) buffer logs and access logs
                   15766: 
                   15767: =item *
                   15768: 
                   15769: courselog($what) : save message for course in hash
                   15770: 
                   15771: =item *
                   15772: 
                   15773: courseacclog($what) : save message for course using &courselog().  Perform
                   15774: special processing for specific resource types (problems, exams, quizzes, etc).
                   15775: 
1.191     harris41 15776: =item *
                   15777: 
                   15778: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   15779: as a PerlChildExitHandler
1.243     albertel 15780: 
                   15781: =back
                   15782: 
                   15783: =head2 Other
                   15784: 
                   15785: =over 4
                   15786: 
                   15787: =item *
                   15788: 
                   15789: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 15790: 
                   15791: =back
                   15792: 
                   15793: =cut
1.877     foxr     15794: 

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