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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1181  ! raeburn     4: # $Id: lonnet.pm,v 1.1180 2012/07/17 14:49:32 droeschl Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1173    foxr       78: use Encode;
                     79: 
1.871     albertel   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.539     albertel   94: use Time::HiRes qw( 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.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.550     foxr      107: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.449     matthew   114: 
1.1       albertel  115: # --------------------------------------------------------------------- Logging
1.729     www       116: {
                    117:     my $logid;
                    118:     sub instructor_log {
1.957     raeburn   119: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    120:         if (($cnum eq '') || ($cdom eq '')) {
                    121:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:         }
1.729     www       124: 	$logid++;
1.957     raeburn   125:         my $now = time();
                    126: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       127: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       128: 				    { $id => {
                    129: 					'exe_uname' => $env{'user.name'},
                    130: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   131: 					'exe_time'  => $now,
1.730     www       132: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    133: 					'delflag'   => $delflag,
                    134: 					'logentry'  => $storehash,
                    135: 					'uname'     => $uname,
                    136: 					'udom'      => $udom,
                    137: 				    }
1.957     raeburn   138: 				  },$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    145: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.448     albertel  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
                    355:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   356:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   357:     return $response;
                    358: }
                    359: 
1.1       albertel  360: # -------------------------------------------------- Non-critical communication
                    361: sub subreply {
                    362:     my ($cmd,$server)=@_;
1.838     albertel  363:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      364:     #
                    365:     #  With loncnew process trimming, there's a timing hole between lonc server
                    366:     #  process exit and the master server picking up the listen on the AF_UNIX
                    367:     #  socket.  In that time interval, a lock file will exist:
                    368: 
                    369:     my $lockfile=$peerfile.".lock";
                    370:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    371: 	sleep(1);
                    372:     }
                    373:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      374:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      375:     #
1.550     foxr      376:     #   We'll give the connection a few tries before abandoning it.  If
                    377:     #   connection is not possible, we'll con_lost back to the client.
                    378:     #   
                    379:     my $client;
                    380:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    381: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    382: 				      Type    => SOCK_STREAM,
                    383: 				      Timeout => 10);
1.869     albertel  384: 	if ($client) {
1.550     foxr      385: 	    last;		# Connected!
1.850     albertel  386: 	} else {
1.853     albertel  387: 	    &create_connection(&hostname($server),$server);
1.550     foxr      388: 	}
1.850     albertel  389:         sleep(1);		# Try again later if failed connection.
1.550     foxr      390:     }
                    391:     my $answer;
                    392:     if ($client) {
1.704     albertel  393: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      394: 	$answer=<$client>;
                    395: 	if (!$answer) { $answer="con_lost"; }
                    396: 	chomp($answer);
                    397:     } else {
                    398: 	$answer = 'con_lost';	# Failed connection.
                    399:     }
1.1       albertel  400:     return $answer;
                    401: }
                    402: 
                    403: sub reply {
                    404:     my ($cmd,$server)=@_;
1.838     albertel  405:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  406:     my $answer=subreply($cmd,$server);
1.65      www       407:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  408:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       409:                 " $cmd to $server returned $answer</font>");
                    410:     }
1.1       albertel  411:     return $answer;
                    412: }
                    413: 
                    414: # ----------------------------------------------------------- Send USR1 to lonc
                    415: 
                    416: sub reconlonc {
1.891     albertel  417:     my ($lonid) = @_;
                    418:     my $hostname = &hostname($lonid);
                    419:     if ($lonid) {
                    420: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    421: 	if ($hostname && -e $peerfile) {
                    422: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    423: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    424: 					     Type    => SOCK_STREAM,
                    425: 					     Timeout => 10);
                    426: 	    if ($client) {
                    427: 		print $client ("reset_retries\n");
                    428: 		my $answer=<$client>;
                    429: 		#reset just this one.
                    430: 	    }
                    431: 	}
                    432: 	return;
                    433:     }
                    434: 
1.836     www       435:     &logthis("Trying to reconnect lonc");
1.1       albertel  436:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  437:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  438: 	my $loncpid=<$fh>;
                    439:         chomp($loncpid);
                    440:         if (kill 0 => $loncpid) {
                    441: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    442:             kill USR1 => $loncpid;
                    443:             sleep 1;
1.836     www       444:          } else {
1.12      www       445: 	    &logthis(
1.672     albertel  446:                "<font color=\"blue\">WARNING:".
1.12      www       447:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  448:         }
                    449:     } else {
1.836     www       450: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  451:     }
                    452: }
                    453: 
                    454: # ------------------------------------------------------ Critical communication
1.12      www       455: 
1.1       albertel  456: sub critical {
                    457:     my ($cmd,$server)=@_;
1.838     albertel  458:     unless (&hostname($server)) {
1.672     albertel  459:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       460:                " Critical message to unknown server ($server)</font>");
                    461:         return 'no_such_host';
                    462:     }
1.1       albertel  463:     my $answer=reply($cmd,$server);
                    464:     if ($answer eq 'con_lost') {
                    465: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  466: 	my $answer=reply($cmd,$server);
1.1       albertel  467:         if ($answer eq 'con_lost') {
                    468:             my $now=time;
                    469:             my $middlename=$cmd;
1.5       www       470:             $middlename=substr($middlename,0,16);
1.1       albertel  471:             $middlename=~s/\W//g;
                    472:             my $dfilename=
1.305     www       473:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    474:             $dumpcount++;
1.1       albertel  475:             {
1.448     albertel  476: 		my $dfh;
                    477: 		if (open($dfh,">$dfilename")) {
                    478: 		    print $dfh "$cmd\n"; 
                    479: 		    close($dfh);
                    480: 		}
1.1       albertel  481:             }
                    482:             sleep 2;
                    483:             my $wcmd='';
                    484:             {
1.448     albertel  485: 		my $dfh;
                    486: 		if (open($dfh,"<$dfilename")) {
                    487: 		    $wcmd=<$dfh>; 
                    488: 		    close($dfh);
                    489: 		}
1.1       albertel  490:             }
                    491:             chomp($wcmd);
1.7       www       492:             if ($wcmd eq $cmd) {
1.672     albertel  493: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       494:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  495:                 &logperm("D:$server:$cmd");
                    496: 	        return 'con_delayed';
                    497:             } else {
1.672     albertel  498:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       499:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  500:                 &logperm("F:$server:$cmd");
                    501:                 return 'con_failed';
                    502:             }
                    503:         }
                    504:     }
                    505:     return $answer;
1.405     albertel  506: }
                    507: 
1.755     albertel  508: # ------------------------------------------- check if return value is an error
                    509: 
                    510: sub error {
                    511:     my ($result) = @_;
1.756     albertel  512:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  513: 	if ($2 == 2) { return undef; }
                    514: 	return $1;
                    515:     }
                    516:     return undef;
                    517: }
                    518: 
1.783     albertel  519: sub convert_and_load_session_env {
                    520:     my ($lonidsdir,$handle)=@_;
                    521:     my @profile;
                    522:     {
1.917     albertel  523: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    524: 	if (!$opened) {
1.915     albertel  525: 	    return 0;
                    526: 	}
1.783     albertel  527: 	flock($idf,LOCK_SH);
                    528: 	@profile=<$idf>;
                    529: 	close($idf);
                    530:     }
                    531:     my %temp_env;
                    532:     foreach my $line (@profile) {
1.786     albertel  533: 	if ($line !~ m/=/) {
                    534: 	    return 0;
                    535: 	}
1.783     albertel  536: 	chomp($line);
                    537: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    538: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    539:     }
                    540:     unlink("$lonidsdir/$handle.id");
                    541:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    542: 	    0640)) {
                    543: 	%disk_env = %temp_env;
                    544: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    545: 	untie(%disk_env);
                    546:     }
1.786     albertel  547:     return 1;
1.783     albertel  548: }
                    549: 
1.374     www       550: # ------------------------------------------- Transfer profile into environment
1.780     albertel  551: my $env_loaded;
                    552: sub transfer_profile_to_env {
1.788     albertel  553:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    554:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       555: 
1.720     albertel  556:     if (!defined($lonidsdir)) {
                    557: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    558:     }
                    559:     if (!defined($handle)) {
                    560:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    561:     }
                    562: 
1.786     albertel  563:     my $convert;
                    564:     {
1.917     albertel  565:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    566: 	if (!$opened) {
1.915     albertel  567: 	    return;
                    568: 	}
1.786     albertel  569: 	flock($idf,LOCK_SH);
                    570: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    571: 		&GDBM_READER(),0640)) {
                    572: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    573: 	    untie(%disk_env);
                    574: 	} else {
                    575: 	    $convert = 1;
                    576: 	}
                    577:     }
                    578:     if ($convert) {
                    579: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    580: 	    &logthis("Failed to load session, or convert session.");
                    581: 	}
1.374     www       582:     }
1.783     albertel  583: 
1.786     albertel  584:     my %remove;
1.783     albertel  585:     while ( my $envname = each(%env) ) {
1.433     matthew   586:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    587:             if ($time < time-300) {
1.783     albertel  588:                 $remove{$key}++;
1.433     matthew   589:             }
                    590:         }
                    591:     }
1.783     albertel  592: 
1.619     albertel  593:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  594:     $env_loaded=1;
1.783     albertel  595:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   596:         &delenv($expired_key);
1.374     www       597:     }
1.1       albertel  598: }
                    599: 
1.916     albertel  600: # ---------------------------------------------------- Check for valid session 
                    601: sub check_for_valid_session {
1.1155    raeburn   602:     my ($r,$name) = @_;
1.916     albertel  603:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   604:     if ($name eq '') {
                    605:         $name = 'lonID';
                    606:     }
                    607:     my $lonid=$cookies{$name};
1.916     albertel  608:     return undef if (!$lonid);
                    609: 
                    610:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   611:     my $lonidsdir;
                    612:     if ($name eq 'lonDAV') {
                    613:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    614:     } else {
                    615:         $lonidsdir=$r->dir_config('lonIDsDir');
                    616:     }
1.916     albertel  617:     return undef if (!-e "$lonidsdir/$handle.id");
                    618: 
1.917     albertel  619:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    620:     return undef if (!$opened);
1.916     albertel  621: 
                    622:     flock($idf,LOCK_SH);
                    623:     my %disk_env;
                    624:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    625: 	    &GDBM_READER(),0640)) {
                    626: 	return undef;	
                    627:     }
                    628: 
                    629:     if (!defined($disk_env{'user.name'})
                    630: 	|| !defined($disk_env{'user.domain'})) {
                    631: 	return undef;
                    632:     }
                    633:     return $handle;
                    634: }
                    635: 
1.830     albertel  636: sub timed_flock {
                    637:     my ($file,$lock_type) = @_;
                    638:     my $failed=0;
                    639:     eval {
                    640: 	local $SIG{__DIE__}='DEFAULT';
                    641: 	local $SIG{ALRM}=sub {
                    642: 	    $failed=1;
                    643: 	    die("failed lock");
                    644: 	};
                    645: 	alarm(13);
                    646: 	flock($file,$lock_type);
                    647: 	alarm(0);
                    648:     };
                    649:     if ($failed) {
                    650: 	return undef;
                    651:     } else {
                    652: 	return 1;
                    653:     }
                    654: }
                    655: 
1.5       www       656: # ---------------------------------------------------------- Append Environment
                    657: 
                    658: sub appenv {
1.949     raeburn   659:     my ($newenv,$roles) = @_;
                    660:     if (ref($newenv) eq 'HASH') {
                    661:         foreach my $key (keys(%{$newenv})) {
                    662:             my $refused = 0;
                    663: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    664:                 $refused = 1;
                    665:                 if (ref($roles) eq 'ARRAY') {
                    666:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    667:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    668:                         $refused = 0;
                    669:                     }
                    670:                 }
                    671:             }
                    672:             if ($refused) {
                    673:                 &logthis("<font color=\"blue\">WARNING: ".
                    674:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    675:                          .'</font>');
                    676: 	        delete($newenv->{$key});
                    677:             } else {
                    678:                 $env{$key}=$newenv->{$key};
                    679:             }
                    680:         }
                    681:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    682:         if ($opened
                    683: 	    && &timed_flock($env_file,LOCK_EX)
                    684: 	    &&
                    685: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    686: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    687: 	    while (my ($key,$value) = each(%{$newenv})) {
                    688: 	        $disk_env{$key} = $value;
                    689: 	    }
                    690: 	    untie(%disk_env);
1.35      www       691:         }
1.191     harris41  692:     }
1.56      www       693:     return 'ok';
                    694: }
                    695: # ----------------------------------------------------- Delete from Environment
                    696: 
                    697: sub delenv {
1.1104    raeburn   698:     my ($delthis,$regexp,$roles) = @_;
                    699:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    700:         my $refused = 1;
                    701:         if (ref($roles) eq 'ARRAY') {
                    702:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    703:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    704:                 $refused = 0;
                    705:             }
                    706:         }
                    707:         if ($refused) {
                    708:             &logthis("<font color=\"blue\">WARNING: ".
                    709:                      "Attempt to delete from environment ".$delthis);
                    710:             return 'error';
                    711:         }
1.56      www       712:     }
1.917     albertel  713:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    714:     if ($opened
1.915     albertel  715: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  716: 	&&
                    717: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    718: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  719: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   720: 	    if ($regexp) {
                    721:                 if ($key=~/^$delthis/) {
                    722:                     delete($env{$key});
                    723:                     delete($disk_env{$key});
                    724:                 } 
                    725:             } else {
                    726:                 if ($key=~/^\Q$delthis\E/) {
                    727: 		    delete($env{$key});
                    728: 		    delete($disk_env{$key});
                    729: 	        }
                    730:             }
1.448     albertel  731: 	}
1.783     albertel  732: 	untie(%disk_env);
1.5       www       733:     }
                    734:     return 'ok';
1.369     albertel  735: }
                    736: 
1.790     albertel  737: sub get_env_multiple {
                    738:     my ($name) = @_;
                    739:     my @values;
                    740:     if (defined($env{$name})) {
                    741:         # exists is it an array
                    742:         if (ref($env{$name})) {
                    743:             @values=@{ $env{$name} };
                    744:         } else {
                    745:             $values[0]=$env{$name};
                    746:         }
                    747:     }
                    748:     return(@values);
                    749: }
                    750: 
1.958     www       751: # ------------------------------------------------------------------- Locking
                    752: 
                    753: sub set_lock {
                    754:     my ($text)=@_;
                    755:     $locknum++;
                    756:     my $id=$$.'-'.$locknum;
                    757:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    758:              'session.lock.'.$id => $text});
                    759:     return $id;
                    760: }
                    761: 
                    762: sub get_locks {
                    763:     my $num=0;
                    764:     my %texts=();
                    765:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    766:        if ($lock=~/\w/) {
                    767:           $num++;
                    768:           $texts{$lock}=$env{'session.lock.'.$lock};
                    769:        }
                    770:    }
                    771:    return ($num,%texts);
                    772: }
                    773: 
                    774: sub remove_lock {
                    775:     my ($id)=@_;
                    776:     my $newlocks='';
                    777:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    778:        if (($lock=~/\w/) && ($lock ne $id)) {
                    779:           $newlocks.=','.$lock;
                    780:        }
                    781:     }
                    782:     &appenv({'session.locks' => $newlocks});
                    783:     &delenv('session.lock.'.$id);
                    784: }
                    785: 
                    786: sub remove_all_locks {
                    787:     my $activelocks=$env{'session.locks'};
                    788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    789:        if ($lock=~/\w/) {
                    790:           &remove_lock($lock);
                    791:        }
                    792:     }
                    793: }
                    794: 
                    795: 
1.369     albertel  796: # ------------------------------------------ Find out current server userload
                    797: sub userload {
                    798:     my $numusers=0;
                    799:     {
                    800: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    801: 	my $filename;
                    802: 	my $curtime=time;
                    803: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  804: 	    next if ($filename eq '.' || $filename eq '..');
                    805: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  806: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  807: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  808: 	}
                    809: 	closedir(LONIDS);
                    810:     }
                    811:     my $userloadpercent=0;
                    812:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    813:     if ($maxuserload) {
1.371     albertel  814: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  815:     }
1.372     albertel  816:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  817:     return $userloadpercent;
1.283     www       818: }
                    819: 
1.1       albertel  820: # ------------------------------ Find server with least workload from spare.tab
1.11      www       821: 
1.1       albertel  822: sub spareserver {
1.1083    raeburn   823:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  824:     my $spare_server;
1.370     albertel  825:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  826:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    827:                                                      :  $userloadpercent;
1.1083    raeburn   828:     my ($uint_dom,$remotesessions);
                    829:     if (($udom ne '') && (&domain($udom) ne '')) {
                    830:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    831:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    832:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    833:         $remotesessions = $udomdefaults{'remotesessions'};
                    834:     }
1.1123    raeburn   835:     my $spareshash = &this_host_spares($udom);
                    836:     if (ref($spareshash) eq 'HASH') {
                    837:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    838:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    839:                 if ($uint_dom) {
                    840:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    841:                                                  $try_server));
                    842:                 }
                    843: 	        ($spare_server, $lowest_load) =
                    844: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    845:             }
1.1083    raeburn   846:         }
1.784     albertel  847: 
1.1123    raeburn   848:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    849: 
                    850:         if (!$found_server) {
                    851:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    852: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    853:                     if ($uint_dom) {
                    854:                         next unless (&spare_can_host($udom,$uint_dom,
                    855:                                                      $remotesessions,$try_server));
                    856:                     }
                    857: 	            ($spare_server, $lowest_load) =
                    858: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    859:                 }
                    860: 	    }
                    861:         }
1.784     albertel  862:     }
                    863: 
                    864:     if (!$want_server_name) {
1.968     raeburn   865:         my $protocol = 'http';
                    866:         if ($protocol{$spare_server} eq 'https') {
                    867:             $protocol = $protocol{$spare_server};
                    868:         }
1.1001    raeburn   869:         if (defined($spare_server)) {
                    870:             my $hostname = &hostname($spare_server);
1.1083    raeburn   871:             if (defined($hostname)) {
1.1001    raeburn   872: 	        $spare_server = $protocol.'://'.$hostname;
                    873:             }
                    874:         }
1.784     albertel  875:     }
                    876:     return $spare_server;
                    877: }
                    878: 
                    879: sub compare_server_load {
                    880:     my ($try_server, $spare_server, $lowest_load) = @_;
                    881: 
                    882:     my $loadans     = &reply('load',    $try_server);
                    883:     my $userloadans = &reply('userload',$try_server);
                    884: 
                    885:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   886: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  887:     }
                    888: 
                    889:     my $load;
                    890:     if ($loadans =~ /\d/) {
                    891: 	if ($userloadans =~ /\d/) {
                    892: 	    #both are numbers, pick the bigger one
                    893: 	    $load = ($loadans > $userloadans) ? $loadans 
                    894: 		                              : $userloadans;
1.411     albertel  895: 	} else {
1.784     albertel  896: 	    $load = $loadans;
1.411     albertel  897: 	}
1.784     albertel  898:     } else {
                    899: 	$load = $userloadans;
                    900:     }
                    901: 
                    902:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    903: 	$spare_server = $try_server;
                    904: 	$lowest_load  = $load;
1.370     albertel  905:     }
1.784     albertel  906:     return ($spare_server,$lowest_load);
1.202     matthew   907: }
1.914     albertel  908: 
                    909: # --------------------------- ask offload servers if user already has a session
                    910: sub find_existing_session {
                    911:     my ($udom,$uname) = @_;
1.1123    raeburn   912:     my $spareshash = &this_host_spares($udom);
                    913:     if (ref($spareshash) eq 'HASH') {
                    914:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    915:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    916:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    917:             }
                    918:         }
                    919:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    920:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    921:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    922:             }
                    923:         }
1.914     albertel  924:     }
                    925:     return;
                    926: }
                    927: 
                    928: # -------------------------------- ask if server already has a session for user
                    929: sub has_user_session {
                    930:     my ($lonid,$udom,$uname) = @_;
                    931:     my $result = &reply(join(':','userhassession',
                    932: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    933:     return 1 if ($result eq 'ok');
                    934: 
                    935:     return 0;
                    936: }
                    937: 
1.1076    raeburn   938: # --------- determine least loaded server in a user's domain which allows login
                    939: 
                    940: sub choose_server {
1.1115    raeburn   941:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   942:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   943:     my %servers = &get_servers($udom);
1.1076    raeburn   944:     my $lowest_load = 30000;
1.1151    raeburn   945:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   946:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   947:         my $loginvia;
                    948:         if ($checkloginvia) {
                    949:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   950:             if ($loginvia) {
                    951:                 my ($server,$path) = split(/:/,$loginvia);
                    952:                 ($login_host, $lowest_load) =
                    953:                     &compare_server_load($server, $login_host, $lowest_load);
                    954:                 if ($login_host eq $server) {
                    955:                     $portal_path = $path;
1.1151    raeburn   956:                     $isredirect = 1;
1.1116    raeburn   957:                 }
                    958:             } else {
                    959:                 ($login_host, $lowest_load) =
                    960:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    961:                 if ($login_host eq $lonhost) {
                    962:                     $portal_path = '';
1.1151    raeburn   963:                     $isredirect = ''; 
1.1116    raeburn   964:                 }
                    965:             }
                    966:         } else {
1.1076    raeburn   967:             ($login_host, $lowest_load) =
1.1116    raeburn   968:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   969:         }
                    970:     }
                    971:     if ($login_host ne '') {
1.1116    raeburn   972:         $hostname = &hostname($login_host);
1.1076    raeburn   973:     }
1.1151    raeburn   974:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   975: }
                    976: 
1.202     matthew   977: # --------------------------------------------- Try to change a user's password
                    978: 
                    979: sub changepass {
1.799     raeburn   980:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   981:     $currentpass = &escape($currentpass);
                    982:     $newpass     = &escape($newpass);
1.1030    raeburn   983:     my $lonhost = $perlvar{'lonHostID'};
                    984:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   985: 		       $server);
                    986:     if (! $answer) {
                    987: 	&logthis("No reply on password change request to $server ".
                    988: 		 "by $uname in domain $udom.");
                    989:     } elsif ($answer =~ "^ok") {
                    990:         &logthis("$uname in $udom successfully changed their password ".
                    991: 		 "on $server.");
                    992:     } elsif ($answer =~ "^pwchange_failure") {
                    993: 	&logthis("$uname in $udom was unable to change their password ".
                    994: 		 "on $server.  The action was blocked by either lcpasswd ".
                    995: 		 "or pwchange");
                    996:     } elsif ($answer =~ "^non_authorized") {
                    997:         &logthis("$uname in $udom did not get their password correct when ".
                    998: 		 "attempting to change it on $server.");
                    999:     } elsif ($answer =~ "^auth_mode_error") {
                   1000:         &logthis("$uname in $udom attempted to change their password despite ".
                   1001: 		 "not being locally or internally authenticated on $server.");
                   1002:     } elsif ($answer =~ "^unknown_user") {
                   1003:         &logthis("$uname in $udom attempted to change their password ".
                   1004: 		 "on $server but were unable to because $server is not ".
                   1005: 		 "their home server.");
                   1006:     } elsif ($answer =~ "^refused") {
                   1007: 	&logthis("$server refused to change $uname in $udom password because ".
                   1008: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1009:     } elsif ($answer =~ "invalid_client") {
                   1010:         &logthis("$server refused to change $uname in $udom password because ".
                   1011:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1012:     }
                   1013:     return $answer;
1.1       albertel 1014: }
                   1015: 
1.169     harris41 1016: # ----------------------- Try to determine user's current authentication scheme
                   1017: 
                   1018: sub queryauthenticate {
                   1019:     my ($uname,$udom)=@_;
1.456     albertel 1020:     my $uhome=&homeserver($uname,$udom);
                   1021:     if (!$uhome) {
                   1022: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1023: 	return 'no_host';
                   1024:     }
                   1025:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1026:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1027: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1028:     }
1.456     albertel 1029:     return $answer;
1.169     harris41 1030: }
                   1031: 
1.1       albertel 1032: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1033: 
1.1       albertel 1034: sub authenticate {
1.1073    raeburn  1035:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1036:     $upass=&escape($upass);
                   1037:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1038:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1039:     my $newhome;
1.836     www      1040:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1041: # Maybe the machine was offline and only re-appeared again recently?
                   1042:         &reconlonc();
                   1043: # One more
1.952     raeburn  1044: 	$uhome=&homeserver($uname,$udom,1);
                   1045:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1046:             if (defined(&domain($udom,'primary'))) {
                   1047:                 $newhome=&domain($udom,'primary');
                   1048:             }
                   1049:             if ($newhome ne '') {
                   1050:                 $uhome = $newhome;
                   1051:             }
                   1052:         }
1.836     www      1053: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1054: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1055: 	    return 'no_host';
                   1056:         }
1.1       albertel 1057:     }
1.1073    raeburn  1058:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1059:     if ($answer eq 'authorized') {
1.952     raeburn  1060:         if ($newhome) {
                   1061:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1062:             return 'no_account_on_host'; 
                   1063:         } else {
                   1064:             &logthis("User $uname at $udom authorized by $uhome");
                   1065:             return $uhome;
                   1066:         }
1.471     albertel 1067:     }
                   1068:     if ($answer eq 'non_authorized') {
                   1069: 	&logthis("User $uname at $udom rejected by $uhome");
                   1070: 	return 'no_host'; 
1.9       www      1071:     }
1.471     albertel 1072:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1073:     return 'no_host';
                   1074: }
                   1075: 
1.1073    raeburn  1076: sub can_host_session {
1.1074    raeburn  1077:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1078:     my $canhost = 1;
1.1074    raeburn  1079:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1080:     if (ref($remotesessions) eq 'HASH') {
                   1081:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1082:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1083:                 $canhost = 0;
                   1084:             } else {
                   1085:                 $canhost = 1;
                   1086:             }
                   1087:         }
                   1088:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1089:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1090:                 $canhost = 1;
                   1091:             } else {
                   1092:                 $canhost = 0;
                   1093:             }
                   1094:         }
                   1095:         if ($canhost) {
                   1096:             if ($remotesessions->{'version'} ne '') {
                   1097:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1098:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1099:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1100:                         my $major = $1;
                   1101:                         my $minor = $2;
                   1102:                         if (($major < $reqmajor ) ||
                   1103:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1104:                             $canhost = 0;
                   1105:                         }
                   1106:                     } else {
                   1107:                         $canhost = 0;
                   1108:                     }
                   1109:                 }
                   1110:             }
                   1111:         }
                   1112:     }
                   1113:     if ($canhost) {
                   1114:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1115:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1116:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1117:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1118:                 if (($uint_dom ne '') && 
                   1119:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1120:                     $canhost = 0;
                   1121:                 } else {
                   1122:                     $canhost = 1;
                   1123:                 }
                   1124:             }
                   1125:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1126:                 if (($uint_dom ne '') && 
                   1127:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1128:                     $canhost = 1;
                   1129:                 } else {
                   1130:                     $canhost = 0;
                   1131:                 }
                   1132:             }
                   1133:         }
                   1134:     }
                   1135:     return $canhost;
                   1136: }
                   1137: 
1.1083    raeburn  1138: sub spare_can_host {
                   1139:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1140:     my $canhost=1;
                   1141:     my @intdoms;
                   1142:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1143:     if (ref($internet_names) eq 'ARRAY') {
                   1144:         @intdoms = @{$internet_names};
                   1145:     }
                   1146:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1147:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1148:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1149:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1150:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1151:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1152:                                      $remotesessions,
                   1153:                                      $defdomdefaults{'hostedsessions'});
                   1154:     }
                   1155:     return $canhost;
                   1156: }
                   1157: 
1.1123    raeburn  1158: sub this_host_spares {
                   1159:     my ($dom) = @_;
1.1126    raeburn  1160:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1161:     my @hosts = &current_machine_ids();
                   1162:     foreach my $lonhost (@hosts) {
                   1163:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1164:             $dom_in_use = $dom;
                   1165:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1166:             last;
                   1167:         }
                   1168:     }
1.1126    raeburn  1169:     if ($dom_in_use ne '') {
                   1170:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1171:     }
                   1172:     if (ref($result) ne 'HASH') {
                   1173:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1174:         $dom_in_use = &host_domain($lonhost_in_use);
                   1175:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1176:         if (ref($result) ne 'HASH') {
                   1177:             $result = \%spareid;
                   1178:         }
                   1179:     }
                   1180:     return $result;
                   1181: }
                   1182: 
                   1183: sub spares_for_offload  {
                   1184:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1185:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1186:     if (defined($cached)) {
                   1187:         return $result;
                   1188:     } else {
1.1126    raeburn  1189:         my $cachetime = 60*60*24;
                   1190:         my %domconfig =
                   1191:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1192:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1193:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1194:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1195:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1196:                 }
                   1197:             }
                   1198:         }
                   1199:     }
1.1126    raeburn  1200:     return;
1.1123    raeburn  1201: }
                   1202: 
1.1129    raeburn  1203: sub get_lonbalancer_config {
                   1204:     my ($servers) = @_;
                   1205:     my ($currbalancer,$currtargets);
                   1206:     if (ref($servers) eq 'HASH') {
                   1207:         foreach my $server (keys(%{$servers})) {
                   1208:             my %what = (
                   1209:                          spareid => 1,
                   1210:                          perlvar => 1,
                   1211:                        );
                   1212:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1213:             if ($result eq 'ok') {
                   1214:                 if (ref($returnhash) eq 'HASH') {
                   1215:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1216:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1217:                             $currbalancer = $server;
                   1218:                             $currtargets = {};
                   1219:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1220:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1221:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1222:                                 }
                   1223:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1224:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1225:                                 }
                   1226:                             }
                   1227:                             last;
                   1228:                         }
                   1229:                     }
                   1230:                 }
                   1231:             }
                   1232:         }
                   1233:     }
                   1234:     return ($currbalancer,$currtargets);
                   1235: }
                   1236: 
                   1237: sub check_loadbalancing {
                   1238:     my ($uname,$udom) = @_;
                   1239:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1240:         $offloadto,$otherserver);
                   1241:     my $lonhost = $perlvar{'lonHostID'};
1.1175    raeburn  1242:     my @hosts = &current_machine_ids();
1.1129    raeburn  1243:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1244:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1245:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1246:     my $serverhomedom = &host_domain($lonhost);
                   1247: 
                   1248:     my $cachetime = 60*60*24;
                   1249: 
                   1250:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1251:         $dom_in_use = $udom;
                   1252:         $homeintdom = 1;
                   1253:     } else {
                   1254:         $dom_in_use = $serverhomedom;
                   1255:     }
                   1256:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1257:     unless (defined($cached)) {
                   1258:         my %domconfig =
                   1259:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1260:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1261:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1262:         }
                   1263:     }
                   1264:     if (ref($result) eq 'HASH') {
                   1265:         my $currbalancer = $result->{'lonhost'};
                   1266:         my $currtargets = $result->{'targets'};
                   1267:         my $currrules = $result->{'rules'};
                   1268:         if ($currbalancer ne '') {
                   1269:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1270:                 $is_balancer = 1;
                   1271:             }
                   1272:         }
                   1273:         if ($is_balancer) {
                   1274:             if (ref($currrules) eq 'HASH') {
                   1275:                 if ($homeintdom) {
                   1276:                     if ($uname ne '') {
                   1277:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1278:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1279:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1280:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1281:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1282:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1283:                             }
                   1284:                         }
                   1285:                         if ($rule_in_effect eq '') {
                   1286:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1287:                             if ($userenv{'inststatus'} ne '') {
                   1288:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1289:                                 my ($othertitle,$usertypes,$types) =
                   1290:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1291:                                 if (ref($types) eq 'ARRAY') {
                   1292:                                     foreach my $type (@{$types}) {
                   1293:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1294:                                             if (exists($currrules->{$type})) {
                   1295:                                                 $rule_in_effect = $currrules->{$type};
                   1296:                                             }
                   1297:                                         }
                   1298:                                     }
                   1299:                                 }
                   1300:                             } else {
                   1301:                                 if (exists($currrules->{'default'})) {
                   1302:                                     $rule_in_effect = $currrules->{'default'};
                   1303:                                 }
                   1304:                             }
                   1305:                         }
                   1306:                     } else {
                   1307:                         if (exists($currrules->{'default'})) {
                   1308:                             $rule_in_effect = $currrules->{'default'};
                   1309:                         }
                   1310:                     }
                   1311:                 } else {
                   1312:                     if ($currrules->{'_LC_external'} ne '') {
                   1313:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1314:                     }
                   1315:                 }
                   1316:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1317:                                                        $uname,$udom);
                   1318:             }
                   1319:         }
                   1320:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1321:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1322:         unless (defined($cached)) {
                   1323:             my %domconfig =
                   1324:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1325:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1326:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1327:             }
                   1328:         }
                   1329:         if (ref($result) eq 'HASH') {
                   1330:             my $currbalancer = $result->{'lonhost'};
                   1331:             my $currtargets = $result->{'targets'};
                   1332:             my $currrules = $result->{'rules'};
                   1333: 
                   1334:             if ($currbalancer eq $lonhost) {
                   1335:                 $is_balancer = 1;
                   1336:                 if (ref($currrules) eq 'HASH') {
                   1337:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1338:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1339:                     }
                   1340:                 }
                   1341:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1342:                                                        $uname,$udom);
                   1343:             }
                   1344:         } else {
                   1345:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1346:                 $is_balancer = 1;
                   1347:                 $offloadto = &this_host_spares($dom_in_use);
                   1348:             }
                   1349:         }
                   1350:     } else {
                   1351:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1352:             $is_balancer = 1;
                   1353:             $offloadto = &this_host_spares($dom_in_use);
                   1354:         }
                   1355:     }
1.1176    raeburn  1356:     if ($is_balancer) {
                   1357:         my $lowest_load = 30000;
                   1358:         if (ref($offloadto) eq 'HASH') {
                   1359:             if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1360:                 foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1361:                     ($otherserver,$lowest_load) =
                   1362:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1363:                 }
1.1129    raeburn  1364:             }
1.1176    raeburn  1365:             my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129    raeburn  1366: 
1.1176    raeburn  1367:             if (!$found_server) {
                   1368:                 if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1369:                     foreach my $try_server (@{$offloadto->{'default'}}) {
                   1370:                         ($otherserver,$lowest_load) =
                   1371:                             &compare_server_load($try_server,$otherserver,$lowest_load);
                   1372:                     }
                   1373:                 }
                   1374:             }
                   1375:         } elsif (ref($offloadto) eq 'ARRAY') {
                   1376:             if (@{$offloadto} == 1) {
                   1377:                 $otherserver = $offloadto->[0];
                   1378:             } elsif (@{$offloadto} > 1) {
                   1379:                 foreach my $try_server (@{$offloadto}) {
1.1129    raeburn  1380:                     ($otherserver,$lowest_load) =
                   1381:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1382:                 }
                   1383:             }
                   1384:         }
1.1176    raeburn  1385:         if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
                   1386:             $is_balancer = 0;
                   1387:             if ($uname ne '' && $udom ne '') {
                   1388:                 if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
                   1389:                     
                   1390:                     &appenv({'user.loadbalexempt'     => $lonhost,  
                   1391:                              'user.loadbalcheck.time' => time});
                   1392:                 }
1.1129    raeburn  1393:             }
                   1394:         }
                   1395:     }
                   1396:     return ($is_balancer,$otherserver);
                   1397: }
                   1398: 
                   1399: sub get_loadbalancer_targets {
                   1400:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1401:     my $offloadto;
1.1175    raeburn  1402:     if ($rule_in_effect eq 'none') {
                   1403:         return [$perlvar{'lonHostID'}];
                   1404:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1405:         $offloadto = $currtargets;
                   1406:     } else {
                   1407:         if ($rule_in_effect eq 'homeserver') {
                   1408:             my $homeserver = &homeserver($uname,$udom);
                   1409:             if ($homeserver ne 'no_host') {
                   1410:                 $offloadto = [$homeserver];
                   1411:             }
                   1412:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1413:             my %domconfig =
                   1414:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1415:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1416:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1417:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1418:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1419:                     }
                   1420:                 }
                   1421:             } else {
1.1178    raeburn  1422:                 my %servers = &internet_dom_servers($udom);
1.1129    raeburn  1423:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1424:                 if (&hostname($remotebalancer) ne '') {
                   1425:                     $offloadto = [$remotebalancer];
                   1426:                 }
                   1427:             }
                   1428:         } elsif (&hostname($rule_in_effect) ne '') {
                   1429:             $offloadto = [$rule_in_effect];
                   1430:         }
                   1431:     }
                   1432:     return $offloadto;
                   1433: }
                   1434: 
1.1127    raeburn  1435: sub internet_dom_servers {
                   1436:     my ($dom) = @_;
                   1437:     my (%uniqservers,%servers);
                   1438:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1439:     my @machinedoms = &machine_domains($primaryserver);
                   1440:     foreach my $mdom (@machinedoms) {
                   1441:         my %currservers = %servers;
                   1442:         my %server = &get_servers($mdom);
                   1443:         %servers = (%currservers,%server);
                   1444:     }
                   1445:     my %by_hostname;
                   1446:     foreach my $id (keys(%servers)) {
                   1447:         push(@{$by_hostname{$servers{$id}}},$id);
                   1448:     }
                   1449:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1450:         if (@{$by_hostname{$hostname}} > 1) {
                   1451:             my $match = 0;
                   1452:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1453:                 if (&host_domain($id) eq $dom) {
                   1454:                     $uniqservers{$id} = $hostname;
                   1455:                     $match = 1;
                   1456:                 }
                   1457:             }
                   1458:             unless ($match) {
                   1459:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1460:             }
                   1461:         } else {
                   1462:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1463:         }
                   1464:     }
                   1465:     return %uniqservers;
                   1466: }
                   1467: 
1.1       albertel 1468: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1469: 
1.599     albertel 1470: my %homecache;
1.1       albertel 1471: sub homeserver {
1.230     stredwic 1472:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1473:     my $index="$uname:$udom";
1.426     albertel 1474: 
1.599     albertel 1475:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1476: 
                   1477:     my %servers = &get_servers($udom,'library');
                   1478:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1479:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1480: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1481: 
                   1482: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1483: 	if ($answer eq 'found') {
                   1484: 	    delete($badServerCache{$tryserver}); 
                   1485: 	    return $homecache{$index}=$tryserver;
                   1486: 	} elsif ($answer eq 'no_host') {
                   1487: 	    $badServerCache{$tryserver}=1;
                   1488: 	}
1.1       albertel 1489:     }    
                   1490:     return 'no_host';
1.70      www      1491: }
                   1492: 
                   1493: # ------------------------------------- Find the usernames behind a list of IDs
                   1494: 
                   1495: sub idget {
                   1496:     my ($udom,@ids)=@_;
                   1497:     my %returnhash=();
                   1498:     
1.841     albertel 1499:     my %servers = &get_servers($udom,'library');
                   1500:     foreach my $tryserver (keys(%servers)) {
                   1501: 	my $idlist=join('&',@ids);
                   1502: 	$idlist=~tr/A-Z/a-z/; 
                   1503: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1504: 	my @answer=();
                   1505: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1506: 	    @answer=split(/\&/,$reply);
                   1507: 	}                    ;
                   1508: 	my $i;
                   1509: 	for ($i=0;$i<=$#ids;$i++) {
                   1510: 	    if ($answer[$i]) {
                   1511: 		$returnhash{$ids[$i]}=$answer[$i];
                   1512: 	    } 
                   1513: 	}
                   1514:     } 
1.70      www      1515:     return %returnhash;
                   1516: }
                   1517: 
                   1518: # ------------------------------------- Find the IDs behind a list of usernames
                   1519: 
                   1520: sub idrget {
                   1521:     my ($udom,@unames)=@_;
                   1522:     my %returnhash=();
1.800     albertel 1523:     foreach my $uname (@unames) {
                   1524:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1525:     }
1.70      www      1526:     return %returnhash;
                   1527: }
                   1528: 
                   1529: # ------------------------------- Store away a list of names and associated IDs
                   1530: 
                   1531: sub idput {
                   1532:     my ($udom,%ids)=@_;
                   1533:     my %servers=();
1.800     albertel 1534:     foreach my $uname (keys(%ids)) {
                   1535: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1536:         my $uhom=&homeserver($uname,$udom);
1.70      www      1537:         if ($uhom ne 'no_host') {
1.800     albertel 1538:             my $id=&escape($ids{$uname});
1.70      www      1539:             $id=~tr/A-Z/a-z/;
1.800     albertel 1540:             my $esc_unam=&escape($uname);
1.70      www      1541: 	    if ($servers{$uhom}) {
1.800     albertel 1542: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1543:             } else {
1.800     albertel 1544:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1545:             }
                   1546:         }
1.191     harris41 1547:     }
1.800     albertel 1548:     foreach my $server (keys(%servers)) {
                   1549:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1550:     }
1.344     www      1551: }
                   1552: 
1.1023    raeburn  1553: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1554: sub dump_dom {
1.1165    droeschl 1555:     my ($namespace, $udom, $regexp) = @_;
                   1556: 
                   1557:     $udom ||= $env{'user.domain'};
                   1558: 
                   1559:     return () unless $udom;
                   1560: 
                   1561:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1562: }
                   1563: 
1.1023    raeburn  1564: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1565: 
                   1566: sub get_dom {
1.860     raeburn  1567:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1568:     my $items='';
                   1569:     foreach my $item (@$storearr) {
                   1570:         $items.=&escape($item).'&';
                   1571:     }
                   1572:     $items=~s/\&$//;
1.860     raeburn  1573:     if (!$udom) {
                   1574:         $udom=$env{'user.domain'};
                   1575:         if (defined(&domain($udom,'primary'))) {
                   1576:             $uhome=&domain($udom,'primary');
                   1577:         } else {
1.874     albertel 1578:             undef($uhome);
1.860     raeburn  1579:         }
                   1580:     } else {
                   1581:         if (!$uhome) {
                   1582:             if (defined(&domain($udom,'primary'))) {
                   1583:                 $uhome=&domain($udom,'primary');
                   1584:             }
                   1585:         }
                   1586:     }
                   1587:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1588:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1589:         my %returnhash;
1.875     albertel 1590:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1591:             return %returnhash;
                   1592:         }
1.806     raeburn  1593:         my @pairs=split(/\&/,$rep);
                   1594:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1595:             return @pairs;
                   1596:         }
                   1597:         my $i=0;
                   1598:         foreach my $item (@$storearr) {
                   1599:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1600:             $i++;
                   1601:         }
                   1602:         return %returnhash;
                   1603:     } else {
1.880     banghart 1604:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1605:     }
                   1606: }
                   1607: 
                   1608: # -------------------------------------------- put items in domain db files 
                   1609: 
                   1610: sub put_dom {
1.860     raeburn  1611:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1612:     if (!$udom) {
                   1613:         $udom=$env{'user.domain'};
                   1614:         if (defined(&domain($udom,'primary'))) {
                   1615:             $uhome=&domain($udom,'primary');
                   1616:         } else {
1.874     albertel 1617:             undef($uhome);
1.860     raeburn  1618:         }
                   1619:     } else {
                   1620:         if (!$uhome) {
                   1621:             if (defined(&domain($udom,'primary'))) {
                   1622:                 $uhome=&domain($udom,'primary');
                   1623:             }
                   1624:         }
                   1625:     } 
                   1626:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1627:         my $items='';
                   1628:         foreach my $item (keys(%$storehash)) {
                   1629:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1630:         }
                   1631:         $items=~s/\&$//;
                   1632:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1633:     } else {
1.860     raeburn  1634:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1635:     }
                   1636: }
                   1637: 
1.1023    raeburn  1638: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1639: sub newput_dom {
1.1023    raeburn  1640:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1641:     my $result;
                   1642:     if (!$udom) {
                   1643:         $udom=$env{'user.domain'};
                   1644:     }
1.1023    raeburn  1645:     if ($udom) {
                   1646:         my $uname = &get_domainconfiguser($udom);
                   1647:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1648:     }
                   1649:     return $result;
                   1650: }
                   1651: 
1.1023    raeburn  1652: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1653: sub del_dom {
1.1023    raeburn  1654:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1655:     if (ref($storearr) eq 'ARRAY') {
                   1656:         if (!$udom) {
                   1657:             $udom=$env{'user.domain'};
                   1658:         }
1.1023    raeburn  1659:         if ($udom) {
                   1660:             my $uname = &get_domainconfiguser($udom); 
                   1661:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1662:         }
                   1663:     }
                   1664: }
                   1665: 
1.1023    raeburn  1666: # ----------------------------------construct domainconfig user for a domain 
                   1667: sub get_domainconfiguser {
                   1668:     my ($udom) = @_;
                   1669:     return $udom.'-domainconfig';
                   1670: }
                   1671: 
1.837     raeburn  1672: sub retrieve_inst_usertypes {
                   1673:     my ($udom) = @_;
                   1674:     my (%returnhash,@order);
1.989     raeburn  1675:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1676:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1677:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1678:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1679:         @order = @{$domdefs{'inststatusorder'}};
                   1680:     } else {
                   1681:         if (defined(&domain($udom,'primary'))) {
                   1682:             my $uhome=&domain($udom,'primary');
                   1683:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1684:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1685:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1686:                 return (\%returnhash,\@order);
                   1687:             }
                   1688:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1689:             my @pairs=split(/\&/,$hashitems);
                   1690:             foreach my $item (@pairs) {
                   1691:                 my ($key,$value)=split(/=/,$item,2);
                   1692:                 $key = &unescape($key);
                   1693:                 next if ($key =~ /^error: 2 /);
                   1694:                 $returnhash{$key}=&thaw_unescape($value);
                   1695:             }
                   1696:             my @esc_order = split(/\&/,$orderitems);
                   1697:             foreach my $item (@esc_order) {
                   1698:                 push(@order,&unescape($item));
                   1699:             }
                   1700:         } else {
                   1701:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1702:         }
                   1703:     }
                   1704:     return (\%returnhash,\@order);
                   1705: }
                   1706: 
1.868     raeburn  1707: sub is_domainimage {
                   1708:     my ($url) = @_;
                   1709:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1710:         if (&domain($1) ne '') {
                   1711:             return '1';
                   1712:         }
                   1713:     }
                   1714:     return;
                   1715: }
                   1716: 
1.899     raeburn  1717: sub inst_directory_query {
                   1718:     my ($srch) = @_;
                   1719:     my $udom = $srch->{'srchdomain'};
                   1720:     my %results;
                   1721:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1722:     my $outcome;
1.899     raeburn  1723:     if ($homeserver ne '') {
1.904     albertel 1724: 	my $queryid=&reply("querysend:instdirsearch:".
                   1725: 			   &escape($srch->{'srchby'}).':'.
                   1726: 			   &escape($srch->{'srchterm'}).':'.
                   1727: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1728: 	my $host=&hostname($homeserver);
                   1729: 	if ($queryid !~/^\Q$host\E\_/) {
                   1730: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1731: 	    return;
                   1732: 	}
                   1733: 	my $response = &get_query_reply($queryid);
                   1734: 	my $maxtries = 5;
                   1735: 	my $tries = 1;
                   1736: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1737: 	    $response = &get_query_reply($queryid);
                   1738: 	    $tries ++;
                   1739: 	}
                   1740: 
                   1741:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1742:             if ($response eq 'unavailable') {
                   1743:                 $outcome = $response;
                   1744:             } else {
                   1745:                 $outcome = 'ok';
                   1746:                 my @matches = split(/\n/,$response);
                   1747:                 foreach my $match (@matches) {
                   1748:                     my ($key,$value) = split(/=/,$match);
                   1749:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1750:                 }
1.899     raeburn  1751:             }
                   1752:         }
                   1753:     }
1.909     raeburn  1754:     return ($outcome,%results);
1.899     raeburn  1755: }
                   1756: 
                   1757: sub usersearch {
                   1758:     my ($srch) = @_;
                   1759:     my $dom = $srch->{'srchdomain'};
                   1760:     my %results;
                   1761:     my %libserv = &all_library();
                   1762:     my $query = 'usersearch';
                   1763:     foreach my $tryserver (keys(%libserv)) {
                   1764:         if (&host_domain($tryserver) eq $dom) {
                   1765:             my $host=&hostname($tryserver);
                   1766:             my $queryid=
1.911     raeburn  1767:                 &reply("querysend:".&escape($query).':'.
                   1768:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1769:                        &escape($srch->{'srchtype'}).':'.
                   1770:                        &escape($srch->{'srchterm'}),$tryserver);
                   1771:             if ($queryid !~/^\Q$host\E\_/) {
                   1772:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1773:                 next;
1.899     raeburn  1774:             }
                   1775:             my $reply = &get_query_reply($queryid);
                   1776:             my $maxtries = 1;
                   1777:             my $tries = 1;
                   1778:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1779:                 $reply = &get_query_reply($queryid);
                   1780:                 $tries ++;
                   1781:             }
                   1782:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1783:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1784:             } else {
1.911     raeburn  1785:                 my @matches;
                   1786:                 if ($reply =~ /\n/) {
                   1787:                     @matches = split(/\n/,$reply);
                   1788:                 } else {
                   1789:                     @matches = split(/\&/,$reply);
                   1790:                 }
1.899     raeburn  1791:                 foreach my $match (@matches) {
                   1792:                     my ($uname,$udom,%userhash);
1.911     raeburn  1793:                     foreach my $entry (split(/:/,$match)) {
                   1794:                         my ($key,$value) =
                   1795:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1796:                         $userhash{$key} = $value;
                   1797:                         if ($key eq 'username') {
                   1798:                             $uname = $value;
                   1799:                         } elsif ($key eq 'domain') {
                   1800:                             $udom = $value;
1.911     raeburn  1801:                         }
1.899     raeburn  1802:                     }
                   1803:                     $results{$uname.':'.$udom} = \%userhash;
                   1804:                 }
                   1805:             }
                   1806:         }
                   1807:     }
                   1808:     return %results;
                   1809: }
                   1810: 
1.912     raeburn  1811: sub get_instuser {
                   1812:     my ($udom,$uname,$id) = @_;
                   1813:     my $homeserver = &domain($udom,'primary');
                   1814:     my ($outcome,%results);
                   1815:     if ($homeserver ne '') {
                   1816:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1817:                            &escape($id).':'.&escape($udom),$homeserver);
                   1818:         my $host=&hostname($homeserver);
                   1819:         if ($queryid !~/^\Q$host\E\_/) {
                   1820:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1821:             return;
                   1822:         }
                   1823:         my $response = &get_query_reply($queryid);
                   1824:         my $maxtries = 5;
                   1825:         my $tries = 1;
                   1826:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1827:             $response = &get_query_reply($queryid);
                   1828:             $tries ++;
                   1829:         }
                   1830:         if (!&error($response) && $response ne 'refused') {
                   1831:             if ($response eq 'unavailable') {
                   1832:                 $outcome = $response;
                   1833:             } else {
                   1834:                 $outcome = 'ok';
                   1835:                 my @matches = split(/\n/,$response);
                   1836:                 foreach my $match (@matches) {
                   1837:                     my ($key,$value) = split(/=/,$match);
                   1838:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1839:                 }
                   1840:             }
                   1841:         }
                   1842:     }
                   1843:     my %userinfo;
                   1844:     if (ref($results{$uname}) eq 'HASH') {
                   1845:         %userinfo = %{$results{$uname}};
                   1846:     } 
                   1847:     return ($outcome,%userinfo);
                   1848: }
                   1849: 
                   1850: sub inst_rulecheck {
1.923     raeburn  1851:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1852:     my %returnhash;
                   1853:     if ($udom ne '') {
                   1854:         if (ref($rules) eq 'ARRAY') {
                   1855:             @{$rules} = map {&escape($_);} (@{$rules});
                   1856:             my $rulestr = join(':',@{$rules});
                   1857:             my $homeserver=&domain($udom,'primary');
                   1858:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1859:                 my $response;
                   1860:                 if ($item eq 'username') {                
                   1861:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1862:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1863:                                               $homeserver));
1.923     raeburn  1864:                 } elsif ($item eq 'id') {
                   1865:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1866:                                               ':'.&escape($id).':'.$rulestr,
                   1867:                                               $homeserver));
1.945     raeburn  1868:                 } elsif ($item eq 'selfcreate') {
                   1869:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1870:                                                &escape($udom).':'.&escape($uname).
                   1871:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1872:                 }
1.912     raeburn  1873:                 if ($response ne 'refused') {
                   1874:                     my @pairs=split(/\&/,$response);
                   1875:                     foreach my $item (@pairs) {
                   1876:                         my ($key,$value)=split(/=/,$item,2);
                   1877:                         $key = &unescape($key);
                   1878:                         next if ($key =~ /^error: 2 /);
                   1879:                         $returnhash{$key}=&thaw_unescape($value);
                   1880:                     }
                   1881:                 }
                   1882:             }
                   1883:         }
                   1884:     }
                   1885:     return %returnhash;
                   1886: }
                   1887: 
                   1888: sub inst_userrules {
1.923     raeburn  1889:     my ($udom,$check) = @_;
1.912     raeburn  1890:     my (%ruleshash,@ruleorder);
                   1891:     if ($udom ne '') {
                   1892:         my $homeserver=&domain($udom,'primary');
                   1893:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1894:             my $response;
                   1895:             if ($check eq 'id') {
                   1896:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1897:                                  $homeserver);
1.943     raeburn  1898:             } elsif ($check eq 'email') {
                   1899:                 $response=&reply('instemailrules:'.&escape($udom),
                   1900:                                  $homeserver);
1.923     raeburn  1901:             } else {
                   1902:                 $response=&reply('instuserrules:'.&escape($udom),
                   1903:                                  $homeserver);
                   1904:             }
1.912     raeburn  1905:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1906:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1907:                 ($response ne 'no_such_host')) {
                   1908:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1909:                 my @pairs=split(/\&/,$hashitems);
                   1910:                 foreach my $item (@pairs) {
                   1911:                     my ($key,$value)=split(/=/,$item,2);
                   1912:                     $key = &unescape($key);
                   1913:                     next if ($key =~ /^error: 2 /);
                   1914:                     $ruleshash{$key}=&thaw_unescape($value);
                   1915:                 }
                   1916:                 my @esc_order = split(/\&/,$orderitems);
                   1917:                 foreach my $item (@esc_order) {
                   1918:                     push(@ruleorder,&unescape($item));
                   1919:                 }
                   1920:             }
                   1921:         }
                   1922:     }
                   1923:     return (\%ruleshash,\@ruleorder);
                   1924: }
                   1925: 
1.976     raeburn  1926: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1927: 
                   1928: sub get_domain_defaults {
                   1929:     my ($domain) = @_;
                   1930:     my $cachetime = 60*60*24;
                   1931:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1932:     if (defined($cached)) {
                   1933:         if (ref($result) eq 'HASH') {
                   1934:             return %{$result};
                   1935:         }
                   1936:     }
                   1937:     my %domdefaults;
                   1938:     my %domconfig =
1.989     raeburn  1939:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1940:                                   'requestcourses','inststatus',
1.1073    raeburn  1941:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1942:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1943:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1944:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1945:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1946:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1947:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1948:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1949:     } else {
                   1950:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1951:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1952:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1953:     }
1.976     raeburn  1954:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1955:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1956:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1957:         } else {
                   1958:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1959:         } 
1.1177    raeburn  1960:         my @usertools = ('aboutme','blog','webdav','portfolio');
1.976     raeburn  1961:         foreach my $item (@usertools) {
                   1962:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1963:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1964:             }
                   1965:         }
                   1966:     }
1.985     raeburn  1967:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1968:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1969:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1970:         }
                   1971:     }
1.989     raeburn  1972:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1973:         foreach my $item ('inststatustypes','inststatusorder') {
                   1974:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1975:         }
                   1976:     }
1.1047    raeburn  1977:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1978:         foreach my $item ('canuse_pdfforms') {
                   1979:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1980:         }
                   1981:     }
1.1073    raeburn  1982:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1983:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1984:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1985:         }
                   1986:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1987:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1988:         }
                   1989:     }
1.943     raeburn  1990:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1991:                                   $cachetime);
                   1992:     return %domdefaults;
                   1993: }
                   1994: 
1.344     www      1995: # --------------------------------------------------- Assign a key to a student
                   1996: 
                   1997: sub assign_access_key {
1.364     www      1998: #
                   1999: # a valid key looks like uname:udom#comments
                   2000: # comments are being appended
                   2001: #
1.498     www      2002:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   2003:     $kdom=
1.620     albertel 2004:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      2005:     $knum=
1.620     albertel 2006:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      2007:     $cdom=
1.620     albertel 2008:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2009:     $cnum=
1.620     albertel 2010:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2011:     $udom=$env{'user.name'} unless (defined($udom));
                   2012:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2013:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2014:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2015:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2016:                                                   # assigned to this person
                   2017:                                                   # - this should not happen,
1.345     www      2018:                                                   # unless something went wrong
                   2019:                                                   # the first time around
                   2020: # ready to assign
1.364     www      2021:         $logentry=$1.'; '.$logentry;
1.496     www      2022:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2023:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2024: # key now belongs to user
1.346     www      2025: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2026:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2027:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2028:                 return 'ok';
                   2029:             } else {
                   2030:                 return 
                   2031:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2032: 	    }
                   2033:         } else {
                   2034:             return 'error: Could not assign key, try again later.';
                   2035:         }
1.364     www      2036:     } elsif (!$existing{$ckey}) {
1.345     www      2037: # the key does not exist
                   2038: 	return 'error: The key does not exist';
                   2039:     } else {
                   2040: # the key is somebody else's
                   2041: 	return 'error: The key is already in use';
                   2042:     }
1.344     www      2043: }
                   2044: 
1.364     www      2045: # ------------------------------------------ put an additional comment on a key
                   2046: 
                   2047: sub comment_access_key {
                   2048: #
                   2049: # a valid key looks like uname:udom#comments
                   2050: # comments are being appended
                   2051: #
                   2052:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2053:     $cdom=
1.620     albertel 2054:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2055:     $cnum=
1.620     albertel 2056:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2057:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2058:     if ($existing{$ckey}) {
                   2059:         $existing{$ckey}.='; '.$logentry;
                   2060: # ready to assign
1.367     www      2061:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2062:                                                  $cdom,$cnum) eq 'ok') {
                   2063: 	    return 'ok';
                   2064:         } else {
                   2065: 	    return 'error: Count not store comment.';
                   2066:         }
                   2067:     } else {
                   2068: # the key does not exist
                   2069: 	return 'error: The key does not exist';
                   2070:     }
                   2071: }
                   2072: 
1.344     www      2073: # ------------------------------------------------------ Generate a set of keys
                   2074: 
                   2075: sub generate_access_keys {
1.364     www      2076:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2077:     $cdom=
1.620     albertel 2078:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2079:     $cnum=
1.620     albertel 2080:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2081:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2082:     unless (($cdom) && ($cnum)) { return 0; }
                   2083:     if ($number>10000) { return 0; }
                   2084:     sleep(2); # make sure don't get same seed twice
                   2085:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2086:     my $total=0;
                   2087:     for (my $i=1;$i<=$number;$i++) {
                   2088:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2089:                   sprintf("%lx",int(100000*rand)).'-'.
                   2090:                   sprintf("%lx",int(100000*rand));
                   2091:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2092:        $newkey=~s/0/h/g; # and also 0 and O
                   2093:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2094:        if ($existing{$newkey}) {
                   2095:            $i--;
                   2096:        } else {
1.364     www      2097: 	  if (&put('accesskeys',
                   2098:               { $newkey => '# generated '.localtime().
1.620     albertel 2099:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2100:                            '; '.$logentry },
                   2101: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2102:               $total++;
                   2103: 	  }
                   2104:        }
                   2105:     }
1.620     albertel 2106:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2107:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2108:     return $total;
                   2109: }
                   2110: 
                   2111: # ------------------------------------------------------- Validate an accesskey
                   2112: 
                   2113: sub validate_access_key {
                   2114:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2115:     $cdom=
1.620     albertel 2116:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2117:     $cnum=
1.620     albertel 2118:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2119:     $udom=$env{'user.domain'} unless (defined($udom));
                   2120:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2121:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2122:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2123: }
                   2124: 
                   2125: # ------------------------------------- Find the section of student in a course
1.652     albertel 2126: sub devalidate_getsection_cache {
                   2127:     my ($udom,$unam,$courseid)=@_;
                   2128:     my $hashid="$udom:$unam:$courseid";
                   2129:     &devalidate_cache_new('getsection',$hashid);
                   2130: }
1.298     matthew  2131: 
1.815     albertel 2132: sub courseid_to_courseurl {
                   2133:     my ($courseid) = @_;
                   2134:     #already url style courseid
                   2135:     return $courseid if ($courseid =~ m{^/});
                   2136: 
                   2137:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2138: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2139: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2140: 	return "/$cdom/$cnum";
                   2141:     }
                   2142: 
                   2143:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2144:     if (exists($courseinfo{'num'})) {
                   2145: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2146:     }
                   2147: 
                   2148:     return undef;
                   2149: }
                   2150: 
1.298     matthew  2151: sub getsection {
                   2152:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2153:     my $cachetime=1800;
1.551     albertel 2154: 
                   2155:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2156:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2157:     if (defined($cached)) { return $result; }
                   2158: 
1.298     matthew  2159:     my %Pending; 
                   2160:     my %Expired;
                   2161:     #
                   2162:     # Each role can either have not started yet (pending), be active, 
                   2163:     #    or have expired.
                   2164:     #
                   2165:     # If there is an active role, we are done.
                   2166:     #
                   2167:     # If there is more than one role which has not started yet, 
                   2168:     #     choose the one which will start sooner
                   2169:     # If there is one role which has not started yet, return it.
                   2170:     #
                   2171:     # If there is more than one expired role, choose the one which ended last.
                   2172:     # If there is a role which has expired, return it.
                   2173:     #
1.815     albertel 2174:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2175:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2176:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2177:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2178:         my $section=$1;
                   2179:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2180:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2181:         my $now=time;
1.548     albertel 2182:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2183:             $Expired{$end}=$section;
                   2184:             next;
                   2185:         }
1.548     albertel 2186:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2187:             $Pending{$start}=$section;
                   2188:             next;
                   2189:         }
1.599     albertel 2190:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2191:     }
                   2192:     #
                   2193:     # Presumedly there will be few matching roles from the above
                   2194:     # loop and the sorting time will be negligible.
                   2195:     if (scalar(keys(%Pending))) {
                   2196:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2197:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2198:     } 
                   2199:     if (scalar(keys(%Expired))) {
                   2200:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2201:         my $time = pop(@sorted);
1.599     albertel 2202:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2203:     }
1.599     albertel 2204:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2205: }
1.70      www      2206: 
1.599     albertel 2207: sub save_cache {
                   2208:     &purge_remembered();
1.722     albertel 2209:     #&Apache::loncommon::validate_page();
1.620     albertel 2210:     undef(%env);
1.780     albertel 2211:     undef($env_loaded);
1.599     albertel 2212: }
1.452     albertel 2213: 
1.599     albertel 2214: my $to_remember=-1;
                   2215: my %remembered;
                   2216: my %accessed;
                   2217: my $kicks=0;
                   2218: my $hits=0;
1.849     albertel 2219: sub make_key {
                   2220:     my ($name,$id) = @_;
1.872     albertel 2221:     if (length($id) > 65 
                   2222: 	&& length(&escape($id)) > 200) {
                   2223: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2224:     }
1.849     albertel 2225:     return &escape($name.':'.$id);
                   2226: }
                   2227: 
1.599     albertel 2228: sub devalidate_cache_new {
                   2229:     my ($name,$id,$debug) = @_;
                   2230:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2231:     $id=&make_key($name,$id);
1.599     albertel 2232:     $memcache->delete($id);
                   2233:     delete($remembered{$id});
                   2234:     delete($accessed{$id});
                   2235: }
                   2236: 
                   2237: sub is_cached_new {
                   2238:     my ($name,$id,$debug) = @_;
1.849     albertel 2239:     $id=&make_key($name,$id);
1.599     albertel 2240:     if (exists($remembered{$id})) {
1.1133    foxr     2241: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2242: 	$accessed{$id}=[&gettimeofday()];
                   2243: 	$hits++;
                   2244: 	return ($remembered{$id},1);
                   2245:     }
                   2246:     my $value = $memcache->get($id);
                   2247:     if (!(defined($value))) {
                   2248: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2249: 	return (undef,undef);
1.416     albertel 2250:     }
1.599     albertel 2251:     if ($value eq '__undef__') {
                   2252: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2253: 	$value=undef;
                   2254:     }
                   2255:     &make_room($id,$value,$debug);
                   2256:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2257:     return ($value,1);
                   2258: }
                   2259: 
                   2260: sub do_cache_new {
                   2261:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2262:     $id=&make_key($name,$id);
1.599     albertel 2263:     my $setvalue=$value;
                   2264:     if (!defined($setvalue)) {
                   2265: 	$setvalue='__undef__';
                   2266:     }
1.623     albertel 2267:     if (!defined($time) ) {
                   2268: 	$time=600;
                   2269:     }
1.599     albertel 2270:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2271:     my $result = $memcache->set($id,$setvalue,$time);
                   2272:     if (! $result) {
1.872     albertel 2273: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2274: 	$memcache->disconnect_all();
1.872     albertel 2275:     }
1.600     albertel 2276:     # need to make a copy of $value
1.919     albertel 2277:     &make_room($id,$value,$debug);
1.599     albertel 2278:     return $value;
                   2279: }
                   2280: 
                   2281: sub make_room {
                   2282:     my ($id,$value,$debug)=@_;
1.919     albertel 2283: 
                   2284:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2285:                                     : $value;
1.599     albertel 2286:     if ($to_remember<0) { return; }
                   2287:     $accessed{$id}=[&gettimeofday()];
                   2288:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2289:     my $to_kick;
                   2290:     my $max_time=0;
                   2291:     foreach my $other (keys(%accessed)) {
                   2292: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2293: 	    $to_kick=$other;
                   2294: 	    $max_time=&tv_interval($accessed{$other});
                   2295: 	}
                   2296:     }
                   2297:     delete($remembered{$to_kick});
                   2298:     delete($accessed{$to_kick});
                   2299:     $kicks++;
                   2300:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2301:     return;
                   2302: }
                   2303: 
1.599     albertel 2304: sub purge_remembered {
1.604     albertel 2305:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2306:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2307:     undef(%remembered);
                   2308:     undef(%accessed);
1.428     albertel 2309: }
1.70      www      2310: # ------------------------------------- Read an entry from a user's environment
                   2311: 
                   2312: sub userenvironment {
                   2313:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2314:     my $items;
                   2315:     foreach my $item (@what) {
                   2316:         $items.=&escape($item).'&';
                   2317:     }
                   2318:     $items=~s/\&$//;
1.70      www      2319:     my %returnhash=();
1.1009    raeburn  2320:     my $uhome = &homeserver($unam,$udom);
                   2321:     unless ($uhome eq 'no_host') {
                   2322:         my @answer=split(/\&/, 
                   2323:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2324:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2325:             return %returnhash;
                   2326:         }
1.1009    raeburn  2327:         my $i;
                   2328:         for ($i=0;$i<=$#what;$i++) {
                   2329: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2330:         }
1.70      www      2331:     }
                   2332:     return %returnhash;
1.1       albertel 2333: }
                   2334: 
1.617     albertel 2335: # ---------------------------------------------------------- Get a studentphoto
                   2336: sub studentphoto {
                   2337:     my ($udom,$unam,$ext) = @_;
                   2338:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2339:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2340:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2341:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2342:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2343:             } else {
                   2344:                 my ($result,$perm_reqd)=
1.707     albertel 2345: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2346:                 if ($result eq 'ok') {
                   2347:                     if (!($perm_reqd eq 'yes')) {
                   2348:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2349:                     }
                   2350:                 }
                   2351:             }
                   2352:         }
                   2353:     } else {
                   2354:         my ($result,$perm_reqd) = 
1.707     albertel 2355: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2356:         if ($result eq 'ok') {
                   2357:             if (!($perm_reqd eq 'yes')) {
                   2358:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2359:             }
                   2360:         }
                   2361:     }
                   2362:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2363: }
                   2364: 
                   2365: sub retrievestudentphoto {
                   2366:     my ($udom,$unam,$ext,$type) = @_;
                   2367:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2368:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2369:     if ($ret eq 'ok') {
                   2370:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2371:         if ($type eq 'thumbnail') {
                   2372:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2373:         }
                   2374:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2375:         return $tokenurl;
                   2376:     } else {
                   2377:         if ($type eq 'thumbnail') {
                   2378:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2379:         } else { 
                   2380:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2381:         }
1.617     albertel 2382:     }
                   2383: }
                   2384: 
1.263     www      2385: # -------------------------------------------------------------------- New chat
                   2386: 
                   2387: sub chatsend {
1.724     raeburn  2388:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2389:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2390:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2391:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2392:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2393: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2394: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2395: }
                   2396: 
                   2397: # ------------------------------------------ Find current version of a resource
                   2398: 
                   2399: sub getversion {
                   2400:     my $fname=&clutter(shift);
                   2401:     unless ($fname=~/^\/res\//) { return -1; }
                   2402:     return &currentversion(&filelocation('',$fname));
                   2403: }
                   2404: 
                   2405: sub currentversion {
                   2406:     my $fname=shift;
                   2407:     my $author=$fname;
                   2408:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2409:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2410:     my $home=&homeserver($uname,$udom);
1.292     www      2411:     if ($home eq 'no_host') { 
                   2412:         return -1; 
                   2413:     }
1.1112    www      2414:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2415:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2416: 	return -1;
                   2417:     }
1.1112    www      2418:     return $answer;
1.263     www      2419: }
                   2420: 
1.1111    www      2421: #
                   2422: # Return special version number of resource if set by override, empty otherwise
                   2423: #
                   2424: sub usedversion {
                   2425:     my $fname=shift;
                   2426:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2427:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2428:     if ($urlversion) { return $urlversion; }
                   2429:     return '';
                   2430: }
                   2431: 
1.1       albertel 2432: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2433: 
1.1       albertel 2434: sub subscribe {
                   2435:     my $fname=shift;
1.761     raeburn  2436:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2437:     $fname=~s/[\n\r]//g;
1.1       albertel 2438:     my $author=$fname;
                   2439:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2440:     my ($udom,$uname)=split(/\//,$author);
                   2441:     my $home=homeserver($uname,$udom);
1.335     albertel 2442:     if ($home eq 'no_host') {
                   2443:         return 'not_found';
1.1       albertel 2444:     }
                   2445:     my $answer=reply("sub:$fname",$home);
1.64      www      2446:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2447: 	$answer.=' by '.$home;
                   2448:     }
1.1       albertel 2449:     return $answer;
                   2450: }
                   2451:     
1.8       www      2452: # -------------------------------------------------------------- Replicate file
                   2453: 
                   2454: sub repcopy {
                   2455:     my $filename=shift;
1.23      www      2456:     $filename=~s/\/+/\//g;
1.1142    raeburn  2457:     my $londocroot = $perlvar{'lonDocRoot'};
                   2458:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2459:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2460:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2461: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2462: 	return &repcopy_userfile($filename);
                   2463:     }
1.532     albertel 2464:     $filename=~s/[\n\r]//g;
1.8       www      2465:     my $transname="$filename.in.transfer";
1.828     www      2466: # FIXME: this should flock
1.607     raeburn  2467:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2468:     my $remoteurl=subscribe($filename);
1.64      www      2469:     if ($remoteurl =~ /^con_lost by/) {
                   2470: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2471:            return 'unavailable';
1.8       www      2472:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2473: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2474: 	   return 'not_found';
1.64      www      2475:     } elsif ($remoteurl =~ /^rejected by/) {
                   2476: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2477:            return 'forbidden';
1.20      www      2478:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2479:            return 'ok';
1.8       www      2480:     } else {
1.290     www      2481:         my $author=$filename;
                   2482:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2483:         my ($udom,$uname)=split(/\//,$author);
                   2484:         my $home=homeserver($uname,$udom);
                   2485:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2486:            my @parts=split(/\//,$filename);
                   2487:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2488:            if ($path ne "$londocroot/res") {
1.8       www      2489:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2490: 	       return 'bad_request';
1.8       www      2491:            }
                   2492:            my $count;
                   2493:            for ($count=5;$count<$#parts;$count++) {
                   2494:                $path.="/$parts[$count]";
                   2495:                if ((-e $path)!=1) {
                   2496: 		   mkdir($path,0777);
                   2497:                }
                   2498:            }
                   2499:            my $ua=new LWP::UserAgent;
                   2500:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2501:            my $response=$ua->request($request,$transname);
                   2502:            if ($response->is_error()) {
                   2503: 	       unlink($transname);
                   2504:                my $message=$response->status_line;
1.672     albertel 2505:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2506:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2507:                return 'unavailable';
1.8       www      2508:            } else {
1.16      www      2509: 	       if ($remoteurl!~/\.meta$/) {
                   2510:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2511:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2512:                   if ($mresponse->is_error()) {
                   2513: 		      unlink($filename.'.meta');
                   2514:                       &logthis(
1.672     albertel 2515:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2516:                   }
                   2517: 	       }
1.8       www      2518:                rename($transname,$filename);
1.607     raeburn  2519:                return 'ok';
1.8       www      2520:            }
1.290     www      2521:        }
1.8       www      2522:     }
1.330     www      2523: }
                   2524: 
                   2525: # ------------------------------------------------ Get server side include body
                   2526: sub ssi_body {
1.381     albertel 2527:     my ($filelink,%form)=@_;
1.606     matthew  2528:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2529:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2530:     }
1.953     www      2531:     my $output='';
                   2532:     my $response;
1.980     raeburn  2533:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2534:        ($output,$response)=&externalssi($filelink);
1.953     www      2535:     } else {
1.1004    droeschl 2536:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2537:        $filelink .= 'inhibitmenu=yes';
1.953     www      2538:        ($output,$response)=&ssi($filelink,%form);
                   2539:     }
1.778     albertel 2540:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2541:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2542:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2543:     if (wantarray) {
                   2544:         return ($output, $response);
                   2545:     } else {
                   2546:         return $output;
                   2547:     }
1.8       www      2548: }
                   2549: 
1.15      www      2550: # --------------------------------------------------------- Server Side Include
                   2551: 
1.782     albertel 2552: sub absolute_url {
                   2553:     my ($host_name) = @_;
                   2554:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2555:     if ($host_name eq '') {
                   2556: 	$host_name = $ENV{'SERVER_NAME'};
                   2557:     }
                   2558:     return $protocol.$host_name;
                   2559: }
                   2560: 
1.942     foxr     2561: #
                   2562: #   Server side include.
                   2563: # Parameters:
                   2564: #  fn     Possibly encrypted resource name/id.
                   2565: #  form   Hash that describes how the rendering should be done
                   2566: #         and other things.
1.944     foxr     2567: # Returns:
1.950     raeburn  2568: #   Scalar context: The content of the response.
                   2569: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2570: #     
1.15      www      2571: sub ssi {
                   2572: 
1.944     foxr     2573:     my ($fn,%form)=@_;
1.15      www      2574:     my $ua=new LWP::UserAgent;
1.23      www      2575:     my $request;
1.711     albertel 2576: 
                   2577:     $form{'no_update_last_known'}=1;
1.895     albertel 2578:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2579:     if (%form) {
1.782     albertel 2580:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2581:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2582:     } else {
1.782     albertel 2583:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2584:     }
                   2585: 
1.15      www      2586:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2587:     my $response= $ua->request($request);
                   2588:     my $content = Encode::decode_utf8($response->content);
1.944     foxr     2589:     if (wantarray) {
1.1173    foxr     2590: 	return ($content, $response);
1.944     foxr     2591:     } else {
1.1173    foxr     2592: 	return $content;
1.942     foxr     2593:     }
1.324     www      2594: }
                   2595: 
                   2596: sub externalssi {
                   2597:     my ($url)=@_;
                   2598:     my $ua=new LWP::UserAgent;
                   2599:     my $request=new HTTP::Request('GET',$url);
                   2600:     my $response=$ua->request($request);
1.954     raeburn  2601:     if (wantarray) {
                   2602:         return ($response->content, $response);
                   2603:     } else {
                   2604:         return $response->content;
                   2605:     }
1.15      www      2606: }
1.254     www      2607: 
1.492     albertel 2608: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2609: 
                   2610: sub allowuploaded {
                   2611:     my ($srcurl,$url)=@_;
                   2612:     $url=&clutter(&declutter($url));
                   2613:     my $dir=$url;
                   2614:     $dir=~s/\/[^\/]+$//;
                   2615:     my %httpref=();
                   2616:     my $httpurl=&hreflocation('',$url);
                   2617:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2618:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2619: }
1.477     raeburn  2620: 
1.478     albertel 2621: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2622: # input: action, courseID, current domain, intended
1.637     raeburn  2623: #        path to file, source of file, instruction to parse file for objects,
                   2624: #        ref to hash for embedded objects,
                   2625: #        ref to hash for codebase of java objects.
1.1095    raeburn  2626: #        reference to scalar to accommodate mime type determined
                   2627: #          from File::MMagic if $parser = parse.
1.637     raeburn  2628: #
1.485     raeburn  2629: # output: url to file (if action was uploaddoc), 
                   2630: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2631: #
1.478     albertel 2632: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2633: # course.
1.477     raeburn  2634: #
1.478     albertel 2635: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2636: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2637: #          course's home server.
1.477     raeburn  2638: #
1.478     albertel 2639: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2640: #          be copied from $source (current location) to 
                   2641: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2642: #         and will then be copied to
                   2643: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2644: #         course's home server.
1.485     raeburn  2645: #
1.481     raeburn  2646: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2647: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2648: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2649: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2650: #         in course's home server.
1.637     raeburn  2651: #
1.477     raeburn  2652: 
                   2653: sub process_coursefile {
1.1095    raeburn  2654:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2655:         $mimetype)=@_;
1.477     raeburn  2656:     my $fetchresult;
1.638     albertel 2657:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2658:     if ($action eq 'propagate') {
1.638     albertel 2659:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2660: 			     $home);
1.481     raeburn  2661:     } else {
1.477     raeburn  2662:         my $fpath = '';
                   2663:         my $fname = $file;
1.478     albertel 2664:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2665:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2666:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2667:         if ($action eq 'copy') {
                   2668:             if ($source eq '') {
                   2669:                 $fetchresult = 'no source file';
                   2670:                 return $fetchresult;
                   2671:             } else {
                   2672:                 my $destination = $filepath.'/'.$fname;
                   2673:                 rename($source,$destination);
                   2674:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2675:                                  $home);
1.481     raeburn  2676:             }
                   2677:         } elsif ($action eq 'uploaddoc') {
                   2678:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2679:             print $fh $env{'form.'.$source};
1.481     raeburn  2680:             close($fh);
1.637     raeburn  2681:             if ($parser eq 'parse') {
1.1024    raeburn  2682:                 my $mm = new File::MMagic;
1.1095    raeburn  2683:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2684:                 if ($type eq 'text/html') {
1.1024    raeburn  2685:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2686:                     unless ($parse_result eq 'ok') {
                   2687:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2688:                     }
1.637     raeburn  2689:                 }
1.1095    raeburn  2690:                 if (ref($mimetype)) {
                   2691:                     $$mimetype = $type;
                   2692:                 } 
1.637     raeburn  2693:             }
1.477     raeburn  2694:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2695:                                  $home);
1.481     raeburn  2696:             if ($fetchresult eq 'ok') {
                   2697:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2698:             } else {
                   2699:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2700:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2701:                 return '/adm/notfound.html';
                   2702:             }
1.477     raeburn  2703:         }
                   2704:     }
1.485     raeburn  2705:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2706:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2707:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2708:     }
                   2709:     return $fetchresult;
                   2710: }
                   2711: 
1.637     raeburn  2712: sub build_filepath {
                   2713:     my ($fpath) = @_;
                   2714:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2715:     unless ($fpath eq '') {
                   2716:         my @parts=split('/',$fpath);
                   2717:         foreach my $part (@parts) {
                   2718:             $filepath.= '/'.$part;
                   2719:             if ((-e $filepath)!=1) {
                   2720:                 mkdir($filepath,0777);
                   2721:             }
                   2722:         }
                   2723:     }
                   2724:     return $filepath;
                   2725: }
                   2726: 
                   2727: sub store_edited_file {
1.638     albertel 2728:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2729:     my $file = $primary_url;
                   2730:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2731:     my $fpath = '';
                   2732:     my $fname = $file;
                   2733:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2734:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2735:     my $filepath = &build_filepath($fpath);
                   2736:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2737:     print $fh $content;
                   2738:     close($fh);
1.638     albertel 2739:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2740:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2741: 			  $home);
1.637     raeburn  2742:     if ($$fetchresult eq 'ok') {
                   2743:         return '/uploaded/'.$fpath.'/'.$fname;
                   2744:     } else {
1.638     albertel 2745:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2746: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2747:         return '/adm/notfound.html';
                   2748:     }
                   2749: }
                   2750: 
1.531     albertel 2751: sub clean_filename {
1.831     albertel 2752:     my ($fname,$args)=@_;
1.315     www      2753: # Replace Windows backslashes by forward slashes
1.257     www      2754:     $fname=~s/\\/\//g;
1.831     albertel 2755:     if (!$args->{'keep_path'}) {
                   2756:         # Get rid of everything but the actual filename
                   2757: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2758:     }
1.315     www      2759: # Replace spaces by underscores
                   2760:     $fname=~s/\s+/\_/g;
                   2761: # Replace all other weird characters by nothing
1.831     albertel 2762:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2763: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2764: # numbers
                   2765:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2766:     return $fname;
                   2767: }
1.1051    raeburn  2768: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2769: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2770: # image with the same aspect ratio as the original, but with dimensions which do 
                   2771: # not exceed $resizewidth and $resizeheight.
                   2772:  
1.984     neumanie 2773: sub resizeImage {
1.1051    raeburn  2774:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2775:     my $ima = Image::Magick->new;
                   2776:     my $resized;
                   2777:     if (-e $img_path) {
                   2778:         $ima->Read($img_path);
                   2779:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2780:             my $width = $ima->Get('width');
                   2781:             my $height = $ima->Get('height');
                   2782:             if ($width > $resizewidth) {
                   2783: 	        my $factor = $width/$resizewidth;
                   2784:                 my $newheight = $height/$factor;
                   2785:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2786:                 $resized = 1;
                   2787:             }
                   2788:         }
                   2789:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2790:             my $width = $ima->Get('width');
                   2791:             my $height = $ima->Get('height');
                   2792:             if ($height > $resizeheight) {
                   2793:                 my $factor = $height/$resizeheight;
                   2794:                 my $newwidth = $width/$factor;
                   2795:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2796:                 $resized = 1;
                   2797:             }
                   2798:         }
                   2799:         if ($resized) {
                   2800:             $ima->Write($img_path);
                   2801:         }
                   2802:     }
                   2803:     return;
1.977     amueller 2804: }
                   2805: 
1.608     albertel 2806: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2807: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2808: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2809: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2810: #                                    canceloverwrite, or ''. 
                   2811: #                   if 'coursedoc': upload to the current course
                   2812: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2813: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2814: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2815: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2816: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2817: #        $allfiles - reference to hash for embedded objects
                   2818: #        $codebase - reference to hash for codebase of java objects
                   2819: #        $desuname - username for permanent storage of uploaded file
                   2820: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2821: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2822: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2823: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2824: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2825: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2826: #                    from File::MMagic.
1.858     raeburn  2827: # 
1.686     albertel 2828: # output: url of file in userspace, or error: <message> 
                   2829: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2830: 
1.531     albertel 2831: sub userfileupload {
1.1090    raeburn  2832:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2833:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2834:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2835:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2836:     $fname=&clean_filename($fname);
1.1090    raeburn  2837:     # See if there is anything left
1.257     www      2838:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2839:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2840:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2841:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2842:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2843:         my $now = time;
1.1090    raeburn  2844:         my $filepath;
1.1095    raeburn  2845:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2846:              $filepath = 'tmp/helprequests/'.$now;
                   2847:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2848:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2849:                          '_'.$env{'user.domain'}.'/pending';
                   2850:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2851:             my ($docuname,$docudom);
                   2852:             if ($destudom) {
                   2853:                 $docudom = $destudom;
                   2854:             } else {
                   2855:                 $docudom = $env{'user.domain'};
                   2856:             }
                   2857:             if ($destuname) {
                   2858:                 $docuname = $destuname;
                   2859:             } else {
                   2860:                 $docuname = $env{'user.name'};
                   2861:             }
                   2862:             if (exists($env{'form.group'})) {
                   2863:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2864:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2865:             }
                   2866:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2867:             if ($context eq 'canceloverwrite') {
                   2868:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2869:                 if (-e  $tempfile) {
                   2870:                     my @info = stat($tempfile);
                   2871:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2872:                         unlink($tempfile);
                   2873:                     }
                   2874:                 }
                   2875:                 return;
1.523     raeburn  2876:             }
                   2877:         }
1.1090    raeburn  2878:         # Create the directory if not present
1.741     raeburn  2879:         my @parts=split(/\//,$filepath);
                   2880:         my $fullpath = $perlvar{'lonDaemons'};
                   2881:         for (my $i=0;$i<@parts;$i++) {
                   2882:             $fullpath .= '/'.$parts[$i];
                   2883:             if ((-e $fullpath)!=1) {
                   2884:                 mkdir($fullpath,0777);
                   2885:             }
                   2886:         }
                   2887:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2888:         print $fh $env{'form.'.$formname};
                   2889:         close($fh);
1.1090    raeburn  2890:         if ($context eq 'existingfile') {
                   2891:             my @info = stat($fullpath.'/'.$fname);
                   2892:             return ($fullpath.'/'.$fname,$info[9]);
                   2893:         } else {
                   2894:             return $fullpath.'/'.$fname;
                   2895:         }
1.523     raeburn  2896:     }
1.995     raeburn  2897:     if ($subdir eq 'scantron') {
                   2898:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2899:     } else {
1.995     raeburn  2900:         $fname="$subdir/$fname";
                   2901:     }
1.1090    raeburn  2902:     if ($context eq 'coursedoc') {
1.638     albertel 2903: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2904: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2905:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2906:             return &finishuserfileupload($docuname,$docudom,
                   2907: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2908: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2909:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2910:         } else {
1.620     albertel 2911:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2912:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2913: 				       $fname,$formname,$parser,
1.1095    raeburn  2914: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2915:         }
1.719     banghart 2916:     } elsif (defined($destuname)) {
                   2917:         my $docuname=$destuname;
                   2918:         my $docudom=$destudom;
1.860     raeburn  2919: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2920: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2921:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2922:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2923:     } else {
1.638     albertel 2924:         my $docuname=$env{'user.name'};
                   2925:         my $docudom=$env{'user.domain'};
1.714     raeburn  2926:         if (exists($env{'form.group'})) {
                   2927:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2928:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2929:         }
1.860     raeburn  2930: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2931: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2932:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2933:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2934:     }
1.271     www      2935: }
                   2936: 
                   2937: sub finishuserfileupload {
1.860     raeburn  2938:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2939:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2940:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2941:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2942:   
1.860     raeburn  2943:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2944:     $file=$fname;
                   2945:     if ($fname=~m|/|) {
                   2946:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2947: 	$path.=$fnamepath.'/';
                   2948:     }
1.259     www      2949:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2950:     my $count;
                   2951:     for ($count=4;$count<=$#parts;$count++) {
                   2952:         $filepath.="/$parts[$count]";
                   2953:         if ((-e $filepath)!=1) {
                   2954: 	    mkdir($filepath,0777);
                   2955:         }
                   2956:     }
1.984     neumanie 2957: 
1.258     www      2958: # Save the file
                   2959:     {
1.701     albertel 2960: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2961: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2962: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2963: 	    return '/adm/notfound.html';
                   2964: 	}
1.1090    raeburn  2965:         if ($context eq 'overwrite') {
1.1117    foxr     2966:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2967:             my $target = $filepath.'/'.$file;
                   2968:             if (-e $source) {
                   2969:                 my @info = stat($source);
                   2970:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2971:                     unless (&File::Copy::move($source,$target)) {
                   2972:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2973:                         return "Moving from $source failed";
                   2974:                     }
                   2975:                 } else {
                   2976:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2977:                 }
                   2978:             } else {
                   2979:                 return "Temporary file: $source missing";
                   2980:             }
                   2981:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2982: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2983: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2984: 	    return '/adm/notfound.html';
                   2985: 	}
1.570     albertel 2986: 	close(FH);
1.1051    raeburn  2987:         if ($resizewidth && $resizeheight) {
                   2988:             my $mm = new File::MMagic;
                   2989:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2990:             if ($mime_type =~ m{^image/}) {
                   2991: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2992:             }  
1.977     amueller 2993: 	}
1.258     www      2994:     }
1.1152    raeburn  2995:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   2996:         if (ref($mimetype)) {
                   2997:             if ($$mimetype eq '') {
                   2998:                 my $mm = new File::MMagic;
                   2999:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   3000:                 $$mimetype = $type;
                   3001:             }
                   3002:         }
                   3003:     }
1.637     raeburn  3004:     if ($parser eq 'parse') {
1.1152    raeburn  3005:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  3006:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   3007:                                                        $allfiles,$codebase);
                   3008:             unless ($parse_result eq 'ok') {
                   3009:                 &logthis('Failed to parse '.$filepath.$file.
                   3010: 	   	         ' for embedded media: '.$parse_result); 
                   3011:             }
1.637     raeburn  3012:         }
                   3013:     }
1.860     raeburn  3014:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3015:         my $input = $filepath.'/'.$file;
                   3016:         my $output = $filepath.'/'.'tn-'.$file;
                   3017:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3018:         system("convert -sample $thumbsize $input $output");
                   3019:         if (-e $filepath.'/'.'tn-'.$file) {
                   3020:             $fetchthumb  = 1; 
                   3021:         }
                   3022:     }
1.858     raeburn  3023:  
1.259     www      3024: # Notify homeserver to grep it
                   3025: #
1.984     neumanie 3026:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3027:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3028:     if ($fetchresult eq 'ok') {
1.860     raeburn  3029:         if ($fetchthumb) {
                   3030:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3031:             if ($thumbresult ne 'ok') {
                   3032:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3033:                          $docuhome.': '.$thumbresult);
                   3034:             }
                   3035:         }
1.259     www      3036: #
1.258     www      3037: # Return the URL to it
1.494     albertel 3038:         return '/uploaded/'.$path.$file;
1.263     www      3039:     } else {
1.494     albertel 3040:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3041: 		 ': '.$fetchresult);
1.263     www      3042:         return '/adm/notfound.html';
1.858     raeburn  3043:     }
1.493     albertel 3044: }
                   3045: 
1.637     raeburn  3046: sub extract_embedded_items {
1.961     raeburn  3047:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3048:     my @state = ();
1.1164    raeburn  3049:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3050:     my %javafiles = (
                   3051:                       codebase => '',
                   3052:                       code => '',
                   3053:                       archive => ''
                   3054:                     );
                   3055:     my %mediafiles = (
                   3056:                       src => '',
                   3057:                       movie => '',
                   3058:                      );
1.648     raeburn  3059:     my $p;
                   3060:     if ($content) {
                   3061:         $p = HTML::LCParser->new($content);
                   3062:     } else {
1.961     raeburn  3063:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3064:     }
1.641     albertel 3065:     while (my $t=$p->get_token()) {
1.640     albertel 3066: 	if ($t->[0] eq 'S') {
                   3067: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3068: 	    push(@state, $tagname);
1.648     raeburn  3069:             if (lc($tagname) eq 'allow') {
                   3070:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3071:             }
1.640     albertel 3072: 	    if (lc($tagname) eq 'img') {
                   3073: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3074: 	    }
1.886     albertel 3075: 	    if (lc($tagname) eq 'a') {
                   3076: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3077: 	    }
1.645     raeburn  3078:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3079:                 my $src;
1.645     raeburn  3080:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3081:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3082:                 } else {
1.1164    raeburn  3083:                     if ($attr->{'src'} ne '') {
                   3084:                         $src = $attr->{'src'};
                   3085:                         &add_filetype($allfiles,$src,'src');
                   3086:                     }
                   3087:                 }
                   3088:                 my $text = $p->get_trimmed_text();
                   3089:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3090:                     my @swfargs = split(/,/,$1);
                   3091:                     foreach my $item (@swfargs) {
                   3092:                         $item =~ s/["']//g;
                   3093:                         $item =~ s/^\s+//;
                   3094:                         $item =~ s/\s+$//;
                   3095:                     }
                   3096:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3097:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3098:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3099:                         } else {
                   3100:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3101:                         }
                   3102:                     }
1.645     raeburn  3103:                 }
                   3104:             }
                   3105:             if (lc($tagname) eq 'link') {
                   3106:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3107:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3108:                 }
                   3109:             }
1.640     albertel 3110: 	    if (lc($tagname) eq 'object' ||
                   3111: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3112: 		foreach my $item (keys(%javafiles)) {
                   3113: 		    $javafiles{$item} = '';
                   3114: 		}
1.1164    raeburn  3115:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3116:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3117:                 }
1.640     albertel 3118: 	    }
                   3119: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3120: 		my $name = lc($attr->{'name'});
                   3121: 		foreach my $item (keys(%javafiles)) {
                   3122: 		    if ($name eq $item) {
                   3123: 			$javafiles{$item} = $attr->{'value'};
                   3124: 			last;
                   3125: 		    }
                   3126: 		}
1.1164    raeburn  3127:                 my $pathfrom;
1.640     albertel 3128: 		foreach my $item (keys(%mediafiles)) {
                   3129: 		    if ($name eq $item) {
1.1164    raeburn  3130:                         $pathfrom = $attr->{'value'};
                   3131:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3132: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3133: 			last;
                   3134: 		    }
                   3135: 		}
1.1164    raeburn  3136:                 if ($name eq 'flashvars') {
                   3137:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3138:                 }
                   3139:                 if ($pathfrom ne '') {
                   3140:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3141:                                          $pathfrom);
                   3142:                 }
1.640     albertel 3143: 	    }
                   3144: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3145: 		foreach my $item (keys(%javafiles)) {
                   3146: 		    if ($attr->{$item}) {
                   3147: 			$javafiles{$item} = $attr->{$item};
                   3148: 			last;
                   3149: 		    }
                   3150: 		}
                   3151: 		foreach my $item (keys(%mediafiles)) {
                   3152: 		    if ($attr->{$item}) {
                   3153: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3154: 			last;
                   3155: 		    }
                   3156: 		}
1.1164    raeburn  3157:                 if (lc($tagname) eq 'embed') {
                   3158:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3159:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3160:                                              $attr->{'src'});
                   3161:                     }
                   3162:                 }
1.640     albertel 3163: 	    }
1.1164    raeburn  3164:             if ($t->[4] =~ m{/>$}) {
                   3165:                 pop(@state);  
                   3166:             }
1.640     albertel 3167: 	} elsif ($t->[0] eq 'E') {
                   3168: 	    my ($tagname) = ($t->[1]);
                   3169: 	    if ($javafiles{'codebase'} ne '') {
                   3170: 		$javafiles{'codebase'} .= '/';
                   3171: 	    }  
                   3172: 	    if (lc($tagname) eq 'applet' ||
                   3173: 		lc($tagname) eq 'object' ||
                   3174: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3175: 		) {
                   3176: 		foreach my $item (keys(%javafiles)) {
                   3177: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3178: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3179: 			&add_filetype($allfiles,$file,$item);
                   3180: 		    }
                   3181: 		}
                   3182: 	    } 
                   3183: 	    pop @state;
                   3184: 	}
                   3185:     }
1.1164    raeburn  3186:     foreach my $id (sort(keys(%flashvars))) {
                   3187:         if ($shockwave{$id} ne '') {
                   3188:             my @pairs = split(/\&/,$flashvars{$id});
                   3189:             foreach my $pair (@pairs) {
                   3190:                 my ($key,$value) = split(/\=/,$pair);
                   3191:                 if ($key eq 'thumb') {
                   3192:                     &add_filetype($allfiles,$value,$key);
                   3193:                 } elsif ($key eq 'content') {
                   3194:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3195:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3196:                     if ($ext ne '') {
                   3197:                         &add_filetype($allfiles,$path.$value,$ext);
                   3198:                     }
                   3199:                 }
                   3200:             }
                   3201:         }
                   3202:     }
1.637     raeburn  3203:     return 'ok';
                   3204: }
                   3205: 
1.639     albertel 3206: sub add_filetype {
                   3207:     my ($allfiles,$file,$type)=@_;
                   3208:     if (exists($allfiles->{$file})) {
                   3209: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3210: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3211: 	}
                   3212:     } else {
                   3213: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3214:     }
                   3215: }
                   3216: 
1.1164    raeburn  3217: sub embedded_dependency {
                   3218:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3219:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3220:         if (($identifier ne '') &&
                   3221:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3222:             ($pathfrom ne '')) {
                   3223:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3224:             foreach my $dep (@{$related->{$identifier}}) {
                   3225:                 &add_filetype($allfiles,$path.$dep,'object');
                   3226:             }
                   3227:         }
                   3228:     }
                   3229:     return;
                   3230: }
                   3231: 
1.493     albertel 3232: sub removeuploadedurl {
1.984     neumanie 3233:     my ($url)=@_;	
                   3234:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3235:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3236: }
                   3237: 
                   3238: sub removeuserfile {
                   3239:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3240:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3241:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3242:     if ($result eq 'ok') {	
1.798     raeburn  3243:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3244:             my $metafile = $fname.'.meta';
                   3245:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3246: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3247:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3248:             my $sqlresult = 
1.823     albertel 3249:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3250:                                         'portfolio_metadata',$group,
                   3251:                                         'delete');
1.798     raeburn  3252:         }
                   3253:     }
                   3254:     return $result;
1.257     www      3255: }
1.15      www      3256: 
1.530     albertel 3257: sub mkdiruserfile {
                   3258:     my ($docuname,$docudom,$dir)=@_;
                   3259:     my $home=&homeserver($docuname,$docudom);
                   3260:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3261: }
                   3262: 
1.531     albertel 3263: sub renameuserfile {
                   3264:     my ($docuname,$docudom,$old,$new)=@_;
                   3265:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3266:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3267:                         &escape("$old").':'.&escape("$new"),$home);
                   3268:     if ($result eq 'ok') {
                   3269:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3270:             my $oldmeta = $old.'.meta';
                   3271:             my $newmeta = $new.'.meta';
                   3272:             my $metaresult = 
                   3273:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3274: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3275:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3276:             my $sqlresult = 
1.823     albertel 3277:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3278:                                         'portfolio_metadata',$group,
                   3279:                                         'delete');
1.798     raeburn  3280:         }
                   3281:     }
                   3282:     return $result;
1.531     albertel 3283: }
                   3284: 
1.14      www      3285: # ------------------------------------------------------------------------- Log
                   3286: 
                   3287: sub log {
                   3288:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3289:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3290: }
                   3291: 
                   3292: # ------------------------------------------------------------------ Course Log
1.352     www      3293: #
                   3294: # This routine flushes several buffers of non-mission-critical nature
                   3295: #
1.157     www      3296: 
                   3297: sub flushcourselogs {
1.352     www      3298:     &logthis('Flushing log buffers');
                   3299: #
                   3300: # course logs
                   3301: # This is a log of all transactions in a course, which can be used
                   3302: # for data mining purposes
                   3303: #
                   3304: # It also collects the courseid database, which lists last transaction
                   3305: # times and course titles for all courseids
                   3306: #
                   3307:     my %courseidbuffer=();
1.921     raeburn  3308:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3309:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3310: 		          &escape($courselogs{$crsid}),
                   3311: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3312: 	    delete $courselogs{$crsid};
                   3313:         } else {
                   3314:             &logthis('Failed to flush log buffer for '.$crsid);
                   3315:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3316:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3317:                         " exceeded maximum size, deleting.</font>");
                   3318:                delete $courselogs{$crsid};
                   3319:             }
1.352     www      3320:         }
1.920     raeburn  3321:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3322:             'description' => $coursedescrbuf{$crsid},
                   3323:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3324:             'type'        => $coursetypebuf{$crsid},
                   3325:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3326:         };
1.191     harris41 3327:     }
1.352     www      3328: #
                   3329: # Write course id database (reverse lookup) to homeserver of courses 
                   3330: # Is used in pickcourse
                   3331: #
1.840     albertel 3332:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3333:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3334:                                     $courseidbuffer{$crs_home},
                   3335:                                     $crs_home,'timeonly');
1.352     www      3336:     }
                   3337: #
                   3338: # File accesses
                   3339: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3340: #
1.449     matthew  3341:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3342:         if ($entry =~ /___count$/) {
                   3343:             my ($dom,$name);
1.807     albertel 3344:             ($dom,$name,undef)=
1.811     albertel 3345: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3346:             if (! defined($dom) || $dom eq '' || 
                   3347:                 ! defined($name) || $name eq '') {
1.620     albertel 3348:                 my $cid = $env{'request.course.id'};
                   3349:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3350:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3351:             }
1.450     matthew  3352:             my $value = $accesshash{$entry};
                   3353:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3354:             my %temphash=($url => $value);
1.449     matthew  3355:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3356:             if ($result eq 'ok') {
                   3357:                 delete $accesshash{$entry};
                   3358:             }
                   3359:         } else {
1.811     albertel 3360:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3361:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3362:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3363:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3364:                 delete $accesshash{$entry};
                   3365:             }
1.185     www      3366:         }
1.191     harris41 3367:     }
1.352     www      3368: #
                   3369: # Roles
                   3370: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3371: #
1.800     albertel 3372:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3373:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3374: 	    split(/\:/,$entry);
                   3375:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3376:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3377:                 $rudom,$runame) eq 'ok') {
                   3378: 	    delete $userrolehash{$entry};
                   3379:         }
                   3380:     }
1.662     raeburn  3381: #
                   3382: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3383: #
                   3384:     my %domrolebuffer = ();
1.1000    raeburn  3385:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3386:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3387:         if ($domrolebuffer{$rudom}) {
                   3388:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3389:                       '='.&escape($domainrolehash{$entry});
                   3390:         } else {
                   3391:             $domrolebuffer{$rudom}.=&escape($entry).
                   3392:                       '='.&escape($domainrolehash{$entry});
                   3393:         }
                   3394:         delete $domainrolehash{$entry};
                   3395:     }
                   3396:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3397: 	my %servers = &get_servers($dom,'library');
                   3398: 	foreach my $tryserver (keys(%servers)) {
                   3399: 	    unless (&reply('domroleput:'.$dom.':'.
                   3400: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3401: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3402: 	    }
1.662     raeburn  3403:         }
                   3404:     }
1.186     www      3405:     $dumpcount++;
1.157     www      3406: }
                   3407: 
                   3408: sub courselog {
                   3409:     my $what=shift;
1.158     www      3410:     $what=time.':'.$what;
1.620     albertel 3411:     unless ($env{'request.course.id'}) { return ''; }
                   3412:     $coursedombuf{$env{'request.course.id'}}=
                   3413:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3414:     $coursenumbuf{$env{'request.course.id'}}=
                   3415:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3416:     $coursehombuf{$env{'request.course.id'}}=
                   3417:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3418:     $coursedescrbuf{$env{'request.course.id'}}=
                   3419:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3420:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3421:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3422:     $courseownerbuf{$env{'request.course.id'}}=
                   3423:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3424:     $coursetypebuf{$env{'request.course.id'}}=
                   3425:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3426:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3427: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3428:     } else {
1.620     albertel 3429: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3430:     }
1.620     albertel 3431:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3432: 	&flushcourselogs();
                   3433:     }
1.158     www      3434: }
                   3435: 
                   3436: sub courseacclog {
                   3437:     my $fnsymb=shift;
1.620     albertel 3438:     unless ($env{'request.course.id'}) { return ''; }
                   3439:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3440:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3441:         $what.=':POST';
1.583     matthew  3442:         # FIXME: Probably ought to escape things....
1.800     albertel 3443: 	foreach my $key (keys(%env)) {
                   3444:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3445:                 my $formitem = $1;
                   3446:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3447:                     $what.=':'.$formitem.'='.$env{$key};
                   3448:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3449:                     $what.=':'.$formitem.'='.$env{$key};
                   3450:                 }
1.158     www      3451:             }
1.191     harris41 3452:         }
1.583     matthew  3453:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3454:         # FIXME: We should not be depending on a form parameter that someone
                   3455:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3456:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3457:             $what.= ':POST';
                   3458:             # FIXME: Probably ought to escape things....
                   3459:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3460:                                  'crsdiscuss') {
1.620     albertel 3461:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3462:             }
                   3463:         }
1.158     www      3464:     }
                   3465:     &courselog($what);
1.149     www      3466: }
                   3467: 
1.185     www      3468: sub countacc {
                   3469:     my $url=&declutter(shift);
1.458     matthew  3470:     return if (! defined($url) || $url eq '');
1.620     albertel 3471:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3472: #
                   3473: # Mark that this url was used in this course
                   3474: #
1.620     albertel 3475:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3476: #
                   3477: # Increase the access count for this resource in this child process
                   3478: #
1.281     www      3479:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3480:     $accesshash{$key}++;
1.185     www      3481: }
1.349     www      3482: 
1.361     www      3483: sub linklog {
                   3484:     my ($from,$to)=@_;
                   3485:     $from=&declutter($from);
                   3486:     $to=&declutter($to);
                   3487:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3488:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3489: }
1.1160    www      3490: 
                   3491: sub statslog {
                   3492:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3493:     if ($users<2) { return; }
                   3494:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3495:             'course'       => $env{'request.course.id'},
                   3496:             'sections'     => '"all"',
                   3497:             'num_students' => $users,
                   3498:             'part'         => $part,
                   3499:             'symb'         => $symb,
                   3500:             'mean_tries'   => $av_attempts,
                   3501:             'deg_of_diff'  => $degdiff});
                   3502:     foreach my $key (keys(%dynstore)) {
                   3503:         $accesshash{$key}=$dynstore{$key};
                   3504:     }
                   3505: }
1.361     www      3506:   
1.349     www      3507: sub userrolelog {
                   3508:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3509:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3510:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3511:        $userrolehash
                   3512:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3513:                     =$tend.':'.$tstart;
1.662     raeburn  3514:     }
1.1169    droeschl 3515:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3516:        $userrolehash
                   3517:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3518:                     =$tend.':'.$tstart;
                   3519:     }
1.1169    droeschl 3520:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3521:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3522:        $domainrolehash
                   3523:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3524:                     = $tend.':'.$tstart;
                   3525:     }
1.351     www      3526: }
                   3527: 
1.957     raeburn  3528: sub courserolelog {
                   3529:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3530:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3531:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3532:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3533:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3534:         ($trole eq 'co')) {
1.957     raeburn  3535:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3536:             my $cdom = $1;
                   3537:             my $cnum = $2;
                   3538:             my $sec = $3;
                   3539:             my $namespace = 'rolelog';
                   3540:             my %storehash = (
                   3541:                                role    => $trole,
                   3542:                                start   => $tstart,
                   3543:                                end     => $tend,
                   3544:                                selfenroll => $selfenroll,
                   3545:                                context    => $context,
                   3546:                             );
                   3547:             if ($trole eq 'gr') {
                   3548:                 $namespace = 'groupslog';
                   3549:                 $storehash{'group'} = $sec;
                   3550:             } else {
                   3551:                 $storehash{'section'} = $sec;
                   3552:             }
                   3553:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3554:             if (($trole ne 'st') || ($sec ne '')) {
                   3555:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3556:             }
1.957     raeburn  3557:         }
                   3558:     }
                   3559:     return;
                   3560: }
                   3561: 
1.351     www      3562: sub get_course_adv_roles {
1.948     raeburn  3563:     my ($cid,$codes) = @_;
1.620     albertel 3564:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3565:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3566:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3567:     my %nothide=();
1.800     albertel 3568:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3569:         if ($user !~ /:/) {
                   3570: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3571:         } else {
                   3572:             $nothide{$user}=1;
                   3573:         }
1.470     www      3574:     }
1.351     www      3575:     my %returnhash=();
                   3576:     my %dumphash=
                   3577:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3578:     my $now=time;
1.997     raeburn  3579:     my %privileged;
1.1000    raeburn  3580:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3581: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3582:         if (($tstart) && ($tstart<0)) { next; }
                   3583:         if (($tend) && ($tend<$now)) { next; }
                   3584:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3585:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3586: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3587:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3588:             my %dompersonnel =
1.998     raeburn  3589:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3590:             $privileged{$domain} = {};
                   3591:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3592:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3593:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3594:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3595:                         $privileged{$udom}{$uname} = 1;
                   3596:                     }
                   3597:                 }
                   3598:             }
                   3599:         }
                   3600:         if ((exists($privileged{$domain}{$username})) && 
                   3601:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3602: 	if ($role eq 'cr') { next; }
1.948     raeburn  3603:         if ($codes) {
                   3604:             if ($section) { $role .= ':'.$section; }
                   3605:             if ($returnhash{$role}) {
                   3606:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3607:             } else {
                   3608:                 $returnhash{$role}=$username.':'.$domain;
                   3609:             }
1.351     www      3610:         } else {
1.988     raeburn  3611:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3612:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3613:             if ($returnhash{$key}) {
                   3614: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3615:             } else {
                   3616:                 $returnhash{$key}=$username.':'.$domain;
                   3617:             }
1.351     www      3618:         }
1.948     raeburn  3619:     }
1.400     www      3620:     return %returnhash;
                   3621: }
                   3622: 
                   3623: sub get_my_roles {
1.937     raeburn  3624:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3625:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3626:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3627:     my (%dumphash,%nothide);
1.1086    raeburn  3628:     if ($context eq 'userroles') {
1.1166    raeburn  3629:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3630:     } else {
                   3631:         %dumphash=
1.400     www      3632:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3633:         if ($hidepriv) {
                   3634:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3635:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3636:                 if ($user !~ /:/) {
                   3637:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3638:                 } else {
                   3639:                     $nothide{$user} = 1;
                   3640:                 }
                   3641:             }
                   3642:         }
1.858     raeburn  3643:     }
1.400     www      3644:     my %returnhash=();
                   3645:     my $now=time;
1.999     raeburn  3646:     my %privileged;
1.800     albertel 3647:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3648:         my ($role,$tend,$tstart);
                   3649:         if ($context eq 'userroles') {
1.1149    raeburn  3650:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3651: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3652:         } else {
                   3653:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3654:         }
1.400     www      3655:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3656:         my $status = 'active';
1.939     raeburn  3657:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3658:             $status = 'previous';
                   3659:         } 
                   3660:         if (($tstart) && ($now<$tstart)) {
                   3661:             $status = 'future';
                   3662:         }
                   3663:         if (ref($types) eq 'ARRAY') {
                   3664:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3665:                 next;
                   3666:             } 
                   3667:         } else {
                   3668:             if ($status ne 'active') {
                   3669:                 next;
                   3670:             }
                   3671:         }
1.867     raeburn  3672:         my ($rolecode,$username,$domain,$section,$area);
                   3673:         if ($context eq 'userroles') {
                   3674:             ($area,$rolecode) = split(/_/,$entry);
                   3675:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3676:         } else {
                   3677:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3678:         }
1.832     raeburn  3679:         if (ref($roledoms) eq 'ARRAY') {
                   3680:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3681:                 next;
                   3682:             }
                   3683:         }
                   3684:         if (ref($roles) eq 'ARRAY') {
                   3685:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3686:                 if ($role =~ /^cr\//) {
                   3687:                     if (!grep(/^cr$/,@{$roles})) {
                   3688:                         next;
                   3689:                     }
1.1104    raeburn  3690:                 } elsif ($role =~ /^gr\//) {
                   3691:                     if (!grep(/^gr$/,@{$roles})) {
                   3692:                         next;
                   3693:                     }
1.922     raeburn  3694:                 } else {
                   3695:                     next;
                   3696:                 }
1.832     raeburn  3697:             }
1.867     raeburn  3698:         }
1.937     raeburn  3699:         if ($hidepriv) {
1.999     raeburn  3700:             if ($context eq 'userroles') {
                   3701:                 if ((&privileged($username,$domain)) &&
                   3702:                     (!$nothide{$username.':'.$domain})) {
                   3703:                     next;
                   3704:                 }
                   3705:             } else {
                   3706:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3707:                     my %dompersonnel =
                   3708:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3709:                     $privileged{$domain} = {};
                   3710:                     if (keys(%dompersonnel)) {
                   3711:                         foreach my $server (keys(%dompersonnel)) {
                   3712:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3713:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3714:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3715:                                     $privileged{$udom}{$uname} = $trole;
                   3716:                                 }
                   3717:                             }
                   3718:                         }
                   3719:                     }
                   3720:                 }
                   3721:                 if (exists($privileged{$domain}{$username})) {
                   3722:                     if (!$nothide{$username.':'.$domain}) {
                   3723:                         next;
                   3724:                     }
                   3725:                 }
1.937     raeburn  3726:             }
                   3727:         }
1.933     raeburn  3728:         if ($withsec) {
                   3729:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3730:                 $tstart.':'.$tend;
                   3731:         } else {
                   3732:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3733:         }
1.832     raeburn  3734:     }
1.373     www      3735:     return %returnhash;
1.399     www      3736: }
                   3737: 
                   3738: # ----------------------------------------------------- Frontpage Announcements
                   3739: #
                   3740: #
                   3741: 
                   3742: sub postannounce {
                   3743:     my ($server,$text)=@_;
1.844     albertel 3744:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3745:     unless ($text=~/\w/) { $text=''; }
                   3746:     return &reply('setannounce:'.&escape($text),$server);
                   3747: }
                   3748: 
                   3749: sub getannounce {
1.448     albertel 3750: 
                   3751:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3752: 	my $announcement='';
1.800     albertel 3753: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3754: 	close($fh);
1.399     www      3755: 	if ($announcement=~/\w/) { 
                   3756: 	    return 
                   3757:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3758:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3759: 	} else {
                   3760: 	    return '';
                   3761: 	}
                   3762:     } else {
                   3763: 	return '';
                   3764:     }
1.351     www      3765: }
1.353     www      3766: 
                   3767: # ---------------------------------------------------------- Course ID routines
                   3768: # Deal with domain's nohist_courseid.db files
                   3769: #
                   3770: 
                   3771: sub courseidput {
1.921     raeburn  3772:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3773:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3774:     my $outcome;
                   3775:     if ($caller eq 'timeonly') {
                   3776:         my $cids = '';
                   3777:         foreach my $item (keys(%$storehash)) {
                   3778:             $cids.=&escape($item).'&';
                   3779:         }
                   3780:         $cids=~s/\&$//;
                   3781:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3782:                           $coursehome);       
                   3783:     } else {
                   3784:         my $items = '';
                   3785:         foreach my $item (keys(%$storehash)) {
                   3786:             $items.= &escape($item).'='.
                   3787:                      &freeze_escape($$storehash{$item}).'&';
                   3788:         }
                   3789:         $items=~s/\&$//;
                   3790:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3791:                           $coursehome);
1.918     raeburn  3792:     }
                   3793:     if ($outcome eq 'unknown_cmd') {
                   3794:         my $what;
                   3795:         foreach my $cid (keys(%$storehash)) {
                   3796:             $what .= &escape($cid).'=';
1.921     raeburn  3797:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3798:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3799:             }
                   3800:             $what =~ s/\:$/&/;
                   3801:         }
                   3802:         $what =~ s/\&$//;  
                   3803:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3804:     } else {
                   3805:         return $outcome;
                   3806:     }
1.353     www      3807: }
                   3808: 
                   3809: sub courseiddump {
1.921     raeburn  3810:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3811:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3812:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3813:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3814:     my $as_hash = 1;
                   3815:     my %returnhash;
                   3816:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3817:     my %libserv = &all_library();
                   3818:     foreach my $tryserver (keys(%libserv)) {
                   3819:         if ( (  $hostidflag == 1 
                   3820: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3821: 	     || (!defined($hostidflag)) ) {
                   3822: 
1.918     raeburn  3823: 	    if (($domfilter eq '') ||
                   3824: 		(&host_domain($tryserver) eq $domfilter)) {
1.1180    droeschl 3825:                 my $rep;
                   3826:                 if (grep { $_ eq $tryserver } current_machine_ids()) {
                   3827:                     $rep = LONCAPA::Lond::dump_course_id_handler(
                   3828:                         join(":", (&host_domain($tryserver), $sincefilter, 
                   3829:                                 &escape($descfilter), &escape($instcodefilter), 
                   3830:                                 &escape($ownerfilter), &escape($coursefilter),
                   3831:                                 &escape($typefilter), &escape($regexp_ok), 
                   3832:                                 $as_hash, &escape($selfenrollonly), 
                   3833:                                 &escape($catfilter), $showhidden, $caller, 
                   3834:                                 &escape($cloner), &escape($cc_clone), $cloneonly, 
                   3835:                                 &escape($createdbefore), &escape($createdafter), 
                   3836:                                 &escape($creationcontext), $domcloner)));
                   3837:                 } else {
                   3838:                     $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3839:                              $sincefilter.':'.&escape($descfilter).':'.
                   3840:                              &escape($instcodefilter).':'.&escape($ownerfilter).
                   3841:                              ':'.&escape($coursefilter).':'.&escape($typefilter).
                   3842:                              ':'.&escape($regexp_ok).':'.$as_hash.':'.
                   3843:                              &escape($selfenrollonly).':'.&escape($catfilter).':'.
                   3844:                              $showhidden.':'.$caller.':'.&escape($cloner).':'.
                   3845:                              &escape($cc_clone).':'.$cloneonly.':'.
                   3846:                              &escape($createdbefore).':'.&escape($createdafter).':'.
                   3847:                              &escape($creationcontext).':'.$domcloner,
                   3848:                              $tryserver);
                   3849:                 }
                   3850:                      
1.918     raeburn  3851:                 my @pairs=split(/\&/,$rep);
                   3852:                 foreach my $item (@pairs) {
                   3853:                     my ($key,$value)=split(/\=/,$item,2);
                   3854:                     $key = &unescape($key);
                   3855:                     next if ($key =~ /^error: 2 /);
                   3856:                     my $result = &thaw_unescape($value);
                   3857:                     if (ref($result) eq 'HASH') {
                   3858:                         $returnhash{$key}=$result;
                   3859:                     } else {
1.921     raeburn  3860:                         my @responses = split(/:/,$value);
                   3861:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3862:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3863:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3864:                         }
1.1008    raeburn  3865:                     }
1.353     www      3866:                 }
                   3867:             }
                   3868:         }
                   3869:     }
                   3870:     return %returnhash;
                   3871: }
                   3872: 
1.1055    raeburn  3873: sub courselastaccess {
                   3874:     my ($cdom,$cnum,$hostidref) = @_;
                   3875:     my %returnhash;
                   3876:     if ($cdom && $cnum) {
                   3877:         my $chome = &homeserver($cnum,$cdom);
                   3878:         if ($chome ne 'no_host') {
                   3879:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3880:             &extract_lastaccess(\%returnhash,$rep);
                   3881:         }
                   3882:     } else {
                   3883:         if (!$cdom) { $cdom=''; }
                   3884:         my %libserv = &all_library();
                   3885:         foreach my $tryserver (keys(%libserv)) {
                   3886:             if (ref($hostidref) eq 'ARRAY') {
                   3887:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3888:             } 
                   3889:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3890:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3891:                 &extract_lastaccess(\%returnhash,$rep);
                   3892:             }
                   3893:         }
                   3894:     }
                   3895:     return %returnhash;
                   3896: }
                   3897: 
                   3898: sub extract_lastaccess {
                   3899:     my ($returnhash,$rep) = @_;
                   3900:     if (ref($returnhash) eq 'HASH') {
                   3901:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3902:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3903:                  $rep eq '') {
                   3904:             my @pairs=split(/\&/,$rep);
                   3905:             foreach my $item (@pairs) {
                   3906:                 my ($key,$value)=split(/\=/,$item,2);
                   3907:                 $key = &unescape($key);
                   3908:                 next if ($key =~ /^error: 2 /);
                   3909:                 $returnhash->{$key} = &thaw_unescape($value);
                   3910:             }
                   3911:         }
                   3912:     }
                   3913:     return;
                   3914: }
                   3915: 
1.658     raeburn  3916: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3917: 
                   3918: sub dcmailput {
1.685     raeburn  3919:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3920:     my $status = &Apache::lonnet::critical(
1.740     www      3921:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3922:        &escape($message),$server);
1.662     raeburn  3923:     return $status;
                   3924: }
                   3925: 
1.658     raeburn  3926: sub dcmaildump {
                   3927:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3928:     my %returnhash=();
1.846     albertel 3929: 
                   3930:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3931:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3932:                                                          &escape($enddate).':';
                   3933: 	my @esc_senders=map { &escape($_)} @$senders;
                   3934: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3935: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3936:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3937:             if (($key) && ($value)) {
                   3938:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3939:             }
                   3940:         }
                   3941:     }
                   3942:     return %returnhash;
                   3943: }
1.662     raeburn  3944: # ---------------------------------------------------------- Domain roles
                   3945: 
                   3946: sub get_domain_roles {
                   3947:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3948:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3949:         $startdate = '.';
                   3950:     }
1.1018    raeburn  3951:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3952:         $enddate = '.';
                   3953:     }
1.922     raeburn  3954:     my $rolelist;
                   3955:     if (ref($roles) eq 'ARRAY') {
                   3956:         $rolelist = join(':',@{$roles});
                   3957:     }
1.662     raeburn  3958:     my %personnel = ();
1.841     albertel 3959: 
                   3960:     my %servers = &get_servers($dom,'library');
                   3961:     foreach my $tryserver (keys(%servers)) {
                   3962: 	%{$personnel{$tryserver}}=();
                   3963: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3964: 					    &escape($startdate).':'.
                   3965: 					    &escape($enddate).':'.
                   3966: 					    &escape($rolelist), $tryserver))) {
                   3967: 	    my ($key,$value) = split(/\=/,$line,2);
                   3968: 	    if (($key) && ($value)) {
                   3969: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3970: 	    }
                   3971: 	}
1.662     raeburn  3972:     }
                   3973:     return %personnel;
                   3974: }
1.658     raeburn  3975: 
1.1057    www      3976: # ----------------------------------------------------------- Interval timing 
1.149     www      3977: 
1.1153    www      3978: {
                   3979: # Caches needed for speedup of navmaps
                   3980: # We don't want to cache this for very long at all (5 seconds at most)
                   3981: # 
                   3982: # The user for whom we cache
                   3983: my $cachedkey='';
                   3984: # The cached times for this user
                   3985: my %cachedtimes=();
                   3986: # When this was last done
                   3987: my $cachedtime=();
                   3988: 
                   3989: sub load_all_first_access {
1.1154    raeburn  3990:     my ($uname,$udom)=@_;
1.1156    www      3991:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  3992:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  3993:         return;
                   3994:     }
                   3995:     $cachedtime=time;
                   3996:     $cachedkey=$uname.':'.$udom;
                   3997:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      3998: }
                   3999: 
1.504     albertel 4000: sub get_first_access {
1.1162    raeburn  4001:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 4002:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4003:     if ($argsymb) { $symb=$argsymb; }
                   4004:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  4005:     if ($argmap) { $map = $argmap; }
1.926     albertel 4006:     if ($type eq 'course') {
                   4007: 	$res='course';
                   4008:     } elsif ($type eq 'map') {
1.588     albertel 4009: 	$res=&symbread($map);
                   4010:     } else {
                   4011: 	$res=$symb;
                   4012:     }
1.1153    www      4013:     &load_all_first_access($uname,$udom);
                   4014:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 4015: }
                   4016: 
                   4017: sub set_first_access {
1.1162    raeburn  4018:     my ($type,$interval)=@_;
1.790     albertel 4019:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 4020:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 4021:     if ($type eq 'course') {
                   4022: 	$res='course';
                   4023:     } elsif ($type eq 'map') {
1.588     albertel 4024: 	$res=&symbread($map);
                   4025:     } else {
                   4026: 	$res=$symb;
                   4027:     }
1.1153    www      4028:     $cachedkey='';
1.1162    raeburn  4029:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4030:     if (!$firstaccess) {
1.1162    raeburn  4031:         my $start = time;
                   4032: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4033:                           $udom,$uname);
                   4034:         if ($putres eq 'ok') {
                   4035:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4036:                  $udom,$uname); 
                   4037:             &appenv(
                   4038:                      {
                   4039:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4040:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4041:                      }
                   4042:                   );
                   4043:         }
                   4044:         return $putres;
1.505     albertel 4045:     }
                   4046:     return 'already_set';
1.504     albertel 4047: }
1.1153    www      4048: }
1.110     www      4049: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4050: 
                   4051: sub expirespread {
                   4052:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4053:     my $cid=$env{'request.course.id'}; 
1.110     www      4054:     if ($cid) {
                   4055:        my $now=time;
                   4056:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4057:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4058:                             $env{'course.'.$cid.'.num'}.
1.110     www      4059: 	        	    ':nohist_expirationdates:'.
                   4060:                             &escape($key).'='.$now,
1.620     albertel 4061:                             $env{'course.'.$cid.'.home'})
1.110     www      4062:     }
                   4063:     return 'ok';
1.14      www      4064: }
                   4065: 
1.109     www      4066: # ----------------------------------------------------- Devalidate Spreadsheets
                   4067: 
                   4068: sub devalidate {
1.325     www      4069:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4070:     my $cid=$env{'request.course.id'}; 
1.109     www      4071:     if ($cid) {
1.391     matthew  4072:         # delete the stored spreadsheets for
                   4073:         # - the student level sheet of this user in course's homespace
                   4074:         # - the assessment level sheet for this resource 
                   4075:         #   for this user in user's homespace
1.553     albertel 4076: 	# - current conditional state info
1.325     www      4077: 	my $key=$uname.':'.$udom.':';
1.109     www      4078:         my $status=
1.299     matthew  4079: 	    &del('nohist_calculatedsheets',
1.391     matthew  4080: 		 [$key.'studentcalc:'],
1.620     albertel 4081: 		 $env{'course.'.$cid.'.domain'},
                   4082: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4083: 		.' '.
                   4084: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4085: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4086:         unless ($status eq 'ok ok') {
                   4087:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4088:                     $uname.' at '.$udom.' for '.
1.109     www      4089: 		    $symb.': '.$status);
1.133     albertel 4090:         }
1.553     albertel 4091: 	&delenv('user.state.'.$cid);
1.109     www      4092:     }
                   4093: }
                   4094: 
1.265     albertel 4095: sub get_scalar {
                   4096:     my ($string,$end) = @_;
                   4097:     my $value;
                   4098:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4099: 	$value = $1;
                   4100:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4101: 	$value = $1;
                   4102:     }
                   4103:     return &unescape($value);
                   4104: }
                   4105: 
                   4106: sub array2str {
                   4107:   my (@array) = @_;
                   4108:   my $result=&arrayref2str(\@array);
                   4109:   $result=~s/^__ARRAY_REF__//;
                   4110:   $result=~s/__END_ARRAY_REF__$//;
                   4111:   return $result;
                   4112: }
                   4113: 
1.204     albertel 4114: sub arrayref2str {
                   4115:   my ($arrayref) = @_;
1.265     albertel 4116:   my $result='__ARRAY_REF__';
1.204     albertel 4117:   foreach my $elem (@$arrayref) {
1.265     albertel 4118:     if(ref($elem) eq 'ARRAY') {
                   4119:       $result.=&arrayref2str($elem).'&';
                   4120:     } elsif(ref($elem) eq 'HASH') {
                   4121:       $result.=&hashref2str($elem).'&';
                   4122:     } elsif(ref($elem)) {
                   4123:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4124:     } else {
                   4125:       $result.=&escape($elem).'&';
                   4126:     }
                   4127:   }
                   4128:   $result=~s/\&$//;
1.265     albertel 4129:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4130:   return $result;
                   4131: }
                   4132: 
1.168     albertel 4133: sub hash2str {
1.204     albertel 4134:   my (%hash) = @_;
                   4135:   my $result=&hashref2str(\%hash);
1.265     albertel 4136:   $result=~s/^__HASH_REF__//;
                   4137:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4138:   return $result;
                   4139: }
                   4140: 
                   4141: sub hashref2str {
                   4142:   my ($hashref)=@_;
1.265     albertel 4143:   my $result='__HASH_REF__';
1.800     albertel 4144:   foreach my $key (sort(keys(%$hashref))) {
                   4145:     if (ref($key) eq 'ARRAY') {
                   4146:       $result.=&arrayref2str($key).'=';
                   4147:     } elsif (ref($key) eq 'HASH') {
                   4148:       $result.=&hashref2str($key).'=';
                   4149:     } elsif (ref($key)) {
1.265     albertel 4150:       $result.='=';
1.800     albertel 4151:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4152:     } else {
1.1132    raeburn  4153: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4154:     }
                   4155: 
1.800     albertel 4156:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4157:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4158:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4159:       $result.=&hashref2str($hashref->{$key}).'&';
                   4160:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4161:        $result.='&';
1.800     albertel 4162:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4163:     } else {
1.800     albertel 4164:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4165:     }
                   4166:   }
1.168     albertel 4167:   $result=~s/\&$//;
1.265     albertel 4168:   $result .= '__END_HASH_REF__';
1.168     albertel 4169:   return $result;
                   4170: }
                   4171: 
                   4172: sub str2hash {
1.265     albertel 4173:     my ($string)=@_;
                   4174:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4175:     return %$hash;
                   4176: }
                   4177: 
                   4178: sub str2hashref {
1.168     albertel 4179:   my ($string) = @_;
1.265     albertel 4180: 
                   4181:   my %hash;
                   4182: 
                   4183:   if($string !~ /^__HASH_REF__/) {
                   4184:       if (! ($string eq '' || !defined($string))) {
                   4185: 	  $hash{'error'}='Not hash reference';
                   4186:       }
                   4187:       return (\%hash, $string);
                   4188:   }
                   4189: 
                   4190:   $string =~ s/^__HASH_REF__//;
                   4191: 
                   4192:   while($string !~ /^__END_HASH_REF__/) {
                   4193:       #key
                   4194:       my $key='';
                   4195:       if($string =~ /^__HASH_REF__/) {
                   4196:           ($key, $string)=&str2hashref($string);
                   4197:           if(defined($key->{'error'})) {
                   4198:               $hash{'error'}='Bad data';
                   4199:               return (\%hash, $string);
                   4200:           }
                   4201:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4202:           ($key, $string)=&str2arrayref($string);
                   4203:           if($key->[0] eq 'Array reference error') {
                   4204:               $hash{'error'}='Bad data';
                   4205:               return (\%hash, $string);
                   4206:           }
                   4207:       } else {
                   4208:           $string =~ s/^(.*?)=//;
1.267     albertel 4209: 	  $key=&unescape($1);
1.265     albertel 4210:       }
                   4211:       $string =~ s/^=//;
                   4212: 
                   4213:       #value
                   4214:       my $value='';
                   4215:       if($string =~ /^__HASH_REF__/) {
                   4216:           ($value, $string)=&str2hashref($string);
                   4217:           if(defined($value->{'error'})) {
                   4218:               $hash{'error'}='Bad data';
                   4219:               return (\%hash, $string);
                   4220:           }
                   4221:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4222:           ($value, $string)=&str2arrayref($string);
                   4223:           if($value->[0] eq 'Array reference error') {
                   4224:               $hash{'error'}='Bad data';
                   4225:               return (\%hash, $string);
                   4226:           }
                   4227:       } else {
                   4228: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4229:       }
                   4230:       $string =~ s/^&//;
                   4231: 
                   4232:       $hash{$key}=$value;
1.204     albertel 4233:   }
1.265     albertel 4234: 
                   4235:   $string =~ s/^__END_HASH_REF__//;
                   4236: 
                   4237:   return (\%hash, $string);
1.204     albertel 4238: }
                   4239: 
                   4240: sub str2array {
1.265     albertel 4241:     my ($string)=@_;
                   4242:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4243:     return @$array;
                   4244: }
                   4245: 
                   4246: sub str2arrayref {
1.204     albertel 4247:   my ($string) = @_;
1.265     albertel 4248:   my @array;
                   4249: 
                   4250:   if($string !~ /^__ARRAY_REF__/) {
                   4251:       if (! ($string eq '' || !defined($string))) {
                   4252: 	  $array[0]='Array reference error';
                   4253:       }
                   4254:       return (\@array, $string);
                   4255:   }
                   4256: 
                   4257:   $string =~ s/^__ARRAY_REF__//;
                   4258: 
                   4259:   while($string !~ /^__END_ARRAY_REF__/) {
                   4260:       my $value='';
                   4261:       if($string =~ /^__HASH_REF__/) {
                   4262:           ($value, $string)=&str2hashref($string);
                   4263:           if(defined($value->{'error'})) {
                   4264:               $array[0] ='Array reference error';
                   4265:               return (\@array, $string);
                   4266:           }
                   4267:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4268:           ($value, $string)=&str2arrayref($string);
                   4269:           if($value->[0] eq 'Array reference error') {
                   4270:               $array[0] ='Array reference error';
                   4271:               return (\@array, $string);
                   4272:           }
                   4273:       } else {
                   4274: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4275:       }
                   4276:       $string =~ s/^&//;
                   4277: 
                   4278:       push(@array, $value);
1.191     harris41 4279:   }
1.265     albertel 4280: 
                   4281:   $string =~ s/^__END_ARRAY_REF__//;
                   4282: 
                   4283:   return (\@array, $string);
1.168     albertel 4284: }
                   4285: 
1.167     albertel 4286: # -------------------------------------------------------------------Temp Store
                   4287: 
1.168     albertel 4288: sub tmpreset {
                   4289:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4290:   if (!$symb) {
                   4291:     $symb=&symbread();
1.620     albertel 4292:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4293:   }
                   4294:   $symb=escape($symb);
                   4295: 
1.620     albertel 4296:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4297:   $namespace=~s/\//\_/g;
                   4298:   $namespace=~s/\W//g;
                   4299: 
1.620     albertel 4300:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4301:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4302:   if ($domain eq 'public' && $stuname eq 'public') {
                   4303:       $stuname=$ENV{'REMOTE_ADDR'};
                   4304:   }
1.1117    foxr     4305:   my $path=LONCAPA::tempdir();
1.168     albertel 4306:   my %hash;
                   4307:   if (tie(%hash,'GDBM_File',
                   4308: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4309: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4310:     foreach my $key (keys(%hash)) {
1.180     albertel 4311:       if ($key=~ /:$symb/) {
1.168     albertel 4312: 	delete($hash{$key});
                   4313:       }
                   4314:     }
                   4315:   }
                   4316: }
                   4317: 
1.167     albertel 4318: sub tmpstore {
1.168     albertel 4319:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4320: 
                   4321:   if (!$symb) {
                   4322:     $symb=&symbread();
1.620     albertel 4323:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4324:   }
                   4325:   $symb=escape($symb);
                   4326: 
                   4327:   if (!$namespace) {
                   4328:     # I don't think we would ever want to store this for a course.
                   4329:     # it seems this will only be used if we don't have a course.
1.620     albertel 4330:     #$namespace=$env{'request.course.id'};
1.168     albertel 4331:     #if (!$namespace) {
1.620     albertel 4332:       $namespace=$env{'request.state'};
1.168     albertel 4333:     #}
                   4334:   }
                   4335:   $namespace=~s/\//\_/g;
                   4336:   $namespace=~s/\W//g;
1.620     albertel 4337:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4338:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4339:   if ($domain eq 'public' && $stuname eq 'public') {
                   4340:       $stuname=$ENV{'REMOTE_ADDR'};
                   4341:   }
1.168     albertel 4342:   my $now=time;
                   4343:   my %hash;
1.1117    foxr     4344:   my $path=LONCAPA::tempdir();
1.168     albertel 4345:   if (tie(%hash,'GDBM_File',
                   4346: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4347: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4348:     $hash{"version:$symb"}++;
                   4349:     my $version=$hash{"version:$symb"};
                   4350:     my $allkeys=''; 
                   4351:     foreach my $key (keys(%$storehash)) {
                   4352:       $allkeys.=$key.':';
1.591     albertel 4353:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4354:     }
                   4355:     $hash{"$version:$symb:timestamp"}=$now;
                   4356:     $allkeys.='timestamp';
                   4357:     $hash{"$version:keys:$symb"}=$allkeys;
                   4358:     if (untie(%hash)) {
                   4359:       return 'ok';
                   4360:     } else {
                   4361:       return "error:$!";
                   4362:     }
                   4363:   } else {
                   4364:     return "error:$!";
                   4365:   }
                   4366: }
1.167     albertel 4367: 
1.168     albertel 4368: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4369: 
1.168     albertel 4370: sub tmprestore {
                   4371:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4372: 
1.168     albertel 4373:   if (!$symb) {
                   4374:     $symb=&symbread();
1.620     albertel 4375:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4376:   }
                   4377:   $symb=escape($symb);
                   4378: 
1.620     albertel 4379:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4380: 
1.620     albertel 4381:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4382:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4383:   if ($domain eq 'public' && $stuname eq 'public') {
                   4384:       $stuname=$ENV{'REMOTE_ADDR'};
                   4385:   }
1.168     albertel 4386:   my %returnhash;
                   4387:   $namespace=~s/\//\_/g;
                   4388:   $namespace=~s/\W//g;
                   4389:   my %hash;
1.1117    foxr     4390:   my $path=LONCAPA::tempdir();
1.168     albertel 4391:   if (tie(%hash,'GDBM_File',
                   4392: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4393: 	  &GDBM_READER(),0640)) {
1.168     albertel 4394:     my $version=$hash{"version:$symb"};
                   4395:     $returnhash{'version'}=$version;
                   4396:     my $scope;
                   4397:     for ($scope=1;$scope<=$version;$scope++) {
                   4398:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4399:       my @keys=split(/:/,$vkeys);
                   4400:       my $key;
                   4401:       $returnhash{"$scope:keys"}=$vkeys;
                   4402:       foreach $key (@keys) {
1.591     albertel 4403: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4404: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4405:       }
                   4406:     }
1.168     albertel 4407:     if (!(untie(%hash))) {
                   4408:       return "error:$!";
                   4409:     }
                   4410:   } else {
                   4411:     return "error:$!";
                   4412:   }
                   4413:   return %returnhash;
1.167     albertel 4414: }
                   4415: 
1.9       www      4416: # ----------------------------------------------------------------------- Store
                   4417: 
                   4418: sub store {
1.124     www      4419:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4420:     my $home='';
                   4421: 
1.168     albertel 4422:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4423: 
1.213     www      4424:     $symb=&symbclean($symb);
1.122     albertel 4425:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4426: 
1.620     albertel 4427:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4428:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4429: 
                   4430:     &devalidate($symb,$stuname,$domain);
1.109     www      4431: 
                   4432:     $symb=escape($symb);
1.187     www      4433:     if (!$namespace) { 
1.620     albertel 4434:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4435:           return ''; 
                   4436:        } 
                   4437:     }
1.620     albertel 4438:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4439: 
                   4440:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4441:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4442: 
1.12      www      4443:     my $namevalue='';
1.800     albertel 4444:     foreach my $key (keys(%$storehash)) {
                   4445:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4446:     }
1.12      www      4447:     $namevalue=~s/\&$//;
1.187     www      4448:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4449:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4450: }
                   4451: 
1.47      www      4452: # -------------------------------------------------------------- Critical Store
                   4453: 
                   4454: sub cstore {
1.124     www      4455:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4456:     my $home='';
                   4457: 
1.168     albertel 4458:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4459: 
1.213     www      4460:     $symb=&symbclean($symb);
1.122     albertel 4461:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4462: 
1.620     albertel 4463:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4464:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4465: 
                   4466:     &devalidate($symb,$stuname,$domain);
1.109     www      4467: 
                   4468:     $symb=escape($symb);
1.187     www      4469:     if (!$namespace) { 
1.620     albertel 4470:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4471:           return ''; 
                   4472:        } 
                   4473:     }
1.620     albertel 4474:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4475: 
                   4476:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4477:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4478: 
1.47      www      4479:     my $namevalue='';
1.800     albertel 4480:     foreach my $key (keys(%$storehash)) {
                   4481:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4482:     }
1.47      www      4483:     $namevalue=~s/\&$//;
1.187     www      4484:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4485:     return critical
                   4486:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4487: }
                   4488: 
1.9       www      4489: # --------------------------------------------------------------------- Restore
                   4490: 
                   4491: sub restore {
1.124     www      4492:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4493:     my $home='';
                   4494: 
1.168     albertel 4495:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4496: 
1.122     albertel 4497:     if (!$symb) {
                   4498:       unless ($symb=escape(&symbread())) { return ''; }
                   4499:     } else {
1.213     www      4500:       $symb=&escape(&symbclean($symb));
1.122     albertel 4501:     }
1.188     www      4502:     if (!$namespace) { 
1.620     albertel 4503:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4504:           return ''; 
                   4505:        } 
                   4506:     }
1.620     albertel 4507:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4508:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4509:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4510:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4511: 
1.12      www      4512:     my %returnhash=();
1.800     albertel 4513:     foreach my $line (split(/\&/,$answer)) {
                   4514: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4515:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4516:     }
1.75      www      4517:     my $version;
                   4518:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4519:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4520:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4521:        }
1.75      www      4522:     }
1.13      www      4523:     return %returnhash;
1.34      www      4524: }
                   4525: 
                   4526: # ---------------------------------------------------------- Course Description
1.1118    foxr     4527: #
                   4528: #  
1.34      www      4529: 
                   4530: sub coursedescription {
1.731     albertel 4531:     my ($courseid,$args)=@_;
1.34      www      4532:     $courseid=~s/^\///;
1.49      www      4533:     $courseid=~s/\_/\//g;
1.34      www      4534:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4535:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4536:     my $normalid=$cdomain.'_'.$cnum;
                   4537:     # need to always cache even if we get errors otherwise we keep 
                   4538:     # trying and trying and trying to get the course description.
                   4539:     my %envhash=();
                   4540:     my %returnhash=();
1.731     albertel 4541:     
                   4542:     my $expiretime=600;
                   4543:     if ($env{'request.course.id'} eq $normalid) {
                   4544: 	$expiretime=120;
                   4545:     }
                   4546: 
                   4547:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4548:     if (!$args->{'freshen_cache'}
                   4549: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4550: 	foreach my $key (keys(%env)) {
                   4551: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4552: 	    my ($setting) = $1;
                   4553: 	    $returnhash{$setting} = $env{$key};
                   4554: 	}
                   4555: 	return %returnhash;
                   4556:     }
                   4557: 
1.1118    foxr     4558:     # get the data again
                   4559: 
1.731     albertel 4560:     if (!$args->{'one_time'}) {
                   4561: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4562:     }
1.811     albertel 4563: 
1.34      www      4564:     if ($chome ne 'no_host') {
1.302     albertel 4565:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4566:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4567: 	   my $username = $env{'user.name'}; # Defult username
                   4568: 	   if(defined $args->{'user'}) {
                   4569: 	       $username = $args->{'user'};
                   4570: 	   }
1.129     albertel 4571:            $returnhash{'home'}= $chome;
                   4572: 	   $returnhash{'domain'} = $cdomain;
                   4573: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4574:            if (!defined($returnhash{'type'})) {
                   4575:                $returnhash{'type'} = 'Course';
                   4576:            }
1.130     albertel 4577:            while (my ($name,$value) = each %returnhash) {
1.53      www      4578:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4579:            }
1.270     www      4580:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4581:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4582: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4583:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4584:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4585:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4586:        }
                   4587:     }
1.731     albertel 4588:     if (!$args->{'one_time'}) {
1.949     raeburn  4589: 	&appenv(\%envhash);
1.731     albertel 4590:     }
1.302     albertel 4591:     return %returnhash;
1.461     www      4592: }
                   4593: 
1.1080    raeburn  4594: sub update_released_required {
                   4595:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4596:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4597:         $cid = $env{'request.course.id'};
                   4598:         $cdom = $env{'course.'.$cid.'.domain'};
                   4599:         $cnum = $env{'course.'.$cid.'.num'};
                   4600:         $chome = $env{'course.'.$cid.'.home'};
                   4601:     }
                   4602:     if ($needsrelease) {
                   4603:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4604:         my $needsupdate;
                   4605:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4606:             $needsupdate = 1;
                   4607:         } else {
                   4608:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4609:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4610:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4611:                 $needsupdate = 1;
                   4612:             }
                   4613:         }
                   4614:         if ($needsupdate) {
                   4615:             my %needshash = (
                   4616:                              'internal.releaserequired' => $needsrelease,
                   4617:                             );
                   4618:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4619:             if ($putresult eq 'ok') {
                   4620:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4621:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4622:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4623:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4624:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4625:                 }
                   4626:             }
                   4627:         }
                   4628:     }
                   4629:     return;
                   4630: }
                   4631: 
1.461     www      4632: # -------------------------------------------------See if a user is privileged
                   4633: 
                   4634: sub privileged {
                   4635:     my ($username,$domain)=@_;
1.1170    droeschl 4636: 
                   4637:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4638:     my $now = time;
                   4639: 
                   4640:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4641:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4642:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4643:                 return 1 unless ($tend && $tend < $now) 
                   4644:                     or ($tstart && $tstart > $now);
                   4645:             }
1.461     www      4646: 	}
1.1170    droeschl 4647: 
1.461     www      4648:     return 0;
1.9       www      4649: }
1.1       albertel 4650: 
1.103     harris41 4651: # -------------------------------------------------------- Get user privileges
1.11      www      4652: 
                   4653: sub rolesinit {
1.1169    droeschl 4654:     my ($domain, $username) = @_;
                   4655:     my %userroles = ('user.login.time' => time);
                   4656:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4657: 
                   4658:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4659:     # also, blocking can be triggered by an activating timer
                   4660:     # it's saved in the user's %env.
                   4661:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4662:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4663:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4664:         %timerintchk, %timerintenv);
                   4665: 
1.1162    raeburn  4666:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4667:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4668:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4669:     }
1.1169    droeschl 4670: 
1.1162    raeburn  4671:     foreach my $key (keys(%timerinterval)) {
                   4672:         my ($cid,$rest) = split(/\0/,$key);
                   4673:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4674:     }
1.1169    droeschl 4675: 
1.11      www      4676:     my %allroles=();
1.1162    raeburn  4677:     my %allgroups=();
1.11      www      4678: 
1.1169    droeschl 4679:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4680:         my $role = $rolesdump{$area};
                   4681:         $area =~ s/\_\w\w$//;
                   4682: 
                   4683:         my ($trole, $tend, $tstart, $group_privs);
                   4684: 
                   4685:         if ($role =~ /^cr/) {
                   4686:         # Custom role, defined by a user 
                   4687:         # e.g., user.role.cr/msu/smith/mynewrole
                   4688:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4689:                 $trole = $1;
                   4690:                 ($tend, $tstart) = split('_', $2);
                   4691:             } else {
                   4692:                 $trole = $role;
                   4693:             }
                   4694:         } elsif ($role =~ m|^gr/|) {
                   4695:         # Role of member in a group, defined within a course/community
                   4696:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4697:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4698:             next if $tstart eq '-1';
                   4699:             ($trole, $group_privs) = split(/\//, $trole);
                   4700:             $group_privs = &unescape($group_privs);
                   4701:         } else {
                   4702:         # Just a normal role, defined in roles.tab
                   4703:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4704:         }
                   4705: 
                   4706:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4707:                  $username);
                   4708:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4709: 
                   4710:         # role expired or not available yet?
                   4711:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4712:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4713: 
                   4714:         next if $area eq '' or $trole eq '';
                   4715: 
                   4716:         my $spec = "$trole.$area";
                   4717:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4718: 
                   4719:         if ($trole =~ /^cr\//) {
                   4720:         # Custom role, defined by a user
                   4721:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4722:         } elsif ($trole eq 'gr') {
                   4723:         # Role of a member in a group, defined within a course/community
                   4724:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4725:             next;
                   4726:         } else {
                   4727:         # Normal role, defined in roles.tab
                   4728:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4729:         }
                   4730: 
                   4731:         my $cid = $tdomain.'_'.$trest;
                   4732:         unless ($firstaccchk{$cid}) {
                   4733:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4734:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4735:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4736:                         $coursetimerstarts{$cid}{$item}; 
                   4737:                 }
                   4738:             }
                   4739:             $firstaccchk{$cid} = 1;
                   4740:         }
                   4741:         unless ($timerintchk{$cid}) {
                   4742:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4743:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4744:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4745:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4746:                 }
1.12      www      4747:             }
1.1169    droeschl 4748:             $timerintchk{$cid} = 1;
1.191     harris41 4749:         }
1.11      www      4750:     }
1.1169    droeschl 4751: 
                   4752:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4753:         \%allroles, \%allgroups);
                   4754:     $env{'user.adv'} = $userroles{'user.adv'};
                   4755: 
1.1162    raeburn  4756:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4757: }
                   4758: 
1.567     raeburn  4759: sub set_arearole {
                   4760:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4761: # log the associated role with the area
                   4762:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4763:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4764: }
                   4765: 
                   4766: sub custom_roleprivs {
                   4767:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4768:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4769:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4770:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4771:         my ($rdummy,$roledef)=
                   4772:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4773:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4774:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4775:             if (defined($syspriv)) {
1.1043    raeburn  4776:                 if ($trest =~ /^$match_community$/) {
                   4777:                     $syspriv =~ s/bre\&S//; 
                   4778:                 }
1.567     raeburn  4779:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4780:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4781:             }
                   4782:             if ($tdomain ne '') {
                   4783:                 if (defined($dompriv)) {
                   4784:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4785:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4786:                 }
                   4787:                 if (($trest ne '') && (defined($coursepriv))) {
                   4788:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4789:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4790:                 }
                   4791:             }
                   4792:         }
                   4793:     }
                   4794: }
                   4795: 
1.678     raeburn  4796: sub group_roleprivs {
                   4797:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4798:     my $access = 1;
                   4799:     my $now = time;
                   4800:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4801:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4802:     if ($access) {
1.811     albertel 4803:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4804:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4805:     }
                   4806: }
1.567     raeburn  4807: 
                   4808: sub standard_roleprivs {
                   4809:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4810:     if (defined($pr{$trole.':s'})) {
                   4811:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4812:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4813:     }
                   4814:     if ($tdomain ne '') {
                   4815:         if (defined($pr{$trole.':d'})) {
                   4816:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4817:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4818:         }
                   4819:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4820:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4821:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4822:         }
                   4823:     }
                   4824: }
                   4825: 
                   4826: sub set_userprivs {
1.1064    raeburn  4827:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4828:     my $author=0;
                   4829:     my $adv=0;
1.678     raeburn  4830:     my %grouproles = ();
                   4831:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4832:         my @groupkeys; 
1.1000    raeburn  4833:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4834:             push(@groupkeys,$role);
                   4835:         }
                   4836:         if (ref($groups_roles) eq 'HASH') {
                   4837:             foreach my $key (keys(%{$groups_roles})) {
                   4838:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4839:                     push(@groupkeys,$key);
                   4840:                 }
                   4841:             }
                   4842:         }
                   4843:         if (@groupkeys > 0) {
                   4844:             foreach my $role (@groupkeys) {
                   4845:                 my ($trole,$area,$sec,$extendedarea);
                   4846:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4847:                     $trole = $1;
                   4848:                     $area = $2;
                   4849:                     $sec = $3;
                   4850:                     $extendedarea = $area.$sec;
                   4851:                     if (exists($$allgroups{$area})) {
                   4852:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4853:                             my $spec = $trole.'.'.$extendedarea;
                   4854:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4855:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4856:                         }
1.678     raeburn  4857:                     }
                   4858:                 }
                   4859:             }
                   4860:         }
                   4861:     }
1.800     albertel 4862:     foreach my $group (keys(%grouproles)) {
                   4863:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4864:     }
1.800     albertel 4865:     foreach my $role (keys(%{$allroles})) {
                   4866:         my %thesepriv;
1.941     raeburn  4867:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4868:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4869:             if ($item ne '') {
                   4870:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4871:                 if ($restrictions eq '') {
                   4872:                     $thesepriv{$privilege}='F';
                   4873:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4874:                     $thesepriv{$privilege}.=$restrictions;
                   4875:                 }
                   4876:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4877:             }
                   4878:         }
                   4879:         my $thesestr='';
1.1104    raeburn  4880:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4881: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4882: 	}
                   4883:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4884:     }
                   4885:     return ($author,$adv);
                   4886: }
                   4887: 
1.994     raeburn  4888: sub role_status {
1.1104    raeburn  4889:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4890:     my @pwhere = ();
                   4891:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4892:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4893:         unless (!defined($$role) || $$role eq '') {
                   4894:             $$where=join('.',@pwhere);
                   4895:             $$trolecode=$$role.'.'.$$where;
                   4896:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4897:             $$tstatus='is';
1.1104    raeburn  4898:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4899:                 $$tstatus='future';
1.1034    raeburn  4900:                 if ($$tstart<$now) {
                   4901:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4902:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4903:                             my (%allroles,%allgroups,$group_privs,
                   4904:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4905:                             my %userroles = (
                   4906:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4907:                             );
1.1064    raeburn  4908:                             @rolecodes = ('cm'); 
1.1002    raeburn  4909:                             my $spec=$$role.'.'.$$where;
                   4910:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4911:                             if ($$role =~ /^cr\//) {
                   4912:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4913:                                 push(@rolecodes,'cr');
1.1002    raeburn  4914:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4915:                                 push(@rolecodes,$$role);
1.1002    raeburn  4916:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4917:                                                     $env{'user.name'});
1.1064    raeburn  4918:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4919:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4920:                                 $group_privs = &unescape($group_privs);
                   4921:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4922:                                 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  4923:                                 &get_groups_roles($tdomain,$trest,
                   4924:                                                   \%course_roles,\@rolecodes,
                   4925:                                                   \%groups_roles);
1.1002    raeburn  4926:                             } else {
1.1064    raeburn  4927:                                 push(@rolecodes,$$role);
1.1002    raeburn  4928:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4929:                             }
1.1064    raeburn  4930:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4931:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4932:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4933:                         }
                   4934:                     }
1.1034    raeburn  4935:                     $$tstatus = 'is';
1.1002    raeburn  4936:                 }
1.994     raeburn  4937:             }
                   4938:             if ($$tend) {
1.1104    raeburn  4939:                 if ($$tend<$update) {
1.994     raeburn  4940:                     $$tstatus='expired';
                   4941:                 } elsif ($$tend<$now) {
                   4942:                     $$tstatus='will_not';
                   4943:                 }
                   4944:             }
                   4945:         }
                   4946:     }
                   4947: }
                   4948: 
1.1104    raeburn  4949: sub get_groups_roles {
                   4950:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4951:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4952:                   (ref($rolecodes) eq 'ARRAY') && 
                   4953:                   (ref($groups_roles) eq 'HASH')); 
                   4954:     if (keys(%{$cdom_courseroles}) > 0) {
                   4955:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4956:         if ($cdom ne '' && $cnum ne '') {
                   4957:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4958:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4959:                     my $crsrole = $1;
                   4960:                     my $crssec = $2;
                   4961:                     if ($crsrole =~ /^cr/) {
                   4962:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4963:                             push(@{$rolecodes},'cr');
                   4964:                         }
                   4965:                     } else {
                   4966:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4967:                             push(@{$rolecodes},$crsrole);
                   4968:                         }
                   4969:                     }
                   4970:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4971:                     if ($crssec ne '') {
                   4972:                         $rolekey .= "/$crssec";
                   4973:                     }
                   4974:                     $rolekey .= './';
                   4975:                     $groups_roles->{$rolekey} = $rolecodes;
                   4976:                 }
                   4977:             }
                   4978:         }
                   4979:     }
                   4980:     return;
                   4981: }
                   4982: 
                   4983: sub delete_env_groupprivs {
                   4984:     my ($where,$courseroles,$possroles) = @_;
                   4985:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4986:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4987:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4988:         %{$courseroles->{$udom}} =
                   4989:             &get_my_roles('','','userroles',['active'],
                   4990:                           $possroles,[$udom],1);
                   4991:     }
                   4992:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4993:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4994:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4995:             my $area = '/'.$cdom.'/'.$cnum;
                   4996:             my $privkey = "user.priv.$crsrole.$area";
                   4997:             if ($crssec ne '') {
                   4998:                 $privkey .= '/'.$crssec;
                   4999:             }
                   5000:             $privkey .= ".$area/$group";
                   5001:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   5002:         }
                   5003:     }
                   5004:     return;
                   5005: }
                   5006: 
1.994     raeburn  5007: sub check_adhoc_privs {
1.1104    raeburn  5008:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  5009:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   5010:     if ($env{$cckey}) {
                   5011:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  5012:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  5013:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  5014:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  5015:         }
                   5016:     } else {
1.1088    raeburn  5017:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  5018:     }
                   5019: }
                   5020: 
                   5021: sub set_adhoc_privileges {
                   5022: # role can be cc or ca
1.1088    raeburn  5023:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5024:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5025:     my $spec = $role.'.'.$area;
                   5026:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5027:                                   $env{'user.name'});
                   5028:     my %ccrole = ();
                   5029:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5030:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5031:     &appenv(\%userroles,[$role,'cm']);
                   5032:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5033:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5034:         &appenv( {'request.role'        => $spec,
                   5035:                   'request.role.domain' => $dcdom,
                   5036:                   'request.course.sec'  => ''
                   5037:                  }
                   5038:                );
                   5039:         my $tadv=0;
                   5040:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5041:         &appenv({'request.role.adv'    => $tadv});
                   5042:     }
1.994     raeburn  5043: }
                   5044: 
1.12      www      5045: # --------------------------------------------------------------- get interface
                   5046: 
                   5047: sub get {
1.131     albertel 5048:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5049:    my $items='';
1.800     albertel 5050:    foreach my $item (@$storearr) {
                   5051:        $items.=&escape($item).'&';
1.191     harris41 5052:    }
1.12      www      5053:    $items=~s/\&$//;
1.620     albertel 5054:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5055:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5056:    my $uhome=&homeserver($uname,$udomain);
                   5057: 
1.133     albertel 5058:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5059:    my @pairs=split(/\&/,$rep);
1.273     albertel 5060:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5061:      return @pairs;
                   5062:    }
1.15      www      5063:    my %returnhash=();
1.42      www      5064:    my $i=0;
1.800     albertel 5065:    foreach my $item (@$storearr) {
                   5066:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5067:       $i++;
1.191     harris41 5068:    }
1.15      www      5069:    return %returnhash;
1.27      www      5070: }
                   5071: 
                   5072: # --------------------------------------------------------------- del interface
                   5073: 
                   5074: sub del {
1.133     albertel 5075:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5076:    my $items='';
1.800     albertel 5077:    foreach my $item (@$storearr) {
                   5078:        $items.=&escape($item).'&';
1.191     harris41 5079:    }
1.984     neumanie 5080: 
1.27      www      5081:    $items=~s/\&$//;
1.620     albertel 5082:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5083:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5084:    my $uhome=&homeserver($uname,$udomain);
                   5085:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5086: }
                   5087: 
                   5088: # -------------------------------------------------------------- dump interface
                   5089: 
1.1180    droeschl 5090: sub unserialize {
                   5091:     my ($rep, $escapedkeys) = @_;
                   5092: 
                   5093:     return {} if $rep =~ /^error/;
                   5094: 
                   5095:     my %returnhash=();
                   5096: 	foreach my $item (split /\&/, $rep) {
                   5097: 	    my ($key, $value) = split(/=/, $item, 2);
                   5098: 	    $key = unescape($key) unless $escapedkeys;
                   5099: 	    next if $key =~ /^error: 2 /;
                   5100: 	    $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
                   5101: 	}
                   5102:     #return %returnhash;
                   5103:     return \%returnhash;
                   5104: }        
                   5105: 
                   5106: # see Lond::dump_with_regexp
                   5107: # if $escapedkeys hash keys won't get unescaped.
1.15      www      5108: sub dump {
1.1180    droeschl 5109:     my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755     albertel 5110:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5111:     if (!$uname) { $uname=$env{'user.name'}; }
                   5112:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5113: 
1.1180    droeschl 5114:     my $reply;
                   5115:     if (grep { $_ eq $uhome } current_machine_ids()) {
                   5116:         # user is hosted on this machine
                   5117:         $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
                   5118:                     $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
                   5119:         return %{unserialize($reply, $escapedkeys)};
                   5120:     }
1.755     albertel 5121:     if ($regexp) {
                   5122: 	$regexp=&escape($regexp);
                   5123:     } else {
                   5124: 	$regexp='.';
                   5125:     }
1.1166    raeburn  5126:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5127:     my @pairs=split(/\&/,$rep);
                   5128:     my %returnhash=();
1.1098    foxr     5129:     if (!($rep =~ /^error/ )) {
                   5130: 	foreach my $item (@pairs) {
                   5131: 	    my ($key,$value)=split(/=/,$item,2);
1.1180    droeschl 5132:         $key = unescape($key) unless $escapedkeys;
                   5133:         #$key = &unescape($key);
1.1098    foxr     5134: 	    next if ($key =~ /^error: 2 /);
                   5135: 	    $returnhash{$key}=&thaw_unescape($value);
                   5136: 	}
1.755     albertel 5137:     }
                   5138:     return %returnhash;
1.407     www      5139: }
                   5140: 
1.1098    foxr     5141: 
1.717     albertel 5142: # --------------------------------------------------------- dumpstore interface
                   5143: 
                   5144: sub dumpstore {
                   5145:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180    droeschl 5146:    # same as dump but keys must be escaped. They may contain colon separated
                   5147:    # lists of values that may themself contain colons (e.g. symbs).
                   5148:    return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717     albertel 5149: }
                   5150: 
1.407     www      5151: # -------------------------------------------------------------- keys interface
                   5152: 
                   5153: sub getkeys {
                   5154:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5155:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5156:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5157:    my $uhome=&homeserver($uname,$udomain);
                   5158:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5159:    my @keyarray=();
1.800     albertel 5160:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5161:       next if ($key =~ /^error: 2 /);
1.800     albertel 5162:       push(@keyarray,&unescape($key));
1.407     www      5163:    }
                   5164:    return @keyarray;
1.318     matthew  5165: }
                   5166: 
1.319     matthew  5167: # --------------------------------------------------------------- currentdump
                   5168: sub currentdump {
1.328     matthew  5169:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5170:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5171:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5172:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5173:    my $uhome = &homeserver($sname,$sdom);
1.1180    droeschl 5174:    my $rep;
                   5175: 
                   5176:    if (grep { $_ eq $uhome } current_machine_ids()) {
                   5177:        $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname, 
                   5178:                    $courseid)));
                   5179:    } else {
                   5180:        $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
                   5181:    }
                   5182: 
1.318     matthew  5183:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5184:    #
1.318     matthew  5185:    my %returnhash=();
1.319     matthew  5186:    #
                   5187:    if ($rep eq "unknown_cmd") { 
                   5188:        # an old lond will not know currentdump
                   5189:        # Do a dump and make it look like a currentdump
1.822     albertel 5190:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5191:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5192:        my %hash = @tmp;
                   5193:        @tmp=();
1.424     matthew  5194:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5195:    } else {
                   5196:        my @pairs=split(/\&/,$rep);
1.800     albertel 5197:        foreach my $pair (@pairs) {
                   5198:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5199:            my ($symb,$param) = split(/:/,$key);
                   5200:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5201:                                                         &thaw_unescape($value);
1.319     matthew  5202:        }
1.191     harris41 5203:    }
1.12      www      5204:    return %returnhash;
1.424     matthew  5205: }
                   5206: 
                   5207: sub convert_dump_to_currentdump{
                   5208:     my %hash = %{shift()};
                   5209:     my %returnhash;
                   5210:     # Code ripped from lond, essentially.  The only difference
                   5211:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5212:     # we might run in to problems with parameter names =~ /^v\./
                   5213:     while (my ($key,$value) = each(%hash)) {
                   5214:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5215: 	$symb  = &unescape($symb);
                   5216: 	$param = &unescape($param);
1.424     matthew  5217:         next if ($v eq 'version' || $symb eq 'keys');
                   5218:         next if (exists($returnhash{$symb}) &&
                   5219:                  exists($returnhash{$symb}->{$param}) &&
                   5220:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5221:         $returnhash{$symb}->{$param}=$value;
                   5222:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5223:     }
                   5224:     #
                   5225:     # Remove all of the keys in the hashes which keep track of
                   5226:     # the version of the parameter.
                   5227:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5228:         # use a foreach because we are going to delete from the hash.
                   5229:         foreach my $key (keys(%$param_hash)) {
                   5230:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5231:         }
                   5232:     }
                   5233:     return \%returnhash;
1.12      www      5234: }
                   5235: 
1.627     albertel 5236: # ------------------------------------------------------ critical inc interface
                   5237: 
                   5238: sub cinc {
                   5239:     return &inc(@_,'critical');
                   5240: }
                   5241: 
1.449     matthew  5242: # --------------------------------------------------------------- inc interface
                   5243: 
                   5244: sub inc {
1.627     albertel 5245:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5246:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5247:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5248:     my $uhome=&homeserver($uname,$udomain);
                   5249:     my $items='';
                   5250:     if (! ref($store)) {
                   5251:         # got a single value, so use that instead
                   5252:         $items = &escape($store).'=&';
                   5253:     } elsif (ref($store) eq 'SCALAR') {
                   5254:         $items = &escape($$store).'=&';        
                   5255:     } elsif (ref($store) eq 'ARRAY') {
                   5256:         $items = join('=&',map {&escape($_);} @{$store});
                   5257:     } elsif (ref($store) eq 'HASH') {
                   5258:         while (my($key,$value) = each(%{$store})) {
                   5259:             $items.= &escape($key).'='.&escape($value).'&';
                   5260:         }
                   5261:     }
                   5262:     $items=~s/\&$//;
1.627     albertel 5263:     if ($critical) {
                   5264: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5265:     } else {
                   5266: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5267:     }
1.449     matthew  5268: }
                   5269: 
1.12      www      5270: # --------------------------------------------------------------- put interface
                   5271: 
                   5272: sub put {
1.134     albertel 5273:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5274:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5275:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5276:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5277:    my $items='';
1.800     albertel 5278:    foreach my $item (keys(%$storehash)) {
                   5279:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5280:    }
1.12      www      5281:    $items=~s/\&$//;
1.134     albertel 5282:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5283: }
                   5284: 
1.631     albertel 5285: # ------------------------------------------------------------ newput interface
                   5286: 
                   5287: sub newput {
                   5288:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5289:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5290:    if (!$uname) { $uname=$env{'user.name'}; }
                   5291:    my $uhome=&homeserver($uname,$udomain);
                   5292:    my $items='';
                   5293:    foreach my $key (keys(%$storehash)) {
                   5294:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5295:    }
                   5296:    $items=~s/\&$//;
                   5297:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5298: }
                   5299: 
                   5300: # ---------------------------------------------------------  putstore interface
                   5301: 
1.524     raeburn  5302: sub putstore {
1.715     albertel 5303:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5304:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5305:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5306:    my $uhome=&homeserver($uname,$udomain);
                   5307:    my $items='';
1.715     albertel 5308:    foreach my $key (keys(%$storehash)) {
                   5309:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5310:    }
1.715     albertel 5311:    $items=~s/\&$//;
1.716     albertel 5312:    my $esc_symb=&escape($symb);
                   5313:    my $esc_v=&escape($version);
1.715     albertel 5314:    my $reply =
1.716     albertel 5315:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5316: 	      $uhome);
                   5317:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5318:        # gfall back to way things use to be done
1.715     albertel 5319:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5320: 			    $uname);
1.524     raeburn  5321:    }
1.715     albertel 5322:    return $reply;
                   5323: }
                   5324: 
                   5325: sub old_putstore {
1.716     albertel 5326:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5327:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5328:     if (!$uname) { $uname=$env{'user.name'}; }
                   5329:     my $uhome=&homeserver($uname,$udomain);
                   5330:     my %newstorehash;
1.800     albertel 5331:     foreach my $item (keys(%$storehash)) {
                   5332: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5333: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5334:     }
                   5335:     my $items='';
                   5336:     my %allitems = ();
1.800     albertel 5337:     foreach my $item (keys(%newstorehash)) {
                   5338: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5339: 	    my $key = $1.':keys:'.$2;
                   5340: 	    $allitems{$key} .= $3.':';
                   5341: 	}
1.800     albertel 5342: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5343:     }
1.800     albertel 5344:     foreach my $item (keys(%allitems)) {
                   5345: 	$allitems{$item} =~ s/\:$//;
                   5346: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5347:     }
                   5348:     $items=~s/\&$//;
                   5349:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5350: }
                   5351: 
1.47      www      5352: # ------------------------------------------------------ critical put interface
                   5353: 
                   5354: sub cput {
1.134     albertel 5355:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5356:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5357:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5358:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5359:    my $items='';
1.800     albertel 5360:    foreach my $item (keys(%$storehash)) {
                   5361:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5362:    }
1.47      www      5363:    $items=~s/\&$//;
1.134     albertel 5364:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5365: }
                   5366: 
                   5367: # -------------------------------------------------------------- eget interface
                   5368: 
                   5369: sub eget {
1.133     albertel 5370:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5371:    my $items='';
1.800     albertel 5372:    foreach my $item (@$storearr) {
                   5373:        $items.=&escape($item).'&';
1.191     harris41 5374:    }
1.12      www      5375:    $items=~s/\&$//;
1.620     albertel 5376:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5377:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5378:    my $uhome=&homeserver($uname,$udomain);
                   5379:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5380:    my @pairs=split(/\&/,$rep);
                   5381:    my %returnhash=();
1.42      www      5382:    my $i=0;
1.800     albertel 5383:    foreach my $item (@$storearr) {
                   5384:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5385:       $i++;
1.191     harris41 5386:    }
1.12      www      5387:    return %returnhash;
                   5388: }
                   5389: 
1.667     albertel 5390: # ------------------------------------------------------------ tmpput interface
                   5391: sub tmpput {
1.802     raeburn  5392:     my ($storehash,$server,$context)=@_;
1.667     albertel 5393:     my $items='';
1.800     albertel 5394:     foreach my $item (keys(%$storehash)) {
                   5395: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5396:     }
                   5397:     $items=~s/\&$//;
1.802     raeburn  5398:     if (defined($context)) {
                   5399:         $items .= ':'.&escape($context);
                   5400:     }
1.667     albertel 5401:     return &reply("tmpput:$items",$server);
                   5402: }
                   5403: 
                   5404: # ------------------------------------------------------------ tmpget interface
                   5405: sub tmpget {
1.688     albertel 5406:     my ($token,$server)=@_;
                   5407:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5408:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5409:     my %returnhash;
                   5410:     foreach my $item (split(/\&/,$rep)) {
                   5411: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5412:         next if ($key =~ /^error: 2 /);
1.667     albertel 5413: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5414:     }
                   5415:     return %returnhash;
                   5416: }
                   5417: 
1.1113    raeburn  5418: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5419: sub tmpdel {
                   5420:     my ($token,$server)=@_;
                   5421:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5422:     return &reply("tmpdel:$token",$server);
                   5423: }
                   5424: 
1.765     albertel 5425: # -------------------------------------------------- portfolio access checking
                   5426: 
                   5427: sub portfolio_access {
1.766     albertel 5428:     my ($requrl) = @_;
1.765     albertel 5429:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5430:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5431:     if ($result) {
                   5432:         my %setters;
                   5433:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5434:             my ($startblock,$endblock) =
                   5435:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5436:             if ($startblock && $endblock) {
                   5437:                 return 'B';
                   5438:             }
                   5439:         } else {
                   5440:             my ($startblock,$endblock) =
                   5441:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5442:             if ($startblock && $endblock) {
                   5443:                 return 'B';
                   5444:             }
                   5445:         }
                   5446:     }
1.765     albertel 5447:     if ($result eq 'ok') {
1.766     albertel 5448:        return 'F';
1.765     albertel 5449:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5450:        return 'A';
1.765     albertel 5451:     }
1.766     albertel 5452:     return '';
1.765     albertel 5453: }
                   5454: 
                   5455: sub get_portfolio_access {
1.767     albertel 5456:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5457: 
                   5458:     if (!ref($access_hash)) {
                   5459: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5460: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5461: 						   $file_name);
                   5462: 	$access_hash = $access_controls{$file_name};
                   5463:     }
                   5464: 
1.765     albertel 5465:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5466:     my $now = time;
                   5467:     if (ref($access_hash) eq 'HASH') {
                   5468:         foreach my $key (keys(%{$access_hash})) {
                   5469:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5470:             if ($start > $now) {
                   5471:                 next;
                   5472:             }
                   5473:             if ($end && $end<$now) {
                   5474:                 next;
                   5475:             }
                   5476:             if ($scope eq 'public') {
                   5477:                 $public = $key;
                   5478:                 last;
                   5479:             } elsif ($scope eq 'guest') {
                   5480:                 $guest = $key;
                   5481:             } elsif ($scope eq 'domains') {
                   5482:                 push(@domains,$key);
                   5483:             } elsif ($scope eq 'users') {
                   5484:                 push(@users,$key);
                   5485:             } elsif ($scope eq 'course') {
                   5486:                 push(@courses,$key);
                   5487:             } elsif ($scope eq 'group') {
                   5488:                 push(@groups,$key);
                   5489:             }
                   5490:         }
                   5491:         if ($public) {
                   5492:             return 'ok';
                   5493:         }
                   5494:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5495:             if ($guest) {
                   5496:                 return $guest;
                   5497:             }
                   5498:         } else {
                   5499:             if (@domains > 0) {
                   5500:                 foreach my $domkey (@domains) {
                   5501:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5502:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5503:                             return 'ok';
                   5504:                         }
                   5505:                     }
                   5506:                 }
                   5507:             }
                   5508:             if (@users > 0) {
                   5509:                 foreach my $userkey (@users) {
1.865     raeburn  5510:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5511:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5512:                             if (ref($item) eq 'HASH') {
                   5513:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5514:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5515:                                     return 'ok';
                   5516:                                 }
                   5517:                             }
                   5518:                         }
                   5519:                     } 
1.765     albertel 5520:                 }
                   5521:             }
                   5522:             my %roleshash;
                   5523:             my @courses_and_groups = @courses;
                   5524:             push(@courses_and_groups,@groups); 
                   5525:             if (@courses_and_groups > 0) {
                   5526:                 my (%allgroups,%allroles); 
                   5527:                 my ($start,$end,$role,$sec,$group);
                   5528:                 foreach my $envkey (%env) {
1.1060    raeburn  5529:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5530:                         my $cid = $2.'_'.$3; 
                   5531:                         if ($1 eq 'gr') {
                   5532:                             $group = $4;
                   5533:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5534:                         } else {
                   5535:                             if ($4 eq '') {
                   5536:                                 $sec = 'none';
                   5537:                             } else {
                   5538:                                 $sec = $4;
                   5539:                             }
                   5540:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5541:                         }
1.811     albertel 5542:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5543:                         my $cid = $2.'_'.$3;
                   5544:                         if ($4 eq '') {
                   5545:                             $sec = 'none';
                   5546:                         } else {
                   5547:                             $sec = $4;
                   5548:                         }
                   5549:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5550:                     }
                   5551:                 }
                   5552:                 if (keys(%allroles) == 0) {
                   5553:                     return;
                   5554:                 }
                   5555:                 foreach my $key (@courses_and_groups) {
                   5556:                     my %content = %{$$access_hash{$key}};
                   5557:                     my $cnum = $content{'number'};
                   5558:                     my $cdom = $content{'domain'};
                   5559:                     my $cid = $cdom.'_'.$cnum;
                   5560:                     if (!exists($allroles{$cid})) {
                   5561:                         next;
                   5562:                     }    
                   5563:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5564:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5565:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5566:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5567:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5568:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5569:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5570:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5571:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5572:                                         if (grep/^all$/,@sections) {
                   5573:                                             return 'ok';
                   5574:                                         } else {
                   5575:                                             if (grep/^$sec$/,@sections) {
                   5576:                                                 return 'ok';
                   5577:                                             }
                   5578:                                         }
                   5579:                                     }
                   5580:                                 }
                   5581:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5582:                                     if (grep/^none$/,@groups) {
                   5583:                                         return 'ok';
                   5584:                                     }
                   5585:                                 } else {
                   5586:                                     if (grep/^all$/,@groups) {
                   5587:                                         return 'ok';
                   5588:                                     } 
                   5589:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5590:                                         if (grep/^$group$/,@groups) {
                   5591:                                             return 'ok';
                   5592:                                         }
                   5593:                                     }
                   5594:                                 } 
                   5595:                             }
                   5596:                         }
                   5597:                     }
                   5598:                 }
                   5599:             }
                   5600:             if ($guest) {
                   5601:                 return $guest;
                   5602:             }
                   5603:         }
                   5604:     }
                   5605:     return;
                   5606: }
                   5607: 
                   5608: sub course_group_datechecker {
                   5609:     my ($dates,$now,$status) = @_;
                   5610:     my ($start,$end) = split(/\./,$dates);
                   5611:     if (!$start && !$end) {
                   5612:         return 'ok';
                   5613:     }
                   5614:     if (grep/^active$/,@{$status}) {
                   5615:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5616:             return 'ok';
                   5617:         }
                   5618:     }
                   5619:     if (grep/^previous$/,@{$status}) {
                   5620:         if ($end > $now ) {
                   5621:             return 'ok';
                   5622:         }
                   5623:     }
                   5624:     if (grep/^future$/,@{$status}) {
                   5625:         if ($start > $now) {
                   5626:             return 'ok';
                   5627:         }
                   5628:     }
                   5629:     return; 
                   5630: }
                   5631: 
                   5632: sub parse_portfolio_url {
                   5633:     my ($url) = @_;
                   5634: 
                   5635:     my ($type,$udom,$unum,$group,$file_name);
                   5636:     
1.823     albertel 5637:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5638: 	$type = 1;
                   5639:         $udom = $1;
                   5640:         $unum = $2;
                   5641:         $file_name = $3;
1.823     albertel 5642:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5643: 	$type = 2;
                   5644:         $udom = $1;
                   5645:         $unum = $2;
                   5646:         $group = $3;
                   5647:         $file_name = $3.'/'.$4;
                   5648:     }
                   5649:     if (wantarray) {
                   5650: 	return ($type,$udom,$unum,$file_name,$group);
                   5651:     }
                   5652:     return $type;
                   5653: }
                   5654: 
                   5655: sub is_portfolio_url {
                   5656:     my ($url) = @_;
                   5657:     return scalar(&parse_portfolio_url($url));
                   5658: }
                   5659: 
1.798     raeburn  5660: sub is_portfolio_file {
                   5661:     my ($file) = @_;
1.820     raeburn  5662:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5663:         return 1;
                   5664:     }
                   5665:     return;
                   5666: }
                   5667: 
1.976     raeburn  5668: sub usertools_access {
1.1084    raeburn  5669:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5670:     my ($access,%tools);
                   5671:     if ($context eq '') {
                   5672:         $context = 'tools';
                   5673:     }
                   5674:     if ($context eq 'requestcourses') {
                   5675:         %tools = (
                   5676:                       official   => 1,
                   5677:                       unofficial => 1,
1.1006    raeburn  5678:                       community  => 1,
1.985     raeburn  5679:                  );
                   5680:     } else {
                   5681:         %tools = (
                   5682:                       aboutme   => 1,
                   5683:                       blog      => 1,
1.1177    raeburn  5684:                       webdav    => 1,
1.985     raeburn  5685:                       portfolio => 1,
                   5686:                  );
                   5687:     }
1.976     raeburn  5688:     return if (!defined($tools{$tool}));
                   5689: 
                   5690:     if ((!defined($udom)) || (!defined($uname))) {
                   5691:         $udom = $env{'user.domain'};
                   5692:         $uname = $env{'user.name'};
                   5693:     }
                   5694: 
1.978     raeburn  5695:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5696:         if ($action ne 'reload') {
1.985     raeburn  5697:             if ($context eq 'requestcourses') {
                   5698:                 return $env{'environment.canrequest.'.$tool};
                   5699:             } else {
                   5700:                 return $env{'environment.availabletools.'.$tool};
                   5701:             }
                   5702:         }
1.976     raeburn  5703:     }
                   5704: 
                   5705:     my ($toolstatus,$inststatus);
                   5706: 
1.985     raeburn  5707:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5708:          ($action ne 'reload')) {
                   5709:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5710:         $inststatus = $env{'environment.inststatus'};
                   5711:     } else {
1.1084    raeburn  5712:         if (ref($userenvref) eq 'HASH') {
                   5713:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5714:             $inststatus = $userenvref->{'inststatus'};
                   5715:         } else {
                   5716:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5717:             $toolstatus = $userenv{$context.'.'.$tool};
                   5718:             $inststatus = $userenv{'inststatus'};
                   5719:         }
1.976     raeburn  5720:     }
                   5721: 
                   5722:     if ($toolstatus ne '') {
                   5723:         if ($toolstatus) {
                   5724:             $access = 1;
                   5725:         } else {
                   5726:             $access = 0;
                   5727:         }
                   5728:         return $access;
                   5729:     }
                   5730: 
1.1084    raeburn  5731:     my ($is_adv,%domdef);
                   5732:     if (ref($is_advref) eq 'HASH') {
                   5733:         $is_adv = $is_advref->{'is_adv'};
                   5734:     } else {
                   5735:         $is_adv = &is_advanced_user($udom,$uname);
                   5736:     }
                   5737:     if (ref($domdefref) eq 'HASH') {
                   5738:         %domdef = %{$domdefref};
                   5739:     } else {
                   5740:         %domdef = &get_domain_defaults($udom);
                   5741:     }
1.976     raeburn  5742:     if (ref($domdef{$tool}) eq 'HASH') {
                   5743:         if ($is_adv) {
                   5744:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5745:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5746:                     $access = 1;
                   5747:                 } else {
                   5748:                     $access = 0;
                   5749:                 }
                   5750:                 return $access;
                   5751:             }
                   5752:         }
                   5753:         if ($inststatus ne '') {
                   5754:             my ($hasaccess,$hasnoaccess);
                   5755:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5756:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5757:                     if ($domdef{$tool}{$affiliation}) {
                   5758:                         $hasaccess = 1;
                   5759:                     } else {
                   5760:                         $hasnoaccess = 1;
                   5761:                     }
                   5762:                 }
                   5763:             }
                   5764:             if ($hasaccess || $hasnoaccess) {
                   5765:                 if ($hasaccess) {
                   5766:                     $access = 1;
                   5767:                 } elsif ($hasnoaccess) {
                   5768:                     $access = 0; 
                   5769:                 }
                   5770:                 return $access;
                   5771:             }
                   5772:         } else {
                   5773:             if ($domdef{$tool}{'default'} ne '') {
                   5774:                 if ($domdef{$tool}{'default'}) {
                   5775:                     $access = 1;
                   5776:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5777:                     $access = 0;
                   5778:                 }
                   5779:                 return $access;
                   5780:             }
                   5781:         }
                   5782:     } else {
1.1177    raeburn  5783:         if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985     raeburn  5784:             $access = 1;
                   5785:         } else {
                   5786:             $access = 0;
                   5787:         }
1.976     raeburn  5788:         return $access;
                   5789:     }
                   5790: }
                   5791: 
1.1050    raeburn  5792: sub is_course_owner {
                   5793:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5794:     if (($udom eq '') || ($uname eq '')) {
                   5795:         $udom = $env{'user.domain'};
                   5796:         $uname = $env{'user.name'};
                   5797:     }
                   5798:     unless (($udom eq '') || ($uname eq '')) {
                   5799:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5800:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5801:                 return 1;
                   5802:             } else {
                   5803:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5804:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5805:                     return 1;
                   5806:                 }
                   5807:             }
                   5808:         }
                   5809:     }
                   5810:     return;
                   5811: }
                   5812: 
1.976     raeburn  5813: sub is_advanced_user {
                   5814:     my ($udom,$uname) = @_;
1.1085    raeburn  5815:     if ($udom ne '' && $uname ne '') {
                   5816:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5817:             if (wantarray) {
                   5818:                 return ($env{'user.adv'},$env{'user.author'});
                   5819:             } else {
                   5820:                 return $env{'user.adv'};
                   5821:             }
1.1085    raeburn  5822:         }
                   5823:     }
1.976     raeburn  5824:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5825:     my %allroles;
1.1128    raeburn  5826:     my ($is_adv,$is_author);
1.976     raeburn  5827:     foreach my $role (keys(%roleshash)) {
                   5828:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5829:         my $area = '/'.$tdomain.'/'.$trest;
                   5830:         if ($sec ne '') {
                   5831:             $area .= '/'.$sec;
                   5832:         }
                   5833:         if (($area ne '') && ($trole ne '')) {
                   5834:             my $spec=$trole.'.'.$area;
                   5835:             if ($trole =~ /^cr\//) {
                   5836:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5837:             } elsif ($trole ne 'gr') {
                   5838:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5839:             }
1.1128    raeburn  5840:             if ($trole eq 'au') {
                   5841:                 $is_author = 1;
                   5842:             }
1.976     raeburn  5843:         }
                   5844:     }
                   5845:     foreach my $role (keys(%allroles)) {
                   5846:         last if ($is_adv);
                   5847:         foreach my $item (split(/:/,$allroles{$role})) {
                   5848:             if ($item ne '') {
                   5849:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5850:                 if ($privilege eq 'adv') {
                   5851:                     $is_adv = 1;
                   5852:                     last;
                   5853:                 }
                   5854:             }
                   5855:         }
                   5856:     }
1.1128    raeburn  5857:     if (wantarray) {
                   5858:         return ($is_adv,$is_author);
                   5859:     }
1.976     raeburn  5860:     return $is_adv;
                   5861: }
1.798     raeburn  5862: 
1.1035    raeburn  5863: sub check_can_request {
1.1036    raeburn  5864:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5865:     my $canreq = 0;
                   5866:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5867:     my @options = ('approval','validate','autolimit');
                   5868:     my $optregex = join('|',@options);
                   5869:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5870:         foreach my $type (@{$types}) {
                   5871:             if (&usertools_access($env{'user.name'},
                   5872:                                   $env{'user.domain'},
                   5873:                                   $type,undef,'requestcourses')) {
                   5874:                 $canreq ++;
1.1036    raeburn  5875:                 if (ref($request_domains) eq 'HASH') {
                   5876:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5877:                 }
1.1035    raeburn  5878:                 if ($dom eq $env{'user.domain'}) {
                   5879:                     $can_request->{$type} = 1;
                   5880:                 }
                   5881:             }
                   5882:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5883:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5884:                 if (@curr > 0) {
1.1036    raeburn  5885:                     foreach my $item (@curr) {
                   5886:                         if (ref($request_domains) eq 'HASH') {
                   5887:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5888:                             if ($otherdom ne '') {
                   5889:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5890:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5891:                                         push(@{$request_domains->{$type}},$otherdom);
                   5892:                                     }
                   5893:                                 } else {
                   5894:                                     push(@{$request_domains->{$type}},$otherdom);
                   5895:                                 }
                   5896:                             }
                   5897:                         }
                   5898:                     }
                   5899:                     unless($dom eq $env{'user.domain'}) {
                   5900:                         $canreq ++;
1.1035    raeburn  5901:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5902:                             $can_request->{$type} = 1;
                   5903:                         }
                   5904:                     }
                   5905:                 }
                   5906:             }
                   5907:         }
                   5908:     }
                   5909:     return $canreq;
                   5910: }
                   5911: 
1.341     www      5912: # ---------------------------------------------- Custom access rule evaluation
                   5913: 
                   5914: sub customaccess {
                   5915:     my ($priv,$uri)=@_;
1.807     albertel 5916:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5917:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5918:     $udom = &LONCAPA::clean_domain($udom);
                   5919:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5920:     my $access=0;
1.800     albertel 5921:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5922: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5923: 	if ($type eq 'user') {
                   5924: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5925: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5926: 		if ($tdom) {
                   5927: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5928: 		}
1.896     albertel 5929: 		if ($tuname) {
                   5930: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5931: 		}
                   5932: 		$access=($effect eq 'allow');
                   5933: 		last;
                   5934: 	    }
                   5935: 	} else {
                   5936: 	    if ($role) {
                   5937: 		if ($role ne $urole) { next; }
                   5938: 	    }
                   5939: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5940: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5941: 		if ($tdom) {
                   5942: 		    if ($tdom ne $udom) { next; }
                   5943: 		}
                   5944: 		if ($tcrs) {
                   5945: 		    if ($tcrs ne $ucrs) { next; }
                   5946: 		}
                   5947: 		if ($tsec) {
                   5948: 		    if ($tsec ne $usec) { next; }
                   5949: 		}
                   5950: 		$access=($effect eq 'allow');
                   5951: 		last;
                   5952: 	    }
                   5953: 	    if ($realm eq '' && $role eq '') {
                   5954: 		$access=($effect eq 'allow');
                   5955: 	    }
1.402     bowersj2 5956: 	}
1.341     www      5957:     }
                   5958:     return $access;
                   5959: }
                   5960: 
1.103     harris41 5961: # ------------------------------------------------- Check for a user privilege
1.12      www      5962: 
                   5963: sub allowed {
1.810     raeburn  5964:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5965:     my $ver_orguri=$uri;
1.439     www      5966:     $uri=&deversion($uri);
1.152     www      5967:     my $orguri=$uri;
1.52      www      5968:     $uri=&declutter($uri);
1.809     raeburn  5969: 
1.810     raeburn  5970:     if ($priv eq 'evb') {
                   5971: # Evade communication block restrictions for specified role in a course
                   5972:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5973:             return $1;
                   5974:         } else {
                   5975:             return;
                   5976:         }
                   5977:     }
                   5978: 
1.620     albertel 5979:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5980: # Free bre access to adm and meta resources
1.775     albertel 5981:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5982: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5983: 	&& ($priv eq 'bre')) {
1.14      www      5984: 	return 'F';
1.159     www      5985:     }
                   5986: 
1.545     banghart 5987: # Free bre access to user's own portfolio contents
1.714     raeburn  5988:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5989:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5990: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5991:         my %setters;
                   5992:         my ($startblock,$endblock) = 
                   5993:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5994:         if ($startblock && $endblock) {
                   5995:             return 'B';
                   5996:         } else {
                   5997:             return 'F';
                   5998:         }
1.545     banghart 5999:     }
                   6000: 
1.762     raeburn  6001: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  6002:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   6003:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   6004:         if (exists($env{'request.course.id'})) {
                   6005:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6006:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6007:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   6008:                 my $courseprivid=$env{'request.course.id'};
                   6009:                 $courseprivid=~s/\_/\//;
                   6010:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   6011:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   6012:                     return $1; 
1.762     raeburn  6013:                 } else {
                   6014:                     if ($env{'request.course.sec'}) {
                   6015:                         $courseprivid.='/'.$env{'request.course.sec'};
                   6016:                     }
                   6017:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   6018:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   6019:                         return $2;
                   6020:                     }
1.714     raeburn  6021:                 }
                   6022:             }
                   6023:         }
                   6024:     }
                   6025: 
1.159     www      6026: # Free bre to public access
                   6027: 
                   6028:     if ($priv eq 'bre') {
1.238     www      6029:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 6030: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      6031:            return 'F'; 
                   6032:         }
1.238     www      6033:         if ($copyright eq 'priv') {
                   6034:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6035: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      6036: 		return '';
                   6037:             }
                   6038:         }
                   6039:         if ($copyright eq 'domain') {
                   6040:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 6041: 	    unless (($env{'user.domain'} eq $1) ||
                   6042:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      6043: 		return '';
                   6044:             }
1.262     matthew  6045:         }
1.620     albertel 6046:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6047:             # Library role, so allow browsing of resources in this domain.
                   6048:             return 'F';
1.238     www      6049:         }
1.341     www      6050:         if ($copyright eq 'custom') {
                   6051: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6052:         }
1.14      www      6053:     }
1.264     matthew  6054:     # Domain coordinator is trying to create a course
1.620     albertel 6055:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6056:         # uri is the requested domain in this case.
                   6057:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6058:         # a role of dc for the domain in question.
1.620     albertel 6059:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6060:     }
1.29      www      6061: 
1.52      www      6062:     my $thisallowed='';
                   6063:     my $statecond=0;
                   6064:     my $courseprivid='';
                   6065: 
1.1039    raeburn  6066:     my $ownaccess;
1.1043    raeburn  6067:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6068:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6069:         if ($uri eq '') {
                   6070:             $ownaccess = 1;
                   6071:         } else {
                   6072:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6073:                 my $udom = $env{'user.domain'};
                   6074:                 my $uname = $env{'user.name'};
                   6075:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6076:                     $ownaccess = 1;
1.1040    raeburn  6077:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6078:                     unless ($uri =~ m{\.\./}) {
                   6079:                         $ownaccess = 1;
                   6080:                     }
                   6081:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6082:                     my $now = time;
                   6083:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6084:                         my $adom = $1;
                   6085:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6086:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6087:                                 my ($start,$end) = split('.',$env{$key});
                   6088:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6089:                                     $ownaccess = 1;
                   6090:                                     last;
                   6091:                                 }
                   6092:                             }
                   6093:                         }
                   6094:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6095:                         my $adom = $1;
                   6096:                         my $aname = $2;
1.1042    raeburn  6097:                         foreach my $role ('ca','aa') { 
                   6098:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6099:                                 my ($start,$end) =
                   6100:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6101:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6102:                                     $ownaccess = 1;
                   6103:                                     last;
                   6104:                                 }
1.1039    raeburn  6105:                             }
                   6106:                         }
                   6107:                     }
                   6108:                 }
                   6109:             }
                   6110:         }
                   6111:     }
                   6112: 
1.52      www      6113: # Course
                   6114: 
1.620     albertel 6115:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6116:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6117:             $thisallowed.=$1;
                   6118:         }
1.52      www      6119:     }
1.29      www      6120: 
1.52      www      6121: # Domain
                   6122: 
1.620     albertel 6123:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6124:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6125:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6126:             $thisallowed.=$1;
                   6127:         }
1.12      www      6128:     }
1.52      www      6129: 
1.1141    raeburn  6130: # User who is not author or co-author might still be able to edit
                   6131: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6132:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6133:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6134:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6135:             $thisallowed.=$1;
                   6136:         }
                   6137:     }
                   6138: 
1.52      www      6139: # Course: uri itself is a course
1.66      www      6140:     my $courseuri=$uri;
                   6141:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6142:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6143: 
1.620     albertel 6144:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6145:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6146:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6147:             $thisallowed.=$1;
                   6148:         }
1.12      www      6149:     }
1.29      www      6150: 
1.665     albertel 6151: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6152: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6153:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6154: 	$thisallowed='';
1.671     raeburn  6155:         my ($match)=&is_on_map($uri);
                   6156:         if ($match) {
                   6157:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6158:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6159:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6160:                 if (@blockers > 0) {
                   6161:                     $thisallowed = 'B';
                   6162:                 } else {
                   6163:                     $thisallowed.=$1;
                   6164:                 }
1.671     raeburn  6165:             }
                   6166:         } else {
1.705     albertel 6167:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6168:             if ($refuri) {
                   6169:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6170:                     $thisallowed='F';
1.671     raeburn  6171:                 } else {
                   6172:                     $refuri=&declutter($refuri);
                   6173:                     my ($match) = &is_on_map($refuri);
                   6174:                     if ($match) {
1.1162    raeburn  6175:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6176:                         if (@blockers > 0) {
                   6177:                             $thisallowed = 'B';
                   6178:                         } else {
                   6179:                             $thisallowed='F';
                   6180:                         }
1.671     raeburn  6181:                     }
1.669     raeburn  6182:                 }
1.671     raeburn  6183:             }
                   6184:         }
1.314     www      6185:     }
1.492     albertel 6186: 
1.766     albertel 6187:     if ($priv eq 'bre'
                   6188: 	&& $thisallowed ne 'F' 
                   6189: 	&& $thisallowed ne '2'
                   6190: 	&& &is_portfolio_url($uri)) {
                   6191: 	$thisallowed = &portfolio_access($uri);
                   6192:     }
                   6193:     
1.52      www      6194: # Full access at system, domain or course-wide level? Exit.
1.29      www      6195:     if ($thisallowed=~/F/) {
                   6196: 	return 'F';
                   6197:     }
                   6198: 
1.52      www      6199: # If this is generating or modifying users, exit with special codes
1.29      www      6200: 
1.643     www      6201:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6202: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6203: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6204: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6205: 	    unless ($auname) { return $thisallowed; }
                   6206: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6207: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6208: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6209: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6210: 	}
1.52      www      6211: 	return $thisallowed;
                   6212:     }
                   6213: #
1.103     harris41 6214: # Gathered so far: system, domain and course wide privileges
1.52      www      6215: #
                   6216: # Course: See if uri or referer is an individual resource that is part of 
                   6217: # the course
                   6218: 
1.620     albertel 6219:     if ($env{'request.course.id'}) {
1.232     www      6220: 
1.620     albertel 6221:        $courseprivid=$env{'request.course.id'};
                   6222:        if ($env{'request.course.sec'}) {
                   6223:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6224:        }
                   6225:        $courseprivid=~s/\_/\//;
                   6226:        my $checkreferer=1;
1.232     www      6227:        my ($match,$cond)=&is_on_map($uri);
                   6228:        if ($match) {
                   6229:            $statecond=$cond;
1.620     albertel 6230:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6231:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6232:                my $value = $1;
                   6233:                if ($priv eq 'bre') {
                   6234:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6235:                    if (@blockers > 0) {
                   6236:                        $thisallowed = 'B';
                   6237:                    } else {
                   6238:                        $thisallowed.=$value;
                   6239:                    }
                   6240:                } else {
                   6241:                    $thisallowed.=$value;
                   6242:                }
1.52      www      6243:                $checkreferer=0;
                   6244:            }
1.29      www      6245:        }
1.83      www      6246:        
1.148     www      6247:        if ($checkreferer) {
1.620     albertel 6248: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6249:             unless ($refuri) {
1.800     albertel 6250:                 foreach my $key (keys(%env)) {
                   6251: 		    if ($key=~/^httpref\..*\*/) {
                   6252: 			my $pattern=$key;
1.156     www      6253:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6254:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6255:                         $pattern=~s/\//\\\//g;
1.152     www      6256:                         if ($orguri=~/$pattern/) {
1.800     albertel 6257: 			    $refuri=$env{$key};
1.148     www      6258:                         }
                   6259:                     }
1.191     harris41 6260:                 }
1.148     www      6261:             }
1.232     www      6262: 
1.148     www      6263:          if ($refuri) { 
1.152     www      6264: 	  $refuri=&declutter($refuri);
1.232     www      6265:           my ($match,$cond)=&is_on_map($refuri);
                   6266:             if ($match) {
                   6267:               my $refstatecond=$cond;
1.620     albertel 6268:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6269:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6270:                   my $value = $1;
                   6271:                   if ($priv eq 'bre') {
                   6272:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6273:                       if (@blockers > 0) {
                   6274:                           $thisallowed = 'B';
                   6275:                       } else {
                   6276:                           $thisallowed.=$value;
                   6277:                       }
                   6278:                   } else {
                   6279:                       $thisallowed.=$value;
                   6280:                   }
1.53      www      6281:                   $uri=$refuri;
                   6282:                   $statecond=$refstatecond;
1.52      www      6283:               }
                   6284:           }
1.148     www      6285:         }
1.29      www      6286:        }
1.52      www      6287:    }
1.29      www      6288: 
1.52      www      6289: #
1.103     harris41 6290: # Gathered now: all privileges that could apply, and condition number
1.52      www      6291: # 
                   6292: #
                   6293: # Full or no access?
                   6294: #
1.29      www      6295: 
1.52      www      6296:     if ($thisallowed=~/F/) {
                   6297: 	return 'F';
                   6298:     }
1.29      www      6299: 
1.52      www      6300:     unless ($thisallowed) {
                   6301:         return '';
                   6302:     }
1.29      www      6303: 
1.52      www      6304: # Restrictions exist, deal with them
                   6305: #
                   6306: #   C:according to course preferences
                   6307: #   R:according to resource settings
                   6308: #   L:unless locked
                   6309: #   X:according to user session state
                   6310: #
                   6311: 
                   6312: # Possibly locked functionality, check all courses
1.54      www      6313: # Locks might take effect only after 10 minutes cache expiration for other
                   6314: # courses, and 2 minutes for current course
1.52      www      6315: 
                   6316:     my $envkey;
                   6317:     if ($thisallowed=~/L/) {
1.1000    raeburn  6318:         foreach $envkey (keys(%env)) {
1.54      www      6319:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6320:                my $courseid=$2;
                   6321:                my $roleid=$1.'.'.$2;
1.92      www      6322:                $courseid=~s/^\///;
1.54      www      6323:                my $expiretime=600;
1.620     albertel 6324:                if ($env{'request.role'} eq $roleid) {
1.54      www      6325: 		  $expiretime=120;
                   6326:                }
                   6327: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6328:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6329:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6330: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6331:                }
1.620     albertel 6332:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6333:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6334: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6335:                        &log($env{'user.domain'},$env{'user.name'},
                   6336:                             $env{'user.home'},
1.57      www      6337:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6338:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6339:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6340: 		       return '';
                   6341:                    }
                   6342:                }
1.620     albertel 6343:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6344:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6345: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6346:                        &log($env{'user.domain'},$env{'user.name'},
                   6347:                             $env{'user.home'},
1.57      www      6348:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6349:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6350:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6351: 		       return '';
                   6352:                    }
                   6353:                }
                   6354: 	   }
1.29      www      6355:        }
1.52      www      6356:     }
                   6357:    
                   6358: #
                   6359: # Rest of the restrictions depend on selected course
                   6360: #
                   6361: 
1.620     albertel 6362:     unless ($env{'request.course.id'}) {
1.766     albertel 6363: 	if ($thisallowed eq 'A') {
                   6364: 	    return 'A';
1.814     raeburn  6365:         } elsif ($thisallowed eq 'B') {
                   6366:             return 'B';
1.766     albertel 6367: 	} else {
                   6368: 	    return '1';
                   6369: 	}
1.52      www      6370:     }
1.29      www      6371: 
1.52      www      6372: #
                   6373: # Now user is definitely in a course
                   6374: #
1.53      www      6375: 
                   6376: 
                   6377: # Course preferences
                   6378: 
                   6379:    if ($thisallowed=~/C/) {
1.620     albertel 6380:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6381:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6382:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6383: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6384: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6385: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6386: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6387: 			$env{'request.course.id'});
                   6388: 	   }
1.237     www      6389:            return '';
                   6390:        }
                   6391: 
1.620     albertel 6392:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6393: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6394: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6395: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6396: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6397: 			$env{'request.course.id'});
                   6398: 	   }
1.54      www      6399:            return '';
                   6400:        }
1.53      www      6401:    }
                   6402: 
                   6403: # Resource preferences
                   6404: 
                   6405:    if ($thisallowed=~/R/) {
1.620     albertel 6406:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6407:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6408: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6409: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6410: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6411: 	   }
                   6412: 	   return '';
1.54      www      6413:        }
1.53      www      6414:    }
1.30      www      6415: 
1.246     www      6416: # Restricted by state or randomout?
1.30      www      6417: 
1.52      www      6418:    if ($thisallowed=~/X/) {
1.620     albertel 6419:       if ($env{'acc.randomout'}) {
1.579     albertel 6420: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6421:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6422:             return ''; 
                   6423:          }
1.247     www      6424:       }
                   6425:       if (&condval($statecond)) {
1.52      www      6426: 	 return '2';
                   6427:       } else {
                   6428:          return '';
                   6429:       }
                   6430:    }
1.30      www      6431: 
1.766     albertel 6432:     if ($thisallowed eq 'A') {
                   6433: 	return 'A';
1.814     raeburn  6434:     } elsif ($thisallowed eq 'B') {
                   6435:         return 'B';
1.766     albertel 6436:     }
1.52      www      6437:    return 'F';
1.232     www      6438: }
1.1162    raeburn  6439: 
                   6440: sub get_comm_blocks {
                   6441:     my ($cdom,$cnum) = @_;
                   6442:     if ($cdom eq '' || $cnum eq '') {
                   6443:         return unless ($env{'request.course.id'});
                   6444:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6445:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6446:     }
                   6447:     my %commblocks;
                   6448:     my $hashid=$cdom.'_'.$cnum;
                   6449:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6450:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6451:         %commblocks = %{$blocksref};
                   6452:     } else {
                   6453:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6454:         my $cachetime = 600;
                   6455:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6456:     }
                   6457:     return %commblocks;
                   6458: }
                   6459: 
                   6460: sub has_comm_blocking {
                   6461:     my ($priv,$symb,$uri,$blocks) = @_;
                   6462:     return unless ($env{'request.course.id'});
                   6463:     return unless ($priv eq 'bre');
                   6464:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6465:     my %commblocks;
                   6466:     if (ref($blocks) eq 'HASH') {
                   6467:         %commblocks = %{$blocks};
                   6468:     } else {
                   6469:         %commblocks = &get_comm_blocks();
                   6470:     }
                   6471:     return unless (keys(%commblocks) > 0);
                   6472:     if (!$symb) { $symb=&symbread($uri,1); }
                   6473:     my ($map,$resid,undef)=&decode_symb($symb);
                   6474:     my %tocheck = (
                   6475:                     maps      => $map,
                   6476:                     resources => $symb,
                   6477:                   );
                   6478:     my @blockers;
                   6479:     my $now = time;
1.1163    raeburn  6480:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6481:     foreach my $block (keys(%commblocks)) {
                   6482:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6483:             my ($start,$end) = ($1,$2);
                   6484:             if ($start <= $now && $end >= $now) {
                   6485:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6486:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6487:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6488:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6489:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6490:                                     push(@blockers,$block);
                   6491:                                 }
                   6492:                             }
                   6493:                         }
                   6494:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6495:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6496:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6497:                                     push(@blockers,$block);
                   6498:                                 }
                   6499:                             }
                   6500:                         }
                   6501:                     }
                   6502:                 }
                   6503:             }
                   6504:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6505:             my $item = $1;
1.1163    raeburn  6506:             my @to_test;
1.1162    raeburn  6507:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6508:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6509:                     my $check_interval;
                   6510:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6511:                         my @interval;
                   6512:                         my $type = 'map';
                   6513:                         if ($item eq 'course') {
                   6514:                             $type = 'course';
                   6515:                             @interval=&EXT("resource.0.interval");
                   6516:                         } else {
                   6517:                             if ($item =~ /___\d+___/) {
                   6518:                                 $type = 'resource';
                   6519:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6520:                                 if (ref($navmap)) {                        
                   6521:                                     my $res = $navmap->getBySymb($item); 
                   6522:                                     push(@to_test,$res);
                   6523:                                 }
1.1162    raeburn  6524:                             } else {
                   6525:                                 my $mapsymb = &symbread($item,1);
                   6526:                                 if ($mapsymb) {
                   6527:                                     if (ref($navmap)) {
                   6528:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6529:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6530:                                         foreach my $res (@to_test) {
1.1162    raeburn  6531:                                             my $symb = $res->symb();
                   6532:                                             next if ($symb eq $mapsymb);
                   6533:                                             if ($symb ne '') {
                   6534:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6535:                                                 last;
                   6536:                                             }
                   6537:                                         }
                   6538:                                     }
                   6539:                                 }
                   6540:                             }
                   6541:                         }
                   6542:                         if ($interval[0] =~ /\d+/) {
                   6543:                             my $first_access;
                   6544:                             if ($type eq 'resource') {
                   6545:                                 $first_access=&get_first_access($interval[1],$item);
                   6546:                             } elsif ($type eq 'map') {
                   6547:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6548:                             } else {
                   6549:                                 $first_access=&get_first_access($interval[1]);
                   6550:                             }
                   6551:                             if ($first_access) {
                   6552:                                 my $timesup = $first_access+$interval[0];
                   6553:                                 if ($timesup > $now) {
1.1163    raeburn  6554:                                     foreach my $res (@to_test) {
                   6555:                                         if ($res->is_problem()) {
                   6556:                                             if ($res->completable()) {
                   6557:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6558:                                                     push(@blockers,$block);
                   6559:                                                 }
                   6560:                                                 last;
                   6561:                                             }
                   6562:                                         }
1.1162    raeburn  6563:                                     }
                   6564:                                 }
                   6565:                             }
                   6566:                         }
                   6567:                     }
                   6568:                 }
                   6569:             }
                   6570:         }
                   6571:     }
                   6572:     return @blockers;
                   6573: }
                   6574: 
                   6575: sub check_docs_block {
                   6576:     my ($docsblock,$tocheck) =@_;
                   6577:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6578:         return;
                   6579:     }
                   6580:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6581:         if ($tocheck->{'maps'}) {
                   6582:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6583:                 return 1;
                   6584:             }
                   6585:         }
                   6586:     }
                   6587:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6588:         if ($tocheck->{'resources'}) {
                   6589:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6590:                 return 1;
                   6591:             }
                   6592:         }
                   6593:     }
                   6594:     return;
                   6595: }
                   6596: 
1.1133    foxr     6597: #
                   6598: #   Removes the versino from a URI and
                   6599: #   splits it in to its filename and path to the filename.
                   6600: #   Seems like File::Basename could have done this more clearly.
                   6601: #   Parameters:
                   6602: #      $uri   - input URI
                   6603: #   Returns:
                   6604: #     Two element list consisting of 
                   6605: #     $pathname  - the URI up to and excluding the trailing /
                   6606: #     $filename  - The part of the URI following the last /
                   6607: #  NOTE:
                   6608: #    Another realization of this is simply:
                   6609: #    use File::Basename;
                   6610: #    ...
                   6611: #    $uri = shift;
                   6612: #    $filename = basename($uri);
                   6613: #    $path     = dirname($uri);
                   6614: #    return ($filename, $path);
                   6615: #
                   6616: #     The implementation below is probably faster however.
                   6617: #
1.710     albertel 6618: sub split_uri_for_cond {
                   6619:     my $uri=&deversion(&declutter(shift));
                   6620:     my @uriparts=split(/\//,$uri);
                   6621:     my $filename=pop(@uriparts);
                   6622:     my $pathname=join('/',@uriparts);
                   6623:     return ($pathname,$filename);
                   6624: }
1.232     www      6625: # --------------------------------------------------- Is a resource on the map?
                   6626: 
                   6627: sub is_on_map {
1.710     albertel 6628:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6629:     #Trying to find the conditional for the file
1.620     albertel 6630:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6631: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6632:     if ($match) {
1.289     bowersj2 6633: 	return (1,$1);
                   6634:     } else {
1.434     www      6635: 	return (0,0);
1.289     bowersj2 6636:     }
1.12      www      6637: }
                   6638: 
1.427     www      6639: # --------------------------------------------------------- Get symb from alias
                   6640: 
                   6641: sub get_symb_from_alias {
                   6642:     my $symb=shift;
                   6643:     my ($map,$resid,$url)=&decode_symb($symb);
                   6644: # Already is a symb
                   6645:     if ($url) { return $symb; }
                   6646: # Must be an alias
                   6647:     my $aliassymb='';
                   6648:     my %bighash;
1.620     albertel 6649:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6650:                             &GDBM_READER(),0640)) {
                   6651:         my $rid=$bighash{'mapalias_'.$symb};
                   6652: 	if ($rid) {
                   6653: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6654: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6655: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6656: 	}
                   6657:         untie %bighash;
                   6658:     }
                   6659:     return $aliassymb;
                   6660: }
                   6661: 
1.12      www      6662: # ----------------------------------------------------------------- Define Role
                   6663: 
                   6664: sub definerole {
                   6665:   if (allowed('mcr','/')) {
                   6666:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6667:     foreach my $role (split(':',$sysrole)) {
                   6668: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6669:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6670:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6671: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6672:                return "refused:s:$crole&$cqual"; 
                   6673:             }
                   6674:         }
1.191     harris41 6675:     }
1.800     albertel 6676:     foreach my $role (split(':',$domrole)) {
                   6677: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6678:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6679:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6680: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6681:                return "refused:d:$crole&$cqual"; 
                   6682:             }
                   6683:         }
1.191     harris41 6684:     }
1.800     albertel 6685:     foreach my $role (split(':',$courole)) {
                   6686: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6687:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6688:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6689: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6690:                return "refused:c:$crole&$cqual"; 
                   6691:             }
                   6692:         }
1.191     harris41 6693:     }
1.620     albertel 6694:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6695:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6696: 	        "rolesdef_$rolename=".
                   6697:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6698:     return reply($command,$env{'user.home'});
1.12      www      6699:   } else {
                   6700:     return 'refused';
                   6701:   }
1.105     harris41 6702: }
                   6703: 
                   6704: # ---------------- Make a metadata query against the network of library servers
                   6705: 
                   6706: sub metadata_query {
1.244     matthew  6707:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6708:     my %rhash;
1.845     albertel 6709:     my %libserv = &all_library();
1.244     matthew  6710:     my @server_list = (defined($server_array) ? @$server_array
                   6711:                                               : keys(%libserv) );
                   6712:     for my $server (@server_list) {
1.118     harris41 6713: 	unless ($custom or $customshow) {
                   6714: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6715: 	    $rhash{$server}=$reply;
                   6716: 	}
                   6717: 	else {
                   6718: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6719: 			     &escape($custom).':'.&escape($customshow),
                   6720: 			     $server);
                   6721: 	    $rhash{$server}=$reply;
                   6722: 	}
1.112     harris41 6723:     }
1.118     harris41 6724:     return \%rhash;
1.240     www      6725: }
                   6726: 
                   6727: # ----------------------------------------- Send log queries and wait for reply
                   6728: 
                   6729: sub log_query {
                   6730:     my ($uname,$udom,$query,%filters)=@_;
                   6731:     my $uhome=&homeserver($uname,$udom);
                   6732:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6733:     my $uhost=&hostname($uhome);
1.800     albertel 6734:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6735:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6736:                        $uhome);
1.479     albertel 6737:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6738:     return get_query_reply($queryid);
                   6739: }
                   6740: 
1.818     raeburn  6741: # -------------------------- Update MySQL table for portfolio file
                   6742: 
                   6743: sub update_portfolio_table {
1.821     raeburn  6744:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6745:     if ($group ne '') {
                   6746:         $file_name =~s /^\Q$group\E//;
                   6747:     }
1.818     raeburn  6748:     my $homeserver = &homeserver($uname,$udom);
                   6749:     my $queryid=
1.821     raeburn  6750:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6751:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6752:     my $reply = &get_query_reply($queryid);
                   6753:     return $reply;
                   6754: }
                   6755: 
1.899     raeburn  6756: # -------------------------- Update MySQL allusers table
                   6757: 
                   6758: sub update_allusers_table {
                   6759:     my ($uname,$udom,$names) = @_;
                   6760:     my $homeserver = &homeserver($uname,$udom);
                   6761:     my $queryid=
                   6762:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6763:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6764:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6765:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6766:                'generation='.&escape($names->{'generation'}).'%%'.
                   6767:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6768:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6769:     return;
1.899     raeburn  6770: }
                   6771: 
1.508     raeburn  6772: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6773: 
                   6774: sub fetch_enrollment_query {
1.511     raeburn  6775:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6776:     my $homeserver;
1.547     raeburn  6777:     my $maxtries = 1;
1.508     raeburn  6778:     if ($context eq 'automated') {
                   6779:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6780:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6781:     } else {
                   6782:         $homeserver = &homeserver($cnum,$dom);
                   6783:     }
1.838     albertel 6784:     my $host=&hostname($homeserver);
1.506     raeburn  6785:     my $cmd = '';
1.1000    raeburn  6786:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6787:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6788:     }
                   6789:     $cmd =~ s/%%$//;
                   6790:     $cmd = &escape($cmd);
                   6791:     my $query = 'fetchenrollment';
1.620     albertel 6792:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6793:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6794:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6795:         return 'error: '.$queryid;
                   6796:     }
1.506     raeburn  6797:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6798:     my $tries = 1;
                   6799:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6800:         $reply = &get_query_reply($queryid);
                   6801:         $tries ++;
                   6802:     }
1.526     raeburn  6803:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6804:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6805:     } else {
1.901     albertel 6806:         my @responses = split(/:/,$reply);
1.515     raeburn  6807:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6808:             foreach my $line (@responses) {
                   6809:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6810:                 $$replyref{$key} = $value;
                   6811:             }
                   6812:         } else {
1.1117    foxr     6813:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6814:             foreach my $line (@responses) {
                   6815:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6816:                 $$replyref{$key} = $value;
                   6817:                 if ($value > 0) {
1.800     albertel 6818:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6819:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6820:                         my $destname = $pathname.'/'.$filename;
                   6821:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6822:                         if ($xml_classlist =~ /^error/) {
                   6823:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6824:                         } else {
1.506     raeburn  6825:                             if ( open(FILE,">$destname") ) {
                   6826:                                 print FILE &unescape($xml_classlist);
                   6827:                                 close(FILE);
1.526     raeburn  6828:                             } else {
                   6829:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6830:                             }
                   6831:                         }
                   6832:                     }
                   6833:                 }
                   6834:             }
                   6835:         }
                   6836:         return 'ok';
                   6837:     }
                   6838:     return 'error';
                   6839: }
                   6840: 
1.242     www      6841: sub get_query_reply {
                   6842:     my $queryid=shift;
1.1117    foxr     6843:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6844:     my $reply='';
                   6845:     for (1..100) {
                   6846: 	sleep 2;
                   6847:         if (-e $replyfile.'.end') {
1.448     albertel 6848: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6849: 		$reply = join('',<$fh>);
                   6850: 		close($fh);
1.240     www      6851: 	   } else { return 'error: reply_file_error'; }
1.242     www      6852:            return &unescape($reply);
                   6853: 	}
1.240     www      6854:     }
1.242     www      6855:     return 'timeout:'.$queryid;
1.240     www      6856: }
                   6857: 
                   6858: sub courselog_query {
1.241     www      6859: #
                   6860: # possible filters:
                   6861: # url: url or symb
                   6862: # username
                   6863: # domain
                   6864: # action: view, submit, grade
                   6865: # start: timestamp
                   6866: # end: timestamp
                   6867: #
1.240     www      6868:     my (%filters)=@_;
1.620     albertel 6869:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6870:     if ($filters{'url'}) {
                   6871: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6872:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6873:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6874:     }
1.620     albertel 6875:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6876:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6877:     return &log_query($cname,$cdom,'courselog',%filters);
                   6878: }
                   6879: 
                   6880: sub userlog_query {
1.858     raeburn  6881: #
                   6882: # possible filters:
                   6883: # action: log check role
                   6884: # start: timestamp
                   6885: # end: timestamp
                   6886: #
1.240     www      6887:     my ($uname,$udom,%filters)=@_;
                   6888:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6889: }
                   6890: 
1.506     raeburn  6891: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6892: 
                   6893: sub auto_run {
1.508     raeburn  6894:     my ($cnum,$cdom) = @_;
1.876     raeburn  6895:     my $response = 0;
                   6896:     my $settings;
                   6897:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6898:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6899:         $settings = $domconfig{'autoenroll'};
                   6900:         if ($settings->{'run'} eq '1') {
                   6901:             $response = 1;
                   6902:         }
                   6903:     } else {
1.934     raeburn  6904:         my $homeserver;
                   6905:         if (&is_course($cdom,$cnum)) {
                   6906:             $homeserver = &homeserver($cnum,$cdom);
                   6907:         } else {
                   6908:             $homeserver = &domain($cdom,'primary');
                   6909:         }
                   6910:         if ($homeserver ne 'no_host') {
                   6911:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6912:         }
1.876     raeburn  6913:     }
1.506     raeburn  6914:     return $response;
                   6915: }
1.776     albertel 6916: 
1.506     raeburn  6917: sub auto_get_sections {
1.508     raeburn  6918:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6919:     my $homeserver;
                   6920:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6921:         $homeserver = &homeserver($cnum,$cdom);
                   6922:     }
                   6923:     if (!defined($homeserver)) { 
                   6924:         if ($cdom =~ /^$match_domain$/) {
                   6925:             $homeserver = &domain($cdom,'primary');
                   6926:         }
                   6927:     }
                   6928:     my @secs;
                   6929:     if (defined($homeserver)) {
                   6930:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6931:         unless ($response eq 'refused') {
                   6932:             @secs = split(/:/,$response);
                   6933:         }
1.506     raeburn  6934:     }
                   6935:     return @secs;
                   6936: }
1.776     albertel 6937: 
1.506     raeburn  6938: sub auto_new_course {
1.1099    raeburn  6939:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6940:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6941:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6942:     return $response;
                   6943: }
1.776     albertel 6944: 
1.506     raeburn  6945: sub auto_validate_courseID {
1.508     raeburn  6946:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6947:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6948:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6949:     return $response;
                   6950: }
1.776     albertel 6951: 
1.1007    raeburn  6952: sub auto_validate_instcode {
1.1020    raeburn  6953:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6954:     my ($homeserver,$response);
                   6955:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6956:         $homeserver = &homeserver($cnum,$cdom);
                   6957:     }
                   6958:     if (!defined($homeserver)) {
                   6959:         if ($cdom =~ /^$match_domain$/) {
                   6960:             $homeserver = &domain($cdom,'primary');
                   6961:         }
                   6962:     }
1.1065    raeburn  6963:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6964:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6965:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6966:     return ($outcome,$description);
1.1007    raeburn  6967: }
                   6968: 
1.506     raeburn  6969: sub auto_create_password {
1.873     raeburn  6970:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6971:     my ($homeserver,$response);
1.506     raeburn  6972:     my $create_passwd = 0;
                   6973:     my $authchk = '';
1.873     raeburn  6974:     if ($udom =~ /^$match_domain$/) {
                   6975:         $homeserver = &domain($udom,'primary');
                   6976:     }
                   6977:     if ($homeserver eq '') {
                   6978:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6979:             $homeserver = &homeserver($cnum,$cdom);
                   6980:         }
                   6981:     }
                   6982:     if ($homeserver eq '') {
                   6983:         $authchk = 'nodomain';
1.506     raeburn  6984:     } else {
1.873     raeburn  6985:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6986:         if ($response eq 'refused') {
                   6987:             $authchk = 'refused';
                   6988:         } else {
1.901     albertel 6989:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6990:         }
1.506     raeburn  6991:     }
                   6992:     return ($authparam,$create_passwd,$authchk);
                   6993: }
                   6994: 
1.706     raeburn  6995: sub auto_photo_permission {
                   6996:     my ($cnum,$cdom,$students) = @_;
                   6997:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6998:     my ($outcome,$perm_reqd,$conditions) = 
                   6999: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 7000:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7001: 	return (undef,undef);
                   7002:     }
1.706     raeburn  7003:     return ($outcome,$perm_reqd,$conditions);
                   7004: }
                   7005: 
                   7006: sub auto_checkphotos {
                   7007:     my ($uname,$udom,$pid) = @_;
                   7008:     my $homeserver = &homeserver($uname,$udom);
                   7009:     my ($result,$resulttype);
                   7010:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 7011: 				   &escape($uname).':'.&escape($pid),
                   7012: 				   $homeserver));
1.709     albertel 7013:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7014: 	return (undef,undef);
                   7015:     }
1.706     raeburn  7016:     if ($outcome) {
                   7017:         ($result,$resulttype) = split(/:/,$outcome);
                   7018:     } 
                   7019:     return ($result,$resulttype);
                   7020: }
                   7021: 
                   7022: sub auto_photochoice {
                   7023:     my ($cnum,$cdom) = @_;
                   7024:     my $homeserver = &homeserver($cnum,$cdom);
                   7025:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 7026: 						       &escape($cdom),
                   7027: 						       $homeserver)));
1.709     albertel 7028:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   7029: 	return (undef,undef);
                   7030:     }
1.706     raeburn  7031:     return ($update,$comment);
                   7032: }
                   7033: 
                   7034: sub auto_photoupdate {
                   7035:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   7036:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 7037:     my $host=&hostname($homeserver);
1.706     raeburn  7038:     my $cmd = '';
                   7039:     my $maxtries = 1;
1.800     albertel 7040:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   7041:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  7042:     }
                   7043:     $cmd =~ s/%%$//;
                   7044:     $cmd = &escape($cmd);
                   7045:     my $query = 'institutionalphotos';
                   7046:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7047:     unless ($queryid=~/^\Q$host\E\_/) {
                   7048:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7049:         return 'error: '.$queryid;
                   7050:     }
                   7051:     my $reply = &get_query_reply($queryid);
                   7052:     my $tries = 1;
                   7053:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7054:         $reply = &get_query_reply($queryid);
                   7055:         $tries ++;
                   7056:     }
                   7057:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7058:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7059:     } else {
                   7060:         my @responses = split(/:/,$reply);
                   7061:         my $outcome = shift(@responses); 
                   7062:         foreach my $item (@responses) {
                   7063:             my ($key,$value) = split(/=/,$item);
                   7064:             $$photo{$key} = $value;
                   7065:         }
                   7066:         return $outcome;
                   7067:     }
                   7068:     return 'error';
                   7069: }
                   7070: 
1.521     raeburn  7071: sub auto_instcode_format {
1.793     albertel 7072:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7073: 	$cat_order) = @_;
1.521     raeburn  7074:     my $courses = '';
1.772     raeburn  7075:     my @homeservers;
1.521     raeburn  7076:     if ($caller eq 'global') {
1.841     albertel 7077: 	my %servers = &get_servers($codedom,'library');
                   7078: 	foreach my $tryserver (keys(%servers)) {
                   7079: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7080: 		push(@homeservers,$tryserver);
                   7081: 	    }
1.584     raeburn  7082:         }
1.1022    raeburn  7083:     } elsif ($caller eq 'requests') {
                   7084:         if ($codedom =~ /^$match_domain$/) {
                   7085:             my $chome = &domain($codedom,'primary');
                   7086:             unless ($chome eq 'no_host') {
                   7087:                 push(@homeservers,$chome);
                   7088:             }
                   7089:         }
1.521     raeburn  7090:     } else {
1.772     raeburn  7091:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7092:     }
1.793     albertel 7093:     foreach my $code (keys(%{$instcodes})) {
                   7094:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7095:     }
                   7096:     chop($courses);
1.772     raeburn  7097:     my $ok_response = 0;
                   7098:     my $response;
                   7099:     while (@homeservers > 0 && $ok_response == 0) {
                   7100:         my $server = shift(@homeservers); 
                   7101:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7102:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7103:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7104: 		split(/:/,$response);
1.772     raeburn  7105:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7106:             push(@{$codetitles},&str2array($codetitles_str));
                   7107:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7108:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7109:             $ok_response = 1;
                   7110:         }
                   7111:     }
                   7112:     if ($ok_response) {
1.521     raeburn  7113:         return 'ok';
1.772     raeburn  7114:     } else {
                   7115:         return $response;
1.521     raeburn  7116:     }
                   7117: }
                   7118: 
1.792     raeburn  7119: sub auto_instcode_defaults {
                   7120:     my ($domain,$returnhash,$code_order) = @_;
                   7121:     my @homeservers;
1.841     albertel 7122: 
                   7123:     my %servers = &get_servers($domain,'library');
                   7124:     foreach my $tryserver (keys(%servers)) {
                   7125: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7126: 	    push(@homeservers,$tryserver);
                   7127: 	}
1.792     raeburn  7128:     }
1.841     albertel 7129: 
1.792     raeburn  7130:     my $response;
1.841     albertel 7131:     foreach my $server (@homeservers) {
1.792     raeburn  7132:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7133:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7134: 	
                   7135: 	foreach my $pair (split(/\&/,$response)) {
                   7136: 	    my ($name,$value)=split(/\=/,$pair);
                   7137: 	    if ($name eq 'code_order') {
                   7138: 		@{$code_order} = split(/\&/,&unescape($value));
                   7139: 	    } else {
                   7140: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7141: 	    }
                   7142: 	}
                   7143: 	return 'ok';
1.792     raeburn  7144:     }
1.841     albertel 7145: 
                   7146:     return $response;
1.1003    raeburn  7147: }
                   7148: 
                   7149: sub auto_possible_instcodes {
1.1007    raeburn  7150:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7151:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7152:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7153:         return;
                   7154:     }
1.1003    raeburn  7155:     my (@homeservers,$uhome);
                   7156:     if (defined(&domain($domain,'primary'))) {
                   7157:         $uhome=&domain($domain,'primary');
                   7158:         push(@homeservers,&domain($domain,'primary'));
                   7159:     } else {
                   7160:         my %servers = &get_servers($domain,'library');
                   7161:         foreach my $tryserver (keys(%servers)) {
                   7162:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7163:                 push(@homeservers,$tryserver);
                   7164:             }
                   7165:         }
                   7166:     }
                   7167:     my $response;
                   7168:     foreach my $server (@homeservers) {
                   7169:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7170:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7171:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7172:             split(':',$response);
                   7173:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7174:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7175:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7176:             my ($name,$value)=split('=',$item);
                   7177:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7178:         }
                   7179:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7180:             my ($name,$value)=split('=',$item);
                   7181:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7182:         }
                   7183:         return 'ok';
                   7184:     }
                   7185:     return $response;
                   7186: }
1.792     raeburn  7187: 
1.1010    raeburn  7188: sub auto_courserequest_checks {
                   7189:     my ($dom) = @_;
1.1020    raeburn  7190:     my ($homeserver,%validations);
                   7191:     if ($dom =~ /^$match_domain$/) {
                   7192:         $homeserver = &domain($dom,'primary');
                   7193:     }
                   7194:     unless ($homeserver eq 'no_host') {
                   7195:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7196:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7197:             my @items = split(/&/,$response);
                   7198:             foreach my $item (@items) {
                   7199:                 my ($key,$value) = split('=',$item);
                   7200:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7201:             }
                   7202:         }
                   7203:     }
1.1010    raeburn  7204:     return %validations; 
                   7205: }
                   7206: 
1.1020    raeburn  7207: sub auto_courserequest_validation {
                   7208:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7209:     my ($homeserver,$response);
                   7210:     if ($dom =~ /^$match_domain$/) {
                   7211:         $homeserver = &domain($dom,'primary');
                   7212:     }
                   7213:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7214:           
1.1020    raeburn  7215:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7216:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7217:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7218:                                     $homeserver));
                   7219:     }
                   7220:     return $response;
                   7221: }
                   7222: 
1.777     albertel 7223: sub auto_validate_class_sec {
1.918     raeburn  7224:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7225:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7226:     my $ownerlist;
                   7227:     if (ref($owners) eq 'ARRAY') {
                   7228:         $ownerlist = join(',',@{$owners});
                   7229:     } else {
                   7230:         $ownerlist = $owners;
                   7231:     }
1.773     raeburn  7232:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7233:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7234:     return $response;
                   7235: }
                   7236: 
1.679     raeburn  7237: # ------------------------------------------------------- Course Group routines
                   7238: 
                   7239: sub get_coursegroups {
1.809     raeburn  7240:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7241:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7242: }
                   7243: 
1.679     raeburn  7244: sub modify_coursegroup {
                   7245:     my ($cdom,$cnum,$groupsettings) = @_;
                   7246:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7247: }
                   7248: 
1.809     raeburn  7249: sub toggle_coursegroup_status {
                   7250:     my ($cdom,$cnum,$group,$action) = @_;
                   7251:     my ($from_namespace,$to_namespace);
                   7252:     if ($action eq 'delete') {
                   7253:         $from_namespace = 'coursegroups';
                   7254:         $to_namespace = 'deleted_groups';
                   7255:     } else {
                   7256:         $from_namespace = 'deleted_groups';
                   7257:         $to_namespace = 'coursegroups';
                   7258:     }
                   7259:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7260:     if (my $tmp = &error(%curr_group)) {
                   7261:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7262:         return ('read error',$tmp);
                   7263:     } else {
                   7264:         my %savedsettings = %curr_group; 
1.809     raeburn  7265:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7266:         my $deloutcome;
                   7267:         if ($result eq 'ok') {
1.809     raeburn  7268:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7269:         } else {
                   7270:             return ('write error',$result);
                   7271:         }
                   7272:         if ($deloutcome eq 'ok') {
                   7273:             return 'ok';
                   7274:         } else {
                   7275:             return ('delete error',$deloutcome);
                   7276:         }
                   7277:     }
                   7278: }
                   7279: 
1.679     raeburn  7280: sub modify_group_roles {
1.957     raeburn  7281:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7282:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7283:     my $role = 'gr/'.&escape($userprivs);
                   7284:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7285:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7286:     if ($result eq 'ok') {
                   7287:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7288:     }
1.679     raeburn  7289:     return $result;
                   7290: }
                   7291: 
                   7292: sub modify_coursegroup_membership {
                   7293:     my ($cdom,$cnum,$membership) = @_;
                   7294:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7295:     return $result;
                   7296: }
                   7297: 
1.682     raeburn  7298: sub get_active_groups {
                   7299:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7300:     my $now = time;
                   7301:     my %groups = ();
                   7302:     foreach my $key (keys(%env)) {
1.811     albertel 7303:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7304:             my ($start,$end) = split(/\./,$env{$key});
                   7305:             if (($end!=0) && ($end<$now)) { next; }
                   7306:             if (($start!=0) && ($start>$now)) { next; }
                   7307:             if ($1 eq $cdom && $2 eq $cnum) {
                   7308:                 $groups{$3} = $env{$key} ;
                   7309:             }
                   7310:         }
                   7311:     }
                   7312:     return %groups;
                   7313: }
                   7314: 
1.683     raeburn  7315: sub get_group_membership {
                   7316:     my ($cdom,$cnum,$group) = @_;
                   7317:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7318: }
                   7319: 
                   7320: sub get_users_groups {
                   7321:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7322:     my @usersgroups;
1.683     raeburn  7323:     my $cachetime=1800;
                   7324: 
                   7325:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7326:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7327:     if (defined($cached)) {
1.734     albertel 7328:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7329:     } else {  
                   7330:         $grouplist = '';
1.816     raeburn  7331:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7332:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7333:         my $access_end = $env{'course.'.$courseid.
                   7334:                               '.default_enrollment_end_date'};
                   7335:         my $now = time;
                   7336:         foreach my $key (keys(%roleshash)) {
                   7337:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7338:                 my $group = $1;
                   7339:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7340:                     my $start = $2;
                   7341:                     my $end = $1;
                   7342:                     if ($start == -1) { next; } # deleted from group
                   7343:                     if (($start!=0) && ($start>$now)) { next; }
                   7344:                     if (($end!=0) && ($end<$now)) {
                   7345:                         if ($access_end && $access_end < $now) {
                   7346:                             if ($access_end - $end < 86400) {
                   7347:                                 push(@usersgroups,$group);
1.733     raeburn  7348:                             }
                   7349:                         }
1.817     raeburn  7350:                         next;
1.733     raeburn  7351:                     }
1.817     raeburn  7352:                     push(@usersgroups,$group);
1.683     raeburn  7353:                 }
                   7354:             }
                   7355:         }
1.817     raeburn  7356:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7357:         $grouplist = join(':',@usersgroups);
                   7358:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7359:     }
1.733     raeburn  7360:     return @usersgroups;
1.683     raeburn  7361: }
                   7362: 
                   7363: sub devalidate_getgroups_cache {
                   7364:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7365:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7366: 
1.683     raeburn  7367:     my $hashid="$udom:$uname:$courseid";
                   7368:     &devalidate_cache_new('getgroups',$hashid);
                   7369: }
                   7370: 
1.12      www      7371: # ------------------------------------------------------------------ Plain Text
                   7372: 
                   7373: sub plaintext {
1.988     raeburn  7374:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7375:     if ($short =~ m{^cr/}) {
1.758     albertel 7376: 	return (split('/',$short))[-1];
                   7377:     }
1.742     raeburn  7378:     if (!defined($cid)) {
                   7379:         $cid = $env{'request.course.id'};
                   7380:     }
                   7381:     my %rolenames = (
1.1008    raeburn  7382:                       Course    => 'std',
                   7383:                       Community => 'alt1',
1.742     raeburn  7384:                     );
1.1037    raeburn  7385:     if ($cid ne '') {
                   7386:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7387:             unless ($forcedefault) {
                   7388:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7389:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7390:                 return &Apache::lonlocal::mt($roletext);
                   7391:             }
                   7392:         }
                   7393:     }
                   7394:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7395:         (defined($rolenames{$type})) && 
                   7396:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7397:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7398:     } elsif ($cid ne '') {
                   7399:         my $crstype = $env{'course.'.$cid.'.type'};
                   7400:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7401:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7402:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7403:         }
1.742     raeburn  7404:     }
1.1037    raeburn  7405:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7406: }
                   7407: 
                   7408: # ----------------------------------------------------------------- Assign Role
                   7409: 
                   7410: sub assignrole {
1.957     raeburn  7411:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7412:         $context)=@_;
1.21      www      7413:     my $mrole;
                   7414:     if ($role =~ /^cr\//) {
1.393     www      7415:         my $cwosec=$url;
1.811     albertel 7416:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7417: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7418:            my $refused = 1;
                   7419:            if ($context eq 'requestcourses') {
                   7420:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7421:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7422:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7423:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7424:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7425:                            if ($crsenv{'internal.courseowner'} eq
                   7426:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7427:                                $refused = '';
                   7428:                            }
                   7429:                        }
                   7430:                    }
                   7431:                }
                   7432:            }
                   7433:            if ($refused) {
                   7434:                &logthis('Refused custom assignrole: '.
                   7435:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7436:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7437:                return 'refused';
                   7438:            }
1.104     www      7439:         }
1.21      www      7440:         $mrole='cr';
1.678     raeburn  7441:     } elsif ($role =~ /^gr\//) {
                   7442:         my $cwogrp=$url;
1.811     albertel 7443:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7444:         unless (&allowed('mdg',$cwogrp)) {
                   7445:             &logthis('Refused group assignrole: '.
                   7446:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7447:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7448:             return 'refused';
                   7449:         }
                   7450:         $mrole='gr';
1.21      www      7451:     } else {
1.82      www      7452:         my $cwosec=$url;
1.811     albertel 7453:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7454:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7455:             my $refused;
                   7456:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7457:                 if (!(&allowed('c'.$role,$url))) {
                   7458:                     $refused = 1;
                   7459:                 }
                   7460:             } else {
                   7461:                 $refused = 1;
                   7462:             }
1.947     raeburn  7463:             if ($refused) {
1.1045    raeburn  7464:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7465:                 if (!$selfenroll && $context eq 'course') {
                   7466:                     my %crsenv;
                   7467:                     if ($role eq 'cc' || $role eq 'co') {
                   7468:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7469:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7470:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7471:                                 if ($crsenv{'internal.courseowner'} eq 
                   7472:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7473:                                     $refused = '';
                   7474:                                 }
                   7475:                             }
                   7476:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7477:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7478:                                 if ($crsenv{'internal.courseowner'} eq 
                   7479:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7480:                                     $refused = '';
                   7481:                                 }
                   7482:                             }
                   7483:                         }
                   7484:                     }
                   7485:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7486:                     $refused = '';
1.1017    raeburn  7487:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7488:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7489:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7490:                         my $wrongcc;
                   7491:                         if ($cnum =~ /^$match_community$/) {
                   7492:                             $wrongcc = 1 if ($role eq 'cc');
                   7493:                         } else {
                   7494:                             $wrongcc = 1 if ($role eq 'co');
                   7495:                         }
                   7496:                         unless ($wrongcc) {
                   7497:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7498:                             if ($crsenv{'internal.courseowner'} eq 
                   7499:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7500:                                 $refused = '';
                   7501:                             }
1.1017    raeburn  7502:                         }
                   7503:                     }
                   7504:                 }
                   7505:                 if ($refused) {
1.947     raeburn  7506:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7507:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7508: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7509:                     return 'refused';
                   7510:                 }
1.932     raeburn  7511:             }
1.1131    raeburn  7512:         } elsif ($role eq 'au') {
                   7513:             if ($url ne '/'.$udom.'/') {
                   7514:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7515:                          ' to assign author role for '.$uname.':'.$udom.
                   7516:                          ' in domain: '.$url.' refused (wrong domain).');
                   7517:                 return 'refused';
                   7518:             }
1.104     www      7519:         }
1.21      www      7520:         $mrole=$role;
                   7521:     }
1.620     albertel 7522:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7523:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7524:     if ($end) { $command.='_'.$end; }
1.21      www      7525:     if ($start) {
                   7526: 	if ($end) { 
1.81      www      7527:            $command.='_'.$start; 
1.21      www      7528:         } else {
1.81      www      7529:            $command.='_0_'.$start;
1.21      www      7530:         }
                   7531:     }
1.739     raeburn  7532:     my $origstart = $start;
                   7533:     my $origend = $end;
1.957     raeburn  7534:     my $delflag;
1.357     www      7535: # actually delete
                   7536:     if ($deleteflag) {
1.373     www      7537: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7538: # modify command to delete the role
1.620     albertel 7539:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7540:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7541: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7542: # set start and finish to negative values for userrolelog
                   7543:            $start=-1;
                   7544:            $end=-1;
1.957     raeburn  7545:            $delflag = 1;
1.357     www      7546:         }
                   7547:     }
                   7548: # send command
1.349     www      7549:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7550: # log new user role if status is ok
1.349     www      7551:     if ($answer eq 'ok') {
1.663     raeburn  7552: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7553: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7554:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7555:         unless ($role =~ /^gr/) {
                   7556:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7557:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7558:         }
1.1053    raeburn  7559:         if ($role eq 'cc') {
                   7560:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7561:         }
1.349     www      7562:     }
                   7563:     return $answer;
1.169     harris41 7564: }
                   7565: 
1.1053    raeburn  7566: sub autoupdate_coowners {
                   7567:     my ($url,$end,$start,$uname,$udom) = @_;
                   7568:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7569:     if (($cdom ne '') && ($cnum ne '')) {
                   7570:         my $now = time;
                   7571:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7572:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7573:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7574:             my $instcode = $coursehash{'internal.coursecode'};
                   7575:             if ($instcode ne '') {
1.1056    raeburn  7576:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7577:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7578:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7579:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7580:                         if ($result eq 'valid') {
                   7581:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7582:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7583:                                     push(@newcoowners,$coowner);
                   7584:                                 }
                   7585:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7586:                                     push(@newcoowners,$uname.':'.$udom);
                   7587:                                 }
                   7588:                                 @newcoowners = sort(@newcoowners);
                   7589:                             } else {
                   7590:                                 push(@newcoowners,$uname.':'.$udom);
                   7591:                             }
                   7592:                         } else {
                   7593:                             if ($coursehash{'internal.co-owners'}) {
                   7594:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7595:                                     unless ($coowner eq $uname.':'.$udom) {
                   7596:                                         push(@newcoowners,$coowner);
                   7597:                                     }
                   7598:                                 }
                   7599:                                 unless (@newcoowners > 0) {
                   7600:                                     $delcoowners = 1;
                   7601:                                     $coowners = '';
                   7602:                                 }
                   7603:                             }
                   7604:                         }
                   7605:                         if (@newcoowners || $delcoowners) {
                   7606:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7607:                                             $delcoowners,@newcoowners);
                   7608:                         }
                   7609:                     }
                   7610:                 }
                   7611:             }
                   7612:         }
                   7613:     }
                   7614: }
                   7615: 
                   7616: sub store_coowners {
                   7617:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7618:     my $cid = $cdom.'_'.$cnum;
                   7619:     my ($coowners,$delresult,$putresult);
                   7620:     if (@newcoowners) {
                   7621:         $coowners = join(',',@newcoowners);
                   7622:         my %coownershash = (
                   7623:                             'internal.co-owners' => $coowners,
                   7624:                            );
                   7625:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7626:         if ($putresult eq 'ok') {
                   7627:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7628:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7629:             }
                   7630:         }
                   7631:     }
                   7632:     if ($delcoowners) {
                   7633:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7634:         if ($delresult eq 'ok') {
                   7635:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7636:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7637:             }
                   7638:         }
                   7639:     }
                   7640:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7641:         my %crsinfo =
                   7642:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7643:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7644:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7645:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7646:         }
                   7647:     }
                   7648: }
                   7649: 
1.169     harris41 7650: # -------------------------------------------------- Modify user authentication
1.197     www      7651: # Overrides without validation
                   7652: 
1.169     harris41 7653: sub modifyuserauth {
                   7654:     my ($udom,$uname,$umode,$upass)=@_;
                   7655:     my $uhome=&homeserver($uname,$udom);
1.197     www      7656:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7657:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7658:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7659:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7660:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7661: 		     &escape($upass),$uhome);
1.620     albertel 7662:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7663:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7664:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7665:     &log($udom,,$uname,$uhome,
1.620     albertel 7666:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7667:                                      $env{'user.name'}.', '.$umode.
1.197     www      7668:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7669:     unless ($reply eq 'ok') {
1.197     www      7670:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7671: 	return 'error: '.$reply;
                   7672:     }   
1.170     harris41 7673:     return 'ok';
1.80      www      7674: }
                   7675: 
1.81      www      7676: # --------------------------------------------------------------- Modify a user
1.80      www      7677: 
1.81      www      7678: sub modifyuser {
1.206     matthew  7679:     my ($udom,    $uname, $uid,
                   7680:         $umode,   $upass, $first,
                   7681:         $middle,  $last,  $gene,
1.1058    raeburn  7682:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7683:     $udom= &LONCAPA::clean_domain($udom);
                   7684:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7685:     my $showcandelete = 'none';
                   7686:     if (ref($candelete) eq 'ARRAY') {
                   7687:         if (@{$candelete} > 0) {
                   7688:             $showcandelete = join(', ',@{$candelete});
                   7689:         }
                   7690:     }
1.81      www      7691:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7692:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7693: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7694:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7695:                                      ' desiredhome not specified'). 
1.620     albertel 7696:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7697:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7698:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7699:     my $newuser;
                   7700:     if ($uhome eq 'no_host') {
                   7701:         $newuser = 1;
                   7702:     }
1.80      www      7703: # ----------------------------------------------------------------- Create User
1.406     albertel 7704:     if (($uhome eq 'no_host') && 
                   7705: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7706:         my $unhome='';
1.844     albertel 7707:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7708:             $unhome = $desiredhome;
1.620     albertel 7709: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7710: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7711:         } else { # load balancing routine for determining $unhome
1.81      www      7712:             my $loadm=10000000;
1.841     albertel 7713: 	    my %servers = &get_servers($udom,'library');
                   7714: 	    foreach my $tryserver (keys(%servers)) {
                   7715: 		my $answer=reply('load',$tryserver);
                   7716: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7717: 		    $loadm=$answer;
                   7718: 		    $unhome=$tryserver;
                   7719: 		}
1.80      www      7720: 	    }
                   7721:         }
                   7722:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7723: 	    return 'error: unable to find a home server for '.$uname.
                   7724:                    ' in domain '.$udom;
1.80      www      7725:         }
                   7726:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7727:                          &escape($upass),$unhome);
                   7728: 	unless ($reply eq 'ok') {
                   7729:             return 'error: '.$reply;
                   7730:         }   
1.230     stredwic 7731:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7732:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7733: 	    return 'error: unable verify users home machine.';
1.80      www      7734:         }
1.209     matthew  7735:     }   # End of creation of new user
1.80      www      7736: # ---------------------------------------------------------------------- Add ID
                   7737:     if ($uid) {
                   7738:        $uid=~tr/A-Z/a-z/;
                   7739:        my %uidhash=&idrget($udom,$uname);
1.196     www      7740:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7741:          && (!$forceid)) {
1.80      www      7742: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7743: 	      return 'error: user id "'.$uid.'" does not match '.
                   7744:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7745:           }
                   7746:        } else {
                   7747: 	  &idput($udom,($uname => $uid));
                   7748:        }
                   7749:     }
                   7750: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7751:     my @tmp=&get('environment',
1.899     raeburn  7752: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7753:                     'permanentemail','inststatus'],
1.134     albertel 7754: 		   $udom,$uname);
1.1075    raeburn  7755:     my (%names,%oldnames);
1.313     matthew  7756:     if ($tmp[0] =~ m/^error:.*/) { 
                   7757:         %names=(); 
                   7758:     } else {
                   7759:         %names = @tmp;
1.1075    raeburn  7760:         %oldnames = %names;
1.313     matthew  7761:     }
1.388     www      7762: #
1.1058    raeburn  7763: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7764: # of users did not contain them), do not overwrite existing values
                   7765: # unless field is in $candelete array ref.  
                   7766: #
                   7767: 
                   7768:     my @fields = ('firstname','middlename','lastname','generation',
                   7769:                   'permanentemail','id');
                   7770:     my %newvalues;
                   7771:     if (ref($candelete) eq 'ARRAY') {
                   7772:         foreach my $field (@fields) {
                   7773:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7774:                 if ($field eq 'firstname') {
                   7775:                     $names{$field} = $first;
                   7776:                 } elsif ($field eq 'middlename') {
                   7777:                     $names{$field} = $middle;
                   7778:                 } elsif ($field eq 'lastname') {
                   7779:                     $names{$field} = $last;
                   7780:                 } elsif ($field eq 'generation') { 
                   7781:                     $names{$field} = $gene;
                   7782:                 } elsif ($field eq 'permanentemail') {
                   7783:                     $names{$field} = $email;
                   7784:                 } elsif ($field eq 'id') {
                   7785:                     $names{$field}  = $uid;
                   7786:                 }
                   7787:             }
                   7788:         }
                   7789:     }
1.388     www      7790:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7791:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7792:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7793:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7794:     if ($email) {
                   7795:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7796:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7797:     }
1.899     raeburn  7798:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7799:     if (defined($inststatus)) {
                   7800:         $names{'inststatus'} = '';
                   7801:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7802:         if (ref($usertypes) eq 'HASH') {
                   7803:             my @okstatuses; 
                   7804:             foreach my $item (split(/:/,$inststatus)) {
                   7805:                 if (defined($usertypes->{$item})) {
                   7806:                     push(@okstatuses,$item);  
                   7807:                 }
                   7808:             }
                   7809:             if (@okstatuses) {
                   7810:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7811:             }
                   7812:         }
                   7813:     }
1.1075    raeburn  7814:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7815:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7816:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7817:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7818:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7819:     } else {
                   7820:         $logmsg .= ' during self creation';
                   7821:     }
1.1075    raeburn  7822:     my $changed;
                   7823:     if ($newuser) {
                   7824:         $changed = 1;
                   7825:     } else {
                   7826:         foreach my $field (@fields) {
                   7827:             if ($names{$field} ne $oldnames{$field}) {
                   7828:                 $changed = 1;
                   7829:                 last;
                   7830:             }
                   7831:         }
                   7832:     }
                   7833:     unless ($changed) {
                   7834:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7835:         &logthis($logmsg);
                   7836:         return 'ok';
                   7837:     }
                   7838:     my $reply = &put('environment', \%names, $udom,$uname);
                   7839:     if ($reply ne 'ok') { 
                   7840:         return 'error: '.$reply;
                   7841:     }
1.1087    raeburn  7842:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7843:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7844:     }
1.1075    raeburn  7845:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7846:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7847:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7848:     &logthis($logmsg);
1.134     albertel 7849:     return 'ok';
1.80      www      7850: }
                   7851: 
1.81      www      7852: # -------------------------------------------------------------- Modify student
1.80      www      7853: 
1.81      www      7854: sub modifystudent {
                   7855:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7856:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7857:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7858:     if (!$cid) {
1.620     albertel 7859: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7860: 	    return 'not_in_class';
                   7861: 	}
1.80      www      7862:     }
                   7863: # --------------------------------------------------------------- Make the user
1.81      www      7864:     my $reply=&modifyuser
1.209     matthew  7865: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7866:          $desiredhome,$email,$inststatus);
1.80      www      7867:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7868:     # This will cause &modify_student_enrollment to get the uid from the
                   7869:     # students environment
                   7870:     $uid = undef if (!$forceid);
1.455     albertel 7871:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7872: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7873:     return $reply;
                   7874: }
                   7875: 
                   7876: sub modify_student_enrollment {
1.957     raeburn  7877:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7878:     my ($cdom,$cnum,$chome);
                   7879:     if (!$cid) {
1.620     albertel 7880: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7881: 	    return 'not_in_class';
                   7882: 	}
1.620     albertel 7883: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7884: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7885:     } else {
                   7886: 	($cdom,$cnum)=split(/_/,$cid);
                   7887:     }
1.620     albertel 7888:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7889:     if (!$chome) {
1.457     raeburn  7890: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7891:     }
1.455     albertel 7892:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7893:     # Make sure the user exists
1.81      www      7894:     my $uhome=&homeserver($uname,$udom);
                   7895:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7896: 	return 'error: no such user';
                   7897:     }
1.297     matthew  7898:     # Get student data if we were not given enough information
                   7899:     if (!defined($first)  || $first  eq '' || 
                   7900:         !defined($last)   || $last   eq '' || 
                   7901:         !defined($uid)    || $uid    eq '' || 
                   7902:         !defined($middle) || $middle eq '' || 
                   7903:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7904:         # They did not supply us with enough data to enroll the student, so
                   7905:         # we need to pick up more information.
1.297     matthew  7906:         my %tmp = &get('environment',
1.294     matthew  7907:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7908:                        ,$udom,$uname);
                   7909: 
1.800     albertel 7910:         #foreach my $key (keys(%tmp)) {
                   7911:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7912:         #}
1.294     matthew  7913:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7914:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7915:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7916:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7917:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7918:     }
1.556     albertel 7919:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7920:     my $user = "$uname:$udom";
                   7921:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7922:     my $reply=cput('classlist',
1.1148    raeburn  7923: 		   {$user => 
1.515     raeburn  7924: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7925: 		   $cdom,$cnum);
1.1148    raeburn  7926:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7927:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7928:     } else { 
1.81      www      7929: 	return 'error: '.$reply;
                   7930:     }
1.297     matthew  7931:     # Add student role to user
1.83      www      7932:     my $uurl='/'.$cid;
1.81      www      7933:     $uurl=~s/\_/\//g;
                   7934:     if ($usec) {
                   7935: 	$uurl.='/'.$usec;
                   7936:     }
1.1148    raeburn  7937:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7938:                              $selfenroll,$context);
                   7939:     if ($result ne 'ok') {
                   7940:         if ($old_entry{$user} ne '') {
                   7941:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7942:         } else {
                   7943:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7944:         }
                   7945:     }
                   7946:     return $result; 
1.21      www      7947: }
                   7948: 
1.556     albertel 7949: sub format_name {
                   7950:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7951:     my $name;
                   7952:     if ($first ne 'lastname') {
                   7953: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7954:     } else {
                   7955: 	if ($lastname=~/\S/) {
                   7956: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7957: 	    $name=~s/\s+,/,/;
                   7958: 	} else {
                   7959: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7960: 	}
                   7961:     }
                   7962:     $name=~s/^\s+//;
                   7963:     $name=~s/\s+$//;
                   7964:     $name=~s/\s+/ /g;
                   7965:     return $name;
                   7966: }
                   7967: 
1.84      www      7968: # ------------------------------------------------- Write to course preferences
                   7969: 
                   7970: sub writecoursepref {
                   7971:     my ($courseid,%prefs)=@_;
                   7972:     $courseid=~s/^\///;
                   7973:     $courseid=~s/\_/\//g;
                   7974:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7975:     my $chome=homeserver($cnum,$cdomain);
                   7976:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7977: 	return 'error: no such course';
                   7978:     }
                   7979:     my $cstring='';
1.800     albertel 7980:     foreach my $pref (keys(%prefs)) {
                   7981: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7982:     }
1.84      www      7983:     $cstring=~s/\&$//;
                   7984:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7985: }
                   7986: 
                   7987: # ---------------------------------------------------------- Make/modify course
                   7988: 
                   7989: sub createcourse {
1.741     raeburn  7990:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7991:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7992:     $url=&declutter($url);
                   7993:     my $cid='';
1.1028    raeburn  7994:     if ($context eq 'requestcourses') {
                   7995:         my $can_create = 0;
                   7996:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7997:         if ($udom eq $ownerdom) {
                   7998:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7999:                                   $context)) {
                   8000:                 $can_create = 1;
                   8001:             }
                   8002:         } else {
                   8003:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   8004:                                            $category);
                   8005:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   8006:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   8007:                 if (@curr > 0) {
                   8008:                     my @options = qw(approval validate autolimit);
                   8009:                     my $optregex = join('|',@options);
                   8010:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   8011:                         $can_create = 1;
                   8012:                     }
                   8013:                 }
                   8014:             }
                   8015:         }
                   8016:         if ($can_create) {
                   8017:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   8018:                 unless (&allowed('ccc',$udom)) {
                   8019:                     return 'refused'; 
                   8020:                 }
1.1017    raeburn  8021:             }
                   8022:         } else {
                   8023:             return 'refused';
                   8024:         }
1.1028    raeburn  8025:     } elsif (!&allowed('ccc',$udom)) {
                   8026:         return 'refused';
1.84      www      8027:     }
1.1011    raeburn  8028: # --------------------------------------------------------------- Get Unique ID
                   8029:     my $uname;
                   8030:     if ($cnum =~ /^$match_courseid$/) {
                   8031:         my $chome=&homeserver($cnum,$udom,'true');
                   8032:         if (($chome eq '') || ($chome eq 'no_host')) {
                   8033:             $uname = $cnum;
                   8034:         } else {
1.1038    raeburn  8035:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8036:         }
                   8037:     } else {
1.1038    raeburn  8038:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  8039:     }
                   8040:     return $uname if ($uname =~ /^error/);
                   8041: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  8042:     if (!defined($course_server)) {
                   8043:         if (defined(&domain($udom,'primary'))) {
                   8044:             $course_server = &domain($udom,'primary');
                   8045:         } else {
                   8046:             $course_server = $env{'user.home'}; 
                   8047:         }
                   8048:     }
                   8049:     my %host_servers =
                   8050:         &Apache::lonnet::get_servers($udom,'library');
                   8051:     unless ($host_servers{$course_server}) {
                   8052:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8053:     }
1.84      www      8054: # ------------------------------------------------------------- Make the course
                   8055:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8056:                       $course_server);
1.84      www      8057:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8058:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8059:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8060: 	return 'error: no such course';
                   8061:     }
1.271     www      8062: # ----------------------------------------------------------------- Course made
1.516     raeburn  8063: # log existence
1.1029    raeburn  8064:     my $now = time;
1.918     raeburn  8065:     my $newcourse = {
                   8066:                     $udom.'_'.$uname => {
1.921     raeburn  8067:                                      description => $description,
                   8068:                                      inst_code   => $inst_code,
                   8069:                                      owner       => $course_owner,
                   8070:                                      type        => $crstype,
1.1029    raeburn  8071:                                      creator     => $env{'user.name'}.':'.
                   8072:                                                     $env{'user.domain'},
                   8073:                                      created     => $now,
                   8074:                                      context     => $context,
1.918     raeburn  8075:                                                 },
                   8076:                     };
1.921     raeburn  8077:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8078: # set toplevel url
1.271     www      8079:     my $topurl=$url;
                   8080:     unless ($nonstandard) {
                   8081: # ------------------------------------------ For standard courses, make top url
                   8082:         my $mapurl=&clutter($url);
1.278     www      8083:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8084:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8085: <map>
                   8086: <resource id="1" type="start"></resource>
                   8087: <resource id="2" src="$mapurl"></resource>
                   8088: <resource id="3" type="finish"></resource>
                   8089: <link index="1" from="1" to="2"></link>
                   8090: <link index="2" from="2" to="3"></link>
                   8091: </map>
                   8092: ENDINITMAP
                   8093:         $topurl=&declutter(
1.638     albertel 8094:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8095:                           );
                   8096:     }
                   8097: # ----------------------------------------------------------- Write preferences
1.84      www      8098:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8099:                      ('description'              => $description,
                   8100:                       'url'                      => $topurl,
                   8101:                       'internal.creator'         => $env{'user.name'}.':'.
                   8102:                                                     $env{'user.domain'},
                   8103:                       'internal.created'         => $now,
                   8104:                       'internal.creationcontext' => $context)
                   8105:                     );
1.84      www      8106:     return '/'.$udom.'/'.$uname;
                   8107: }
                   8108: 
1.1011    raeburn  8109: # ------------------------------------------------------------------- Create ID
                   8110: sub generate_coursenum {
1.1038    raeburn  8111:     my ($udom,$crstype) = @_;
1.1011    raeburn  8112:     my $domdesc = &domain($udom);
                   8113:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8114:     my $first;
                   8115:     if ($crstype eq 'Community') {
                   8116:         $first = '0';
                   8117:     } else {
                   8118:         $first = int(1+rand(9)); 
                   8119:     } 
                   8120:     my $uname=$first.
1.1011    raeburn  8121:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8122:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8123:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8124: # ----------------------------------------------- Make sure that does not exist
                   8125:     my $uhome=&homeserver($uname,$udom,'true');
                   8126:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8127:         if ($crstype eq 'Community') {
                   8128:             $first = '0';
                   8129:         } else {
                   8130:             $first = int(1+rand(9));
                   8131:         }
                   8132:         $uname=$first.
1.1011    raeburn  8133:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8134:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8135:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8136:         $uhome=&homeserver($uname,$udom,'true');
                   8137:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8138:             return 'error: unable to generate unique course-ID';
                   8139:         }
                   8140:     }
                   8141:     return $uname;
                   8142: }
                   8143: 
1.813     albertel 8144: sub is_course {
1.1167    droeschl 8145:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8146:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8147: 
                   8148:     return unless $cdom and $cnum;
                   8149: 
                   8150:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8151:         '.');
                   8152: 
                   8153:     return unless exists($courses{$cdom.'_'.$cnum});
                   8154:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8155: }
                   8156: 
1.1015    raeburn  8157: sub store_userdata {
                   8158:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8159:     my $result;
1.1016    raeburn  8160:     if ($datakey ne '') {
1.1013    raeburn  8161:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8162:             if ($udom eq '' || $uname eq '') {
                   8163:                 $udom = $env{'user.domain'};
                   8164:                 $uname = $env{'user.name'};
                   8165:             }
                   8166:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8167:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8168:                 $result = 'error: no_host';
                   8169:             } else {
                   8170:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8171:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8172: 
                   8173:                 my $namevalue='';
                   8174:                 foreach my $key (keys(%{$storehash})) {
                   8175:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8176:                 }
                   8177:                 $namevalue=~s/\&$//;
1.1105    raeburn  8178:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8179:                                   $namevalue,$uhome);
1.1013    raeburn  8180:             }
                   8181:         } else {
                   8182:             $result = 'error: data to store was not a hash reference'; 
                   8183:         }
                   8184:     } else {
                   8185:         $result= 'error: invalid requestkey'; 
                   8186:     }
                   8187:     return $result;
                   8188: }
                   8189: 
1.21      www      8190: # ---------------------------------------------------------- Assign Custom Role
                   8191: 
                   8192: sub assigncustomrole {
1.957     raeburn  8193:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8194:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8195:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8196: }
                   8197: 
                   8198: # ----------------------------------------------------------------- Revoke Role
                   8199: 
                   8200: sub revokerole {
1.957     raeburn  8201:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8202:     my $now=time;
1.965     raeburn  8203:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8204: }
                   8205: 
                   8206: # ---------------------------------------------------------- Revoke Custom Role
                   8207: 
                   8208: sub revokecustomrole {
1.957     raeburn  8209:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8210:     my $now=time;
1.357     www      8211:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8212:            $deleteflag,$selfenroll,$context);
1.17      www      8213: }
                   8214: 
1.533     banghart 8215: # ------------------------------------------------------------ Disk usage
1.535     albertel 8216: sub diskusage {
1.955     raeburn  8217:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8218:     $directorypath =~ s/\/$//;
                   8219:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8220:                        .&escape($getpropath).':'.&escape($uname).':'
                   8221:                        .&escape($udom),homeserver($uname,$udom));
                   8222:     if ($listing eq 'unknown_cmd') {
                   8223:         if ($getpropath) {
                   8224:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8225:         }
                   8226:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8227:     }
1.514     albertel 8228:     return $listing;
1.512     banghart 8229: }
                   8230: 
1.566     banghart 8231: sub is_locked {
1.1096    raeburn  8232:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8233:     my @check;
                   8234:     my $is_locked;
1.1093    raeburn  8235:     push (@check,$file_name);
1.613     albertel 8236:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8237: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8238:     my ($tmp)=keys(%locked);
                   8239:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8240:     
1.566     banghart 8241:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8242:         $is_locked = 'false';
                   8243:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8244:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8245:                $is_locked = 'true';
1.1096    raeburn  8246:                if (ref($which) eq 'ARRAY') {
                   8247:                    push(@{$which},$entry);
                   8248:                } else {
                   8249:                    last;
                   8250:                }
1.745     raeburn  8251:            }
                   8252:        }
1.566     banghart 8253:     } else {
                   8254:         $is_locked = 'false';
                   8255:     }
1.1093    raeburn  8256:     return $is_locked;
1.566     banghart 8257: }
                   8258: 
1.759     albertel 8259: sub declutter_portfile {
                   8260:     my ($file) = @_;
1.833     albertel 8261:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8262:     return $file;
                   8263: }
                   8264: 
1.559     banghart 8265: # ------------------------------------------------------------- Mark as Read Only
                   8266: 
                   8267: sub mark_as_readonly {
                   8268:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8269:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8270:     my ($tmp)=keys(%current_permissions);
                   8271:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8272:     foreach my $file (@{$files}) {
1.759     albertel 8273: 	$file = &declutter_portfile($file);
1.561     banghart 8274:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8275:     }
1.613     albertel 8276:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8277:     return;
                   8278: }
                   8279: 
1.572     banghart 8280: # ------------------------------------------------------------Save Selected Files
                   8281: 
                   8282: sub save_selected_files {
                   8283:     my ($user, $path, @files) = @_;
                   8284:     my $filename = $user."savedfiles";
1.573     banghart 8285:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8286:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8287:     foreach my $file (@files) {
1.620     albertel 8288:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8289:     }
                   8290:     foreach my $file (@other_files) {
1.574     banghart 8291:         print (OUT $file."\n");
1.572     banghart 8292:     }
1.574     banghart 8293:     close (OUT);
1.572     banghart 8294:     return 'ok';
                   8295: }
                   8296: 
1.574     banghart 8297: sub clear_selected_files {
                   8298:     my ($user) = @_;
                   8299:     my $filename = $user."savedfiles";
1.1117    foxr     8300:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8301:     print (OUT undef);
                   8302:     close (OUT);
                   8303:     return ("ok");    
                   8304: }
                   8305: 
1.572     banghart 8306: sub files_in_path {
                   8307:     my ($user, $path) = @_;
                   8308:     my $filename = $user."savedfiles";
                   8309:     my %return_files;
1.1117    foxr     8310:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8311:     while (my $line_in = <IN>) {
1.574     banghart 8312:         chomp ($line_in);
                   8313:         my @paths_and_file = split (m!/!, $line_in);
                   8314:         my $file_part = pop (@paths_and_file);
                   8315:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8316:         $path_part.='/';
                   8317:         my $path_and_file = $path_part.$file_part;
                   8318:         if ($path_part eq $path) {
                   8319:             $return_files{$file_part}= 'selected';
                   8320:         }
                   8321:     }
1.574     banghart 8322:     close (IN);
                   8323:     return (\%return_files);
1.572     banghart 8324: }
                   8325: 
                   8326: # called in portfolio select mode, to show files selected NOT in current directory
                   8327: sub files_not_in_path {
                   8328:     my ($user, $path) = @_;
                   8329:     my $filename = $user."savedfiles";
                   8330:     my @return_files;
                   8331:     my $path_part;
1.1117    foxr     8332:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8333:     while (my $line = <IN>) {
1.572     banghart 8334:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8335:         my @paths_and_file = split(m|/|, $line);
                   8336:         my $file_part = pop(@paths_and_file);
                   8337:         chomp($file_part);
                   8338:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8339:         $path_part .= '/';
                   8340:         my $path_and_file = $path_part.$file_part;
                   8341:         if ($path_part ne $path) {
1.800     albertel 8342:             push(@return_files, ($path_and_file));
1.572     banghart 8343:         }
                   8344:     }
1.800     albertel 8345:     close(OUT);
1.574     banghart 8346:     return (@return_files);
1.572     banghart 8347: }
                   8348: 
1.745     raeburn  8349: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8350: 
1.745     raeburn  8351: sub get_portfile_permissions {
                   8352:     my ($domain,$user) = @_;
1.613     albertel 8353:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8354:     my ($tmp)=keys(%current_permissions);
                   8355:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8356:     return \%current_permissions;
                   8357: }
                   8358: 
                   8359: #---------------------------------------------Get portfolio file access controls
                   8360: 
1.749     raeburn  8361: sub get_access_controls {
1.745     raeburn  8362:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8363:     my %access;
                   8364:     my $real_file = $file;
                   8365:     $file =~ s/\.meta$//;
1.745     raeburn  8366:     if (defined($file)) {
1.749     raeburn  8367:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8368:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8369:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8370:             }
                   8371:         }
1.745     raeburn  8372:     } else {
1.749     raeburn  8373:         foreach my $key (keys(%{$current_permissions})) {
                   8374:             if ($key =~ /\0accesscontrol$/) {
                   8375:                 if (defined($group)) {
                   8376:                     if ($key !~ m-^\Q$group\E/-) {
                   8377:                         next;
                   8378:                     }
                   8379:                 }
                   8380:                 my ($fullpath) = split(/\0/,$key);
                   8381:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8382:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8383:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8384:                     }
                   8385:                 }
                   8386:             }
                   8387:         }
                   8388:     }
                   8389:     return %access;
                   8390: }
                   8391: 
                   8392: sub modify_access_controls {
                   8393:     my ($file_name,$changes,$domain,$user)=@_;
                   8394:     my ($outcome,$deloutcome);
                   8395:     my %store_permissions;
                   8396:     my %new_values;
                   8397:     my %new_control;
                   8398:     my %translation;
                   8399:     my @deletions = ();
                   8400:     my $now = time;
                   8401:     if (exists($$changes{'activate'})) {
                   8402:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8403:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8404:             my $numnew = scalar(@newitems);
                   8405:             for (my $i=0; $i<$numnew; $i++) {
                   8406:                 my $newkey = $newitems[$i];
                   8407:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8408:                 if ($newkey =~ /^\d+:/) { 
                   8409:                     $newkey =~ s/^(\d+)/$newid/;
                   8410:                     $translation{$1} = $newid;
                   8411:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8412:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8413:                     $translation{$1} = $newid;
                   8414:                 }
1.749     raeburn  8415:                 $new_values{$file_name."\0".$newkey} = 
                   8416:                                           $$changes{'activate'}{$newitems[$i]};
                   8417:                 $new_control{$newkey} = $now;
                   8418:             }
                   8419:         }
                   8420:     }
                   8421:     my %todelete;
                   8422:     my %changed_items;
                   8423:     foreach my $action ('delete','update') {
                   8424:         if (exists($$changes{$action})) {
                   8425:             if (ref($$changes{$action}) eq 'HASH') {
                   8426:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8427:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8428:                     if ($action eq 'delete') { 
                   8429:                         $todelete{$itemnum} = 1;
                   8430:                     } else {
                   8431:                         $changed_items{$itemnum} = $key;
                   8432:                     }
                   8433:                 }
1.745     raeburn  8434:             }
                   8435:         }
1.749     raeburn  8436:     }
                   8437:     # get lock on access controls for file.
                   8438:     my $lockhash = {
                   8439:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8440:                                                        ':'.$env{'user.domain'},
                   8441:                    }; 
                   8442:     my $tries = 0;
                   8443:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8444:    
                   8445:     while (($gotlock ne 'ok') && $tries <3) {
                   8446:         $tries ++;
                   8447:         sleep 1;
                   8448:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8449:     }
                   8450:     if ($gotlock eq 'ok') {
                   8451:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8452:         my ($tmp)=keys(%curr_permissions);
                   8453:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8454:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8455:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8456:             if (ref($curr_controls) eq 'HASH') {
                   8457:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8458:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8459:                     if (defined($todelete{$itemnum})) {
                   8460:                         push(@deletions,$file_name."\0".$control_item);
                   8461:                     } else {
                   8462:                         if (defined($changed_items{$itemnum})) {
                   8463:                             $new_control{$changed_items{$itemnum}} = $now;
                   8464:                             push(@deletions,$file_name."\0".$control_item);
                   8465:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8466:                         } else {
                   8467:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8468:                         }
                   8469:                     }
1.745     raeburn  8470:                 }
                   8471:             }
                   8472:         }
1.970     raeburn  8473:         my ($group);
                   8474:         if (&is_course($domain,$user)) {
                   8475:             ($group,my $file) = split(/\//,$file_name,2);
                   8476:         }
1.749     raeburn  8477:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8478:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8479:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8480:         #  remove lock
                   8481:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8482:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8483:         my $sqlresult =
1.970     raeburn  8484:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8485:                                     $group);
1.749     raeburn  8486:     } else {
                   8487:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8488:     }
1.749     raeburn  8489:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8490: }
                   8491: 
1.827     raeburn  8492: sub make_public_indefinitely {
                   8493:     my ($requrl) = @_;
                   8494:     my $now = time;
                   8495:     my $action = 'activate';
                   8496:     my $aclnum = 0;
                   8497:     if (&is_portfolio_url($requrl)) {
                   8498:         my (undef,$udom,$unum,$file_name,$group) =
                   8499:             &parse_portfolio_url($requrl);
                   8500:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8501:         my %access_controls = &get_access_controls($current_perms,
                   8502:                                                    $group,$file_name);
                   8503:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8504:             my ($num,$scope,$end,$start) = 
                   8505:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8506:             if ($scope eq 'public') {
                   8507:                 if ($start <= $now && $end == 0) {
                   8508:                     $action = 'none';
                   8509:                 } else {
                   8510:                     $action = 'update';
                   8511:                     $aclnum = $num;
                   8512:                 }
                   8513:                 last;
                   8514:             }
                   8515:         }
                   8516:         if ($action eq 'none') {
                   8517:              return 'ok';
                   8518:         } else {
                   8519:             my %changes;
                   8520:             my $newend = 0;
                   8521:             my $newstart = $now;
                   8522:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8523:             $changes{$action}{$newkey} = {
                   8524:                 type => 'public',
                   8525:                 time => {
                   8526:                     start => $newstart,
                   8527:                     end   => $newend,
                   8528:                 },
                   8529:             };
                   8530:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8531:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8532:             return $outcome;
                   8533:         }
                   8534:     } else {
                   8535:         return 'invalid';
                   8536:     }
                   8537: }
                   8538: 
1.745     raeburn  8539: #------------------------------------------------------Get Marked as Read Only
                   8540: 
                   8541: sub get_marked_as_readonly {
                   8542:     my ($domain,$user,$what,$group) = @_;
                   8543:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8544:     my @readonly_files;
1.629     banghart 8545:     my $cmp1=$what;
                   8546:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8547:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8548:         if (defined($group)) {
                   8549:             if ($file_name !~ m-^\Q$group\E/-) {
                   8550:                 next;
                   8551:             }
                   8552:         }
1.561     banghart 8553:         if (ref($value) eq "ARRAY"){
                   8554:             foreach my $stored_what (@{$value}) {
1.629     banghart 8555:                 my $cmp2=$stored_what;
1.759     albertel 8556:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8557:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8558:                 }
1.629     banghart 8559:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8560:                     push(@readonly_files, $file_name);
1.745     raeburn  8561:                     last;
1.563     banghart 8562:                 } elsif (!defined($what)) {
                   8563:                     push(@readonly_files, $file_name);
1.745     raeburn  8564:                     last;
1.561     banghart 8565:                 }
                   8566:             }
1.745     raeburn  8567:         }
1.561     banghart 8568:     }
                   8569:     return @readonly_files;
                   8570: }
1.577     banghart 8571: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8572: 
1.577     banghart 8573: sub get_marked_as_readonly_hash {
1.745     raeburn  8574:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8575:     my %readonly_files;
1.745     raeburn  8576:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8577:         if (defined($group)) {
                   8578:             if ($file_name !~ m-^\Q$group\E/-) {
                   8579:                 next;
                   8580:             }
                   8581:         }
1.577     banghart 8582:         if (ref($value) eq "ARRAY"){
                   8583:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8584:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8585:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8586:                         if ($lock_descriptor eq 'graded') {
                   8587:                             $readonly_files{$file_name} = 'graded';
                   8588:                         } elsif ($lock_descriptor eq 'handback') {
                   8589:                             $readonly_files{$file_name} = 'handback';
                   8590:                         } else {
                   8591:                             if (!exists($readonly_files{$file_name})) {
                   8592:                                 $readonly_files{$file_name} = 'locked';
                   8593:                             }
                   8594:                         }
1.745     raeburn  8595:                     }
1.750     banghart 8596:                 } 
1.577     banghart 8597:             }
                   8598:         } 
                   8599:     }
                   8600:     return %readonly_files;
                   8601: }
1.559     banghart 8602: # ------------------------------------------------------------ Unmark as Read Only
                   8603: 
                   8604: sub unmark_as_readonly {
1.629     banghart 8605:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8606:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8607:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8608:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8609:     my $symb_crs = $what;
                   8610:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8611:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8612:     my ($tmp)=keys(%current_permissions);
                   8613:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8614:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8615:     foreach my $file (@readonly_files) {
1.759     albertel 8616: 	my $clean_file = &declutter_portfile($file);
                   8617: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8618: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8619:         my @new_locks;
                   8620:         my @del_keys;
                   8621:         if (ref($current_locks) eq "ARRAY"){
                   8622:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8623:                 my $compare=$locker;
1.749     raeburn  8624:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8625:                     $compare=join('',@{$locker});
1.746     raeburn  8626:                     if ($compare ne $symb_crs) {
                   8627:                         push(@new_locks, $locker);
                   8628:                     }
1.563     banghart 8629:                 }
                   8630:             }
1.650     albertel 8631:             if (scalar(@new_locks) > 0) {
1.563     banghart 8632:                 $current_permissions{$file} = \@new_locks;
                   8633:             } else {
                   8634:                 push(@del_keys, $file);
1.613     albertel 8635:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8636:                 delete($current_permissions{$file});
1.563     banghart 8637:             }
                   8638:         }
1.561     banghart 8639:     }
1.613     albertel 8640:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8641:     return;
                   8642: }
1.512     banghart 8643: 
1.17      www      8644: # ------------------------------------------------------------ Directory lister
                   8645: 
                   8646: sub dirlist {
1.955     raeburn  8647:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8648:     $uri=~s/^\///;
                   8649:     $uri=~s/\/$//;
1.253     stredwic 8650:     my ($udom, $uname);
1.955     raeburn  8651:     if ($getuserdir) {
1.253     stredwic 8652:         $udom = $userdomain;
                   8653:         $uname = $username;
1.955     raeburn  8654:     } else {
                   8655:         (undef,$udom,$uname)=split(/\//,$uri);
                   8656:         if(defined($userdomain)) {
                   8657:             $udom = $userdomain;
                   8658:         }
                   8659:         if(defined($username)) {
                   8660:             $uname = $username;
                   8661:         }
1.253     stredwic 8662:     }
1.955     raeburn  8663:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8664: 
1.955     raeburn  8665:     $dirRoot = $perlvar{'lonDocRoot'};
                   8666:     if (defined($getpropath)) {
                   8667:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8668:         $dirRoot =~ s/\/$//;
1.955     raeburn  8669:     } elsif (defined($getuserdir)) {
                   8670:         my $subdir=$uname.'__';
                   8671:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8672:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8673:                    ."/$udom/$subdir/$uname";
                   8674:     } elsif (defined($alternateRoot)) {
                   8675:         $dirRoot = $alternateRoot;
1.751     banghart 8676:     }
1.253     stredwic 8677: 
                   8678:     if($udom) {
                   8679:         if($uname) {
1.1135    raeburn  8680:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8681:             if ($uhome eq 'no_host') {
                   8682:                 return ([],'no_host');
                   8683:             }
1.955     raeburn  8684:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8685:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8686:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8687:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8688:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8689:             } else {
                   8690:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8691:             }
1.605     matthew  8692:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8693:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8694:                 @listing_results = split(/:/,$listing);
                   8695:             } else {
                   8696:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8697:             }
1.1135    raeburn  8698:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8699:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8700:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8701:                 return ([],$listing);
                   8702:             } else {
                   8703:                 return (\@listing_results);
1.1135    raeburn  8704:             }
1.955     raeburn  8705:         } elsif(!$alternateRoot) {
1.1136    raeburn  8706:             my (%allusers,%listerror);
1.841     albertel 8707: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8708:  	    foreach my $tryserver (keys(%servers)) {
                   8709:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8710:                                   &escape($udom),$tryserver);
                   8711:                 if ($listing eq 'unknown_cmd') {
                   8712: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8713: 				      $udom, $tryserver);
                   8714:                 } else {
                   8715:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8716:                 }
1.841     albertel 8717: 		if ($listing eq 'unknown_cmd') {
                   8718: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8719: 				      $udom, $tryserver);
                   8720: 		    @listing_results = split(/:/,$listing);
                   8721: 		} else {
                   8722: 		    @listing_results =
                   8723: 			map { &unescape($_); } split(/:/,$listing);
                   8724: 		}
1.1136    raeburn  8725:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8726:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8727:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8728:                     $listerror{$tryserver} = $listing;
                   8729:                 } else {
1.841     albertel 8730: 		    foreach my $line (@listing_results) {
                   8731: 			my ($entry) = split(/&/,$line,2);
                   8732: 			$allusers{$entry} = 1;
                   8733: 		    }
                   8734: 		}
1.253     stredwic 8735:             }
1.1136    raeburn  8736:             my @alluserslist=();
1.800     albertel 8737:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8738:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8739:             }
1.1136    raeburn  8740:             return (\@alluserslist);
1.253     stredwic 8741:         } else {
1.1136    raeburn  8742:             return ([],'missing username');
1.253     stredwic 8743:         }
1.955     raeburn  8744:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8745:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8746:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8747:         return (\@all_domains);
1.955     raeburn  8748:     } else {
1.1136    raeburn  8749:         return ([],'missing domain');
1.275     stredwic 8750:     }
                   8751: }
                   8752: 
                   8753: # --------------------------------------------- GetFileTimestamp
                   8754: # This function utilizes dirlist and returns the date stamp for
                   8755: # when it was last modified.  It will also return an error of -1
                   8756: # if an error occurs
                   8757: 
                   8758: sub GetFileTimestamp {
1.955     raeburn  8759:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8760:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8761:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8762:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8763:                                     undef,$getuserdir);
                   8764:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8765:         return -1;
                   8766:     }
                   8767:     if (ref($fileref) eq 'ARRAY') {
                   8768:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8769:         # @stats contains first the filename, then the stat output
                   8770:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8771:     } else {
                   8772:         return -1;
1.253     stredwic 8773:     }
1.26      www      8774: }
                   8775: 
1.712     albertel 8776: sub stat_file {
                   8777:     my ($uri) = @_;
1.787     albertel 8778:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8779: 
1.955     raeburn  8780:     my ($udom,$uname,$file);
1.712     albertel 8781:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8782: 	($udom,$uname,$file) =
1.811     albertel 8783: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8784: 	$file = 'userfiles/'.$file;
                   8785:     }
                   8786:     if ($uri =~ m-^/res/-) {
                   8787: 	($udom,$uname) = 
1.807     albertel 8788: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8789: 	$file = $uri;
                   8790:     }
                   8791: 
                   8792:     if (!$udom || !$uname || !$file) {
                   8793: 	# unable to handle the uri
                   8794: 	return ();
                   8795:     }
1.956     raeburn  8796:     my $getpropath;
                   8797:     if ($file =~ /^userfiles\//) {
                   8798:         $getpropath = 1;
                   8799:     }
1.1136    raeburn  8800:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8801:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8802:         return ();
                   8803:     } else {
                   8804:         if (ref($listref) eq 'ARRAY') {
                   8805:             my @stats = split('&',$listref->[0]);
                   8806: 	    shift(@stats); #filename is first
                   8807: 	    return @stats;
                   8808:         }
1.712     albertel 8809:     }
                   8810:     return ();
                   8811: }
                   8812: 
1.26      www      8813: # -------------------------------------------------------- Value of a Condition
                   8814: 
1.713     albertel 8815: # gets the value of a specific preevaluated condition
                   8816: #    stored in the string  $env{user.state.<cid>}
                   8817: # or looks up a condition reference in the bighash and if if hasn't
                   8818: # already been evaluated recurses into docondval to get the value of
                   8819: # the condition, then memoizing it to 
                   8820: #   $env{user.state.<cid>.<condition>}
1.40      www      8821: sub directcondval {
                   8822:     my $number=shift;
1.620     albertel 8823:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8824: 	&Apache::lonuserstate::evalstate();
                   8825:     }
1.713     albertel 8826:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8827: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8828:     } elsif ($number =~ /^_/) {
                   8829: 	my $sub_condition;
                   8830: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8831: 		&GDBM_READER(),0640)) {
                   8832: 	    $sub_condition=$bighash{'conditions'.$number};
                   8833: 	    untie(%bighash);
                   8834: 	}
                   8835: 	my $value = &docondval($sub_condition);
1.949     raeburn  8836: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8837: 	return $value;
                   8838:     }
1.620     albertel 8839:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8840:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8841:     } else {
                   8842:        return 2;
                   8843:     }
                   8844: }
                   8845: 
1.713     albertel 8846: # get the collection of conditions for this resource
1.26      www      8847: sub condval {
                   8848:     my $condidx=shift;
1.54      www      8849:     my $allpathcond='';
1.713     albertel 8850:     foreach my $cond (split(/\|/,$condidx)) {
                   8851: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8852: 	    $allpathcond.=
                   8853: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8854: 	}
1.191     harris41 8855:     }
1.54      www      8856:     $allpathcond=~s/\|$//;
1.713     albertel 8857:     return &docondval($allpathcond);
                   8858: }
                   8859: 
                   8860: #evaluates an expression of conditions
                   8861: sub docondval {
                   8862:     my ($allpathcond) = @_;
                   8863:     my $result=0;
                   8864:     if ($env{'request.course.id'}
                   8865: 	&& defined($allpathcond)) {
                   8866: 	my $operand='|';
                   8867: 	my @stack;
                   8868: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8869: 	    if ($chunk eq '(') {
                   8870: 		push @stack,($operand,$result);
                   8871: 	    } elsif ($chunk eq ')') {
                   8872: 		my $before=pop @stack;
                   8873: 		if (pop @stack eq '&') {
                   8874: 		    $result=$result>$before?$before:$result;
                   8875: 		} else {
                   8876: 		    $result=$result>$before?$result:$before;
                   8877: 		}
                   8878: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8879: 		$operand=$chunk;
                   8880: 	    } else {
                   8881: 		my $new=directcondval($chunk);
                   8882: 		if ($operand eq '&') {
                   8883: 		    $result=$result>$new?$new:$result;
                   8884: 		} else {
                   8885: 		    $result=$result>$new?$result:$new;
                   8886: 		}
                   8887: 	    }
                   8888: 	}
1.26      www      8889:     }
                   8890:     return $result;
1.421     albertel 8891: }
                   8892: 
                   8893: # ---------------------------------------------------- Devalidate courseresdata
                   8894: 
                   8895: sub devalidatecourseresdata {
                   8896:     my ($coursenum,$coursedomain)=@_;
                   8897:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8898:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8899: }
                   8900: 
1.763     www      8901: 
1.200     www      8902: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8903: #
                   8904: #  Parameters:
                   8905: #      $coursenum    - Number of the course.
                   8906: #      $coursedomain - Domain at which the course was created.
                   8907: #  Returns:
                   8908: #     A hash of the course parameters along (I think) with timestamps
                   8909: #     and version info.
1.877     foxr     8910: 
1.624     albertel 8911: sub get_courseresdata {
                   8912:     my ($coursenum,$coursedomain)=@_;
1.200     www      8913:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8914:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8915:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8916:     my %dumpreply;
1.417     albertel 8917:     unless (defined($cached)) {
1.624     albertel 8918: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8919: 	$result=\%dumpreply;
1.251     albertel 8920: 	my ($tmp) = keys(%dumpreply);
                   8921: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8922: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8923: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8924: 	    return $tmp;
1.416     albertel 8925: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8926: 	    $result=undef;
1.599     albertel 8927: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8928: 	}
                   8929:     }
1.624     albertel 8930:     return $result;
                   8931: }
                   8932: 
1.633     albertel 8933: sub devalidateuserresdata {
                   8934:     my ($uname,$udom)=@_;
                   8935:     my $hashid="$udom:$uname";
                   8936:     &devalidate_cache_new('userres',$hashid);
                   8937: }
                   8938: 
1.624     albertel 8939: sub get_userresdata {
                   8940:     my ($uname,$udom)=@_;
                   8941:     #most student don\'t have any data set, check if there is some data
                   8942:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8943: 
                   8944:     my $hashid="$udom:$uname";
                   8945:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8946:     if (!defined($cached)) {
                   8947: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8948: 	$result=\%resourcedata;
                   8949: 	&do_cache_new('userres',$hashid,$result,600);
                   8950:     }
                   8951:     my ($tmp)=keys(%$result);
                   8952:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8953: 	return $result;
                   8954:     }
                   8955:     #error 2 occurs when the .db doesn't exist
                   8956:     if ($tmp!~/error: 2 /) {
1.672     albertel 8957: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8958: 		 " Trying to get resource data for ".
                   8959: 		 $uname." at ".$udom.": ".
                   8960: 		 $tmp."</font>");
                   8961:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8962: 	#&EXT_cache_set($udom,$uname);
                   8963: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8964: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8965:     }
                   8966:     return $tmp;
                   8967: }
1.879     foxr     8968: #----------------------------------------------- resdata - return resource data
                   8969: #  Purpose:
                   8970: #    Return resource data for either users or for a course.
                   8971: #  Parameters:
                   8972: #     $name      - Course/user name.
                   8973: #     $domain    - Name of the domain the user/course is registered on.
                   8974: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8975: #     @which     - Array of names of resources desired.
                   8976: #  Returns:
                   8977: #     The value of the first reasource in @which that is found in the
                   8978: #     resource hash.
                   8979: #  Exceptional Conditions:
                   8980: #     If the $type passed in is not valid (not the string 'course' or 
                   8981: #     'user', an undefined  reference is returned.
                   8982: #     If none of the resources are found, an undef is returned
1.624     albertel 8983: sub resdata {
                   8984:     my ($name,$domain,$type,@which)=@_;
                   8985:     my $result;
                   8986:     if ($type eq 'course') {
                   8987: 	$result=&get_courseresdata($name,$domain);
                   8988:     } elsif ($type eq 'user') {
                   8989: 	$result=&get_userresdata($name,$domain);
                   8990:     }
                   8991:     if (!ref($result)) { return $result; }    
1.251     albertel 8992:     foreach my $item (@which) {
1.927     albertel 8993: 	if (defined($result->{$item->[0]})) {
                   8994: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8995: 	}
1.250     albertel 8996:     }
1.291     albertel 8997:     return undef;
1.200     www      8998: }
                   8999: 
1.379     matthew  9000: #
                   9001: # EXT resource caching routines
                   9002: #
                   9003: 
                   9004: sub clear_EXT_cache_status {
1.383     albertel 9005:     &delenv('cache.EXT.');
1.379     matthew  9006: }
                   9007: 
                   9008: sub EXT_cache_status {
                   9009:     my ($target_domain,$target_user) = @_;
1.383     albertel 9010:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 9011:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  9012:         # We know already the user has no data
                   9013:         return 1;
                   9014:     } else {
                   9015:         return 0;
                   9016:     }
                   9017: }
                   9018: 
                   9019: sub EXT_cache_set {
                   9020:     my ($target_domain,$target_user) = @_;
1.383     albertel 9021:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  9022:     #&appenv({$cachename => time});
1.379     matthew  9023: }
                   9024: 
1.28      www      9025: # --------------------------------------------------------- Value of a Variable
1.58      www      9026: sub EXT {
1.715     albertel 9027: 
1.395     albertel 9028:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      9029:     unless ($varname) { return ''; }
1.218     albertel 9030:     #get real user name/domain, courseid and symb
                   9031:     my $courseid;
1.359     albertel 9032:     my $publicuser;
1.427     www      9033:     if ($symbparm) {
                   9034: 	$symbparm=&get_symb_from_alias($symbparm);
                   9035:     }
1.218     albertel 9036:     if (!($uname && $udom)) {
1.790     albertel 9037:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 9038:       if (!$symbparm) {	$symbparm=$cursymb; }
                   9039:     } else {
1.620     albertel 9040: 	$courseid=$env{'request.course.id'};
1.218     albertel 9041:     }
1.48      www      9042:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   9043:     my $rest;
1.320     albertel 9044:     if (defined($therest[0])) {
1.48      www      9045:        $rest=join('.',@therest);
                   9046:     } else {
                   9047:        $rest='';
                   9048:     }
1.320     albertel 9049: 
1.57      www      9050:     my $qualifierrest=$qualifier;
                   9051:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9052:     my $spacequalifierrest=$space;
                   9053:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9054:     if ($realm eq 'user') {
1.48      www      9055: # --------------------------------------------------------------- user.resource
                   9056: 	if ($space eq 'resource') {
1.651     albertel 9057: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9058: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9059: 		 &&
1.744     albertel 9060: 		 ($symbparm eq &symbread()) ) {	
                   9061: 		# if we are in the middle of processing the resource the
                   9062: 		# get the value we are planning on committing
                   9063:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9064:                     return $Apache::lonhomework::results{$qualifierrest};
                   9065:                 } else {
                   9066:                     return $Apache::lonhomework::history{$qualifierrest};
                   9067:                 }
1.335     albertel 9068: 	    } else {
1.359     albertel 9069: 		my %restored;
1.620     albertel 9070: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9071: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9072: 		} else {
                   9073: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9074: 		}
1.335     albertel 9075: 		return $restored{$qualifierrest};
                   9076: 	    }
1.48      www      9077: # ----------------------------------------------------------------- user.access
                   9078:         } elsif ($space eq 'access') {
1.218     albertel 9079: 	    # FIXME - not supporting calls for a specific user
1.48      www      9080:             return &allowed($qualifier,$rest);
                   9081: # ------------------------------------------ user.preferences, user.environment
                   9082:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9083: 	    if (($uname eq $env{'user.name'}) &&
                   9084: 		($udom eq $env{'user.domain'})) {
                   9085: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9086: 	    } else {
1.359     albertel 9087: 		my %returnhash;
                   9088: 		if (!$publicuser) {
                   9089: 		    %returnhash=&userenvironment($udom,$uname,
                   9090: 						 $qualifierrest);
                   9091: 		}
1.218     albertel 9092: 		return $returnhash{$qualifierrest};
                   9093: 	    }
1.48      www      9094: # ----------------------------------------------------------------- user.course
                   9095:         } elsif ($space eq 'course') {
1.218     albertel 9096: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9097:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9098: # ------------------------------------------------------------------- user.role
                   9099:         } elsif ($space eq 'role') {
1.218     albertel 9100: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9101:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9102:             if ($qualifier eq 'value') {
                   9103: 		return $role;
                   9104:             } elsif ($qualifier eq 'extent') {
                   9105:                 return $where;
                   9106:             }
                   9107: # ----------------------------------------------------------------- user.domain
                   9108:         } elsif ($space eq 'domain') {
1.218     albertel 9109:             return $udom;
1.48      www      9110: # ------------------------------------------------------------------- user.name
                   9111:         } elsif ($space eq 'name') {
1.218     albertel 9112:             return $uname;
1.48      www      9113: # ---------------------------------------------------- Any other user namespace
1.29      www      9114:         } else {
1.359     albertel 9115: 	    my %reply;
                   9116: 	    if (!$publicuser) {
                   9117: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9118: 	    }
                   9119: 	    return $reply{$qualifierrest};
1.48      www      9120:         }
1.236     www      9121:     } elsif ($realm eq 'query') {
                   9122: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9123:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9124: 						[$spacequalifierrest]);
1.620     albertel 9125: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9126:    } elsif ($realm eq 'request') {
1.48      www      9127: # ------------------------------------------------------------- request.browser
                   9128:         if ($space eq 'browser') {
1.1145    bisitz   9129:             return $env{'browser.'.$qualifier};
1.57      www      9130: # ------------------------------------------------------------ request.filename
                   9131:         } else {
1.620     albertel 9132:             return $env{'request.'.$spacequalifierrest};
1.29      www      9133:         }
1.28      www      9134:     } elsif ($realm eq 'course') {
1.48      www      9135: # ---------------------------------------------------------- course.description
1.620     albertel 9136:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9137:     } elsif ($realm eq 'resource') {
1.165     www      9138: 
1.620     albertel 9139: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9140: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9141: 	}
1.693     albertel 9142: 
                   9143: 	if ($space eq 'title') {
                   9144: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9145: 	    return &gettitle($symbparm);
                   9146: 	}
                   9147: 	
                   9148: 	if ($space eq 'map') {
                   9149: 	    my ($map) = &decode_symb($symbparm);
                   9150: 	    return &symbread($map);
                   9151: 	}
1.905     albertel 9152: 	if ($space eq 'filename') {
                   9153: 	    if ($symbparm) {
                   9154: 		return &clutter((&decode_symb($symbparm))[2]);
                   9155: 	    }
                   9156: 	    return &hreflocation('',$env{'request.filename'});
                   9157: 	}
1.693     albertel 9158: 
                   9159: 	my ($section, $group, @groups);
1.593     albertel 9160: 	my ($courselevelm,$courselevel);
1.539     albertel 9161: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9162: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9163: 
1.218     albertel 9164: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9165: 
1.60      www      9166: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9167: 	    my $symbp=$symbparm;
1.735     albertel 9168: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9169: 
                   9170: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9171: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9172: 
1.620     albertel 9173: 	    if (($env{'user.name'} eq $uname) &&
                   9174: 		($env{'user.domain'} eq $udom)) {
                   9175: 		$section=$env{'request.course.sec'};
1.733     raeburn  9176:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9177:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9178: 	    } else {
1.539     albertel 9179: 		if (! defined($usection)) {
1.551     albertel 9180: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9181: 		} else {
                   9182: 		    $section = $usection;
                   9183: 		}
1.733     raeburn  9184:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9185: 	    }
                   9186: 
                   9187: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9188: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9189: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9190: 
1.593     albertel 9191: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9192: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9193: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9194: 
1.60      www      9195: # ----------------------------------------------------------- first, check user
1.624     albertel 9196: 
                   9197: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9198: 				       ([$courselevelr,'resource'],
                   9199: 					[$courselevelm,'map'     ],
                   9200: 					[$courselevel, 'course'  ]));
1.931     albertel 9201: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9202: 
1.594     albertel 9203: # ------------------------------------------------ second, check some of course
1.684     raeburn  9204:             my $coursereply;
1.691     raeburn  9205:             if (@groups > 0) {
                   9206:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9207:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9208:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9209:             }
1.96      www      9210: 
1.684     raeburn  9211: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9212: 				  $env{'course.'.$courseid.'.domain'},
                   9213: 				  'course',
                   9214: 				  ([$seclevelr,   'resource'],
                   9215: 				   [$seclevelm,   'map'     ],
                   9216: 				   [$seclevel,    'course'  ],
                   9217: 				   [$courselevelr,'resource']));
                   9218: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9219: 
1.60      www      9220: # ------------------------------------------------------ third, check map parms
1.218     albertel 9221: 	    my %parmhash=();
                   9222: 	    my $thisparm='';
                   9223: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9224: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9225: 		    &GDBM_READER(),0640)) {
1.218     albertel 9226: 		$thisparm=$parmhash{$symbparm};
                   9227: 		untie(%parmhash);
                   9228: 	    }
1.927     albertel 9229: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9230: 	}
1.594     albertel 9231: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9232: 
1.218     albertel 9233: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9234: 	my $filename;
                   9235: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9236: 	if ($symbparm) {
1.409     www      9237: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9238: 	} else {
1.620     albertel 9239: 	    $filename=$env{'request.filename'};
1.282     albertel 9240: 	}
                   9241: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9242: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9243: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9244: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9245: 
1.927     albertel 9246: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9247: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9248: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9249: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9250: 				     $env{'course.'.$courseid.'.domain'},
                   9251: 				     'course',
1.927     albertel 9252: 				     ([$courselevelm,'map'   ],
                   9253: 				      [$courselevel, 'course']));
                   9254: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9255: 	}
1.145     www      9256: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9257: 	unless ($space eq '0') {
1.336     albertel 9258: 	    my @parts=split(/_/,$space);
                   9259: 	    my $id=pop(@parts);
                   9260: 	    my $part=join('_',@parts);
                   9261: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9262: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9263: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9264: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9265: 	}
1.395     albertel 9266: 	if ($recurse) { return undef; }
                   9267: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9268: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9269: # ---------------------------------------------------- Any other user namespace
                   9270:     } elsif ($realm eq 'environment') {
                   9271: # ----------------------------------------------------------------- environment
1.620     albertel 9272: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9273: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9274: 	} else {
1.770     albertel 9275: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9276: 		return '';
                   9277: 	    }
1.219     albertel 9278: 	    my %returnhash=&userenvironment($udom,$uname,
                   9279: 					    $spacequalifierrest);
                   9280: 	    return $returnhash{$spacequalifierrest};
                   9281: 	}
1.28      www      9282:     } elsif ($realm eq 'system') {
1.48      www      9283: # ----------------------------------------------------------------- system.time
                   9284: 	if ($space eq 'time') {
                   9285: 	    return time;
                   9286:         }
1.696     albertel 9287:     } elsif ($realm eq 'server') {
                   9288: # ----------------------------------------------------------------- system.time
                   9289: 	if ($space eq 'name') {
                   9290: 	    return $ENV{'SERVER_NAME'};
                   9291:         }
1.28      www      9292:     }
1.48      www      9293:     return '';
1.61      www      9294: }
                   9295: 
1.927     albertel 9296: sub get_reply {
                   9297:     my ($reply_value) = @_;
1.940     raeburn  9298:     if (ref($reply_value) eq 'ARRAY') {
                   9299:         if (wantarray) {
                   9300: 	    return @$reply_value;
                   9301:         }
                   9302:         return $reply_value->[0];
                   9303:     } else {
                   9304:         return $reply_value;
1.927     albertel 9305:     }
                   9306: }
                   9307: 
1.691     raeburn  9308: sub check_group_parms {
                   9309:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9310:     my @groupitems = ();
                   9311:     my $resultitem;
1.927     albertel 9312:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9313:     foreach my $group (@{$groups}) {
                   9314:         foreach my $level (@levels) {
1.927     albertel 9315:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9316:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9317:         }
                   9318:     }
                   9319:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9320:                             $env{'course.'.$courseid.'.domain'},
                   9321:                                      'course',@groupitems);
                   9322:     return $coursereply;
                   9323: }
                   9324: 
                   9325: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9326:     my ($courseid,@groups) = @_;
                   9327:     @groups = sort(@groups);
1.691     raeburn  9328:     return @groups;
                   9329: }
                   9330: 
1.395     albertel 9331: sub packages_tab_default {
                   9332:     my ($uri,$varname)=@_;
                   9333:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9334: 
                   9335:     my (@extension,@specifics,$do_default);
                   9336:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9337: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9338: 	if ($pack_type eq 'default') {
                   9339: 	    $do_default=1;
                   9340: 	} elsif ($pack_type eq 'extension') {
                   9341: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9342: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9343: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9344: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9345: 	}
                   9346:     }
                   9347:     # first look for a package that matches the requested part id
                   9348:     foreach my $package (@specifics) {
                   9349: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9350: 	next if ($pack_part ne $part);
                   9351: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9352: 	    return $packagetab{"$pack_type&$name&default"};
                   9353: 	}
                   9354:     }
                   9355:     # look for any possible matching non extension_ package
                   9356:     foreach my $package (@specifics) {
                   9357: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9358: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9359: 	    return $packagetab{"$pack_type&$name&default"};
                   9360: 	}
1.585     albertel 9361: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9362: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9363: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9364: 	}
                   9365:     }
1.738     albertel 9366:     # look for any posible extension_ match
                   9367:     foreach my $package (@extension) {
                   9368: 	my ($package,$pack_type)=@{$package};
                   9369: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9370: 	    return $packagetab{"$pack_type&$name&default"};
                   9371: 	}
                   9372: 	if (defined($packagetab{$package."&$name&default"})) {
                   9373: 	    return $packagetab{$package."&$name&default"};
                   9374: 	}
                   9375:     }
                   9376:     # look for a global default setting
                   9377:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9378: 	return $packagetab{"default&$name&default"};
                   9379:     }
1.395     albertel 9380:     return undef;
                   9381: }
                   9382: 
1.334     albertel 9383: sub add_prefix_and_part {
                   9384:     my ($prefix,$part)=@_;
                   9385:     my $keyroot;
                   9386:     if (defined($prefix) && $prefix !~ /^__/) {
                   9387: 	# prefix that has a part already
                   9388: 	$keyroot=$prefix;
                   9389:     } elsif (defined($prefix)) {
                   9390: 	# prefix that is missing a part
                   9391: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9392:     } else {
                   9393: 	# no prefix at all
                   9394: 	if (defined($part)) { $keyroot='_'.$part; }
                   9395:     }
                   9396:     return $keyroot;
                   9397: }
                   9398: 
1.71      www      9399: # ---------------------------------------------------------------- Get metadata
                   9400: 
1.599     albertel 9401: my %metaentry;
1.1070    www      9402: my %importedpartids;
1.71      www      9403: sub metadata {
1.176     www      9404:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9405:     $uri=&declutter($uri);
1.288     albertel 9406:     # if it is a non metadata possible uri return quickly
1.529     albertel 9407:     if (($uri eq '') || 
                   9408: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9409: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9410:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9411: 	return undef;
                   9412:     }
1.1140    www      9413:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9414: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9415: 	return undef;
1.288     albertel 9416:     }
1.73      www      9417:     my $filename=$uri;
                   9418:     $uri=~s/\.meta$//;
1.172     www      9419: #
                   9420: # Is the metadata already cached?
1.177     www      9421: # Look at timestamp of caching
1.172     www      9422: # Everything is cached by the main uri, libraries are never directly cached
                   9423: #
1.428     albertel 9424:     if (!defined($liburi)) {
1.599     albertel 9425: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9426: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9427:     }
                   9428:     {
1.1069    www      9429: # Imported parts would go here
1.1070    www      9430:         my %importedids=();
                   9431:         my @origfileimportpartids=();
1.1069    www      9432:         my $importedparts=0;
1.172     www      9433: #
                   9434: # Is this a recursive call for a library?
                   9435: #
1.599     albertel 9436: #	if (! exists($metacache{$uri})) {
                   9437: #	    $metacache{$uri}={};
                   9438: #	}
1.924     albertel 9439: 	my $cachetime = 60*60;
1.171     www      9440:         if ($liburi) {
                   9441: 	    $liburi=&declutter($liburi);
                   9442:             $filename=$liburi;
1.401     bowersj2 9443:         } else {
1.599     albertel 9444: 	    &devalidate_cache_new('meta',$uri);
                   9445: 	    undef(%metaentry);
1.401     bowersj2 9446: 	}
1.140     www      9447:         my %metathesekeys=();
1.73      www      9448:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9449: 	my $metastring;
1.1140    www      9450: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9451: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9452: 	    $metastring = 
1.929     albertel 9453: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9454: 					  ('grade_target' => 'meta'));
                   9455: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9456: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9457:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9458: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9459: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9460: 	    $metastring=&getfile($file);
1.489     albertel 9461: 	}
1.208     albertel 9462:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9463:         my $token;
1.140     www      9464:         undef %metathesekeys;
1.71      www      9465:         while ($token=$parser->get_token) {
1.339     albertel 9466: 	    if ($token->[0] eq 'S') {
                   9467: 		if (defined($token->[2]->{'package'})) {
1.172     www      9468: #
                   9469: # This is a package - get package info
                   9470: #
1.339     albertel 9471: 		    my $package=$token->[2]->{'package'};
                   9472: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9473: 		    if (defined($token->[2]->{'id'})) { 
                   9474: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9475: 		    }
1.599     albertel 9476: 		    if ($metaentry{':packages'}) {
                   9477: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9478: 		    } else {
1.599     albertel 9479: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9480: 		    }
1.736     albertel 9481: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9482: 			my $part=$keyroot;
                   9483: 			$part=~s/^\_//;
1.736     albertel 9484: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9485: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9486: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9487: 			    # ignore package.tab specified default values
                   9488:                             # here &package_tab_default() will fetch those
                   9489: 			    if ($subp eq 'default') { next; }
1.736     albertel 9490: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9491: 			    my $unikey;
                   9492: 			    if ($pack =~ /_0$/) {
                   9493: 				$unikey='parameter_0_'.$name;
                   9494: 				$part=0;
                   9495: 			    } else {
                   9496: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9497: 			    }
1.339     albertel 9498: 			    if ($subp eq 'display') {
                   9499: 				$value.=' [Part: '.$part.']';
                   9500: 			    }
1.599     albertel 9501: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9502: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9503: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9504: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9505: 			    }
1.599     albertel 9506: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9507: 				$metaentry{':'.$unikey}=
                   9508: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9509: 			    }
1.339     albertel 9510: 			}
                   9511: 		    }
                   9512: 		} else {
1.172     www      9513: #
                   9514: # This is not a package - some other kind of start tag
1.339     albertel 9515: #
                   9516: 		    my $entry=$token->[1];
1.1068    www      9517: 		    my $unikey='';
1.175     www      9518: 
1.339     albertel 9519: 		    if ($entry eq 'import') {
1.175     www      9520: #
                   9521: # Importing a library here
1.339     albertel 9522: #
1.1067    www      9523:                         my $location=$parser->get_text('/import');
                   9524:                         my $dir=$filename;
                   9525:                         $dir=~s|[^/]*$||;
                   9526:                         $location=&filelocation($dir,$location);
1.1069    www      9527:                        
1.1068    www      9528:                         my $importmode=$token->[2]->{'importmode'};
                   9529:                         if ($importmode eq 'problem') {
1.1069    www      9530: # Import as problem/response
1.1068    www      9531:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9532:                         } elsif ($importmode eq 'part') {
                   9533: # Import as part(s)
1.1069    www      9534:                            $importedparts=1;
                   9535: # We need to get the original file and the imported file to get the part order correct
                   9536: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9537: # Load and inspect original file
1.1070    www      9538:                            if ($#origfileimportpartids<0) {
                   9539:                               undef(%importedpartids);
                   9540:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9541:                               my $origfile=&getfile($origfilelocation);
                   9542:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9543:                            }
                   9544: 
1.1069    www      9545: # Load and inspect imported file
                   9546:                            my $impfile=&getfile($location);
                   9547:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9548:                            if ($#impfilepartids>=0) {
                   9549: # This problem had parts
1.1070    www      9550:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9551:                            } else {
                   9552: # Importing by turning a single problem into a problem part
                   9553: # It gets the import-tags ID as part-ID
                   9554:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9555:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9556:                            }
1.1068    www      9557:                         } else {
                   9558: # Normal import
                   9559:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9560:                            if (defined($token->[2]->{'id'})) {
                   9561:                               $unikey.='_'.$token->[2]->{'id'};
                   9562:                            }
1.1067    www      9563:                         }
                   9564: 
1.339     albertel 9565: 			if ($depthcount<20) {
1.736     albertel 9566: 			    my $metadata = 
                   9567: 				&metadata($uri,'keys', $location,$unikey,
                   9568: 					  $depthcount+1);
                   9569: 			    foreach my $meta (split(',',$metadata)) {
                   9570: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9571: 				$metathesekeys{$meta}=1;
1.339     albertel 9572: 			    }
1.1068    www      9573: 			
                   9574:                         }
1.1067    www      9575: 		    } else {
                   9576: #
                   9577: # Not importing, some other kind of non-package, non-library start tag
                   9578: # 
                   9579:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9580:                         if (defined($token->[2]->{'id'})) {
                   9581:                             $unikey.='_'.$token->[2]->{'id'};
                   9582:                         }
1.339     albertel 9583: 			if (defined($token->[2]->{'name'})) { 
                   9584: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9585: 			}
                   9586: 			$metathesekeys{$unikey}=1;
1.736     albertel 9587: 			foreach my $param (@{$token->[3]}) {
                   9588: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9589: 				$token->[2]->{$param};
1.339     albertel 9590: 			}
                   9591: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9592: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9593: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9594: 		 # only ws inside the tag, and not in default, so use default
                   9595: 		 # as value
1.599     albertel 9596: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9597: 			} elsif ( $internaltext =~ /\S/ ) {
                   9598: 		  # something interesting inside the tag
                   9599: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9600: 			} else {
1.908     albertel 9601: 		  # no interesting values, don't set a default
1.339     albertel 9602: 			}
1.172     www      9603: # end of not-a-package not-a-library import
1.339     albertel 9604: 		    }
1.172     www      9605: # end of not-a-package start tag
1.339     albertel 9606: 		}
1.172     www      9607: # the next is the end of "start tag"
1.339     albertel 9608: 	    }
                   9609: 	}
1.483     albertel 9610: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9611: 	$extension = lc($extension);
                   9612: 	if ($extension eq 'htm') { $extension='html'; }
                   9613: 
1.737     albertel 9614: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9615: 	    #no specific packages #how's our extension
                   9616: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9617: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9618: 					 \%metathesekeys);
                   9619: 	}
1.883     albertel 9620: 
                   9621: 	if (!exists($metaentry{':packages'})
                   9622: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9623: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9624: 		#no specific packages well let's get default then
                   9625: 		if ($key!~/^default&/) { next; }
1.488     albertel 9626: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9627: 					     \%metathesekeys);
                   9628: 	    }
                   9629: 	}
1.338     www      9630: # are there custom rights to evaluate
1.599     albertel 9631: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9632: 
1.338     www      9633:     #
                   9634:     # Importing a rights file here
1.339     albertel 9635:     #
                   9636: 	    unless ($depthcount) {
1.599     albertel 9637: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9638: 		my $dir=$filename;
                   9639: 		$dir=~s|[^/]*$||;
                   9640: 		$location=&filelocation($dir,$location);
1.736     albertel 9641: 		my $rights_metadata =
                   9642: 		    &metadata($uri,'keys',$location,'_rights',
                   9643: 			      $depthcount+1);
                   9644: 		foreach my $rights (split(',',$rights_metadata)) {
                   9645: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9646: 		    $metathesekeys{$rights}=1;
1.339     albertel 9647: 		}
                   9648: 	    }
                   9649: 	}
1.737     albertel 9650: 	# uniqifiy package listing
                   9651: 	my %seen;
                   9652: 	my @uniq_packages =
                   9653: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9654: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9655: 
1.1070    www      9656:         if ($importedparts) {
                   9657: # We had imported parts and need to rebuild partorder
                   9658:            $metaentry{':partorder'}='';
                   9659:            $metathesekeys{'partorder'}=1;
                   9660:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9661:                if ($origfileimportpartids[$index] eq 'part') {
                   9662: # original part, part of the problem
                   9663:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9664:                } else {
                   9665: # we have imported parts at this position
                   9666:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9667:                }
                   9668:            }
                   9669:            $metaentry{':partorder'}=~s/^\,//;
                   9670:         }
                   9671: 
1.737     albertel 9672: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9673: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9674: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9675: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9676: # this is the end of "was not already recently cached
1.71      www      9677:     }
1.599     albertel 9678:     return $metaentry{':'.$what};
1.261     albertel 9679: }
                   9680: 
1.488     albertel 9681: sub metadata_create_package_def {
1.483     albertel 9682:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9683:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9684:     if ($subp eq 'default') { next; }
                   9685:     
1.599     albertel 9686:     if (defined($metaentry{':packages'})) {
                   9687: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9688:     } else {
1.599     albertel 9689: 	$metaentry{':packages'}=$package;
1.483     albertel 9690:     }
                   9691:     my $value=$packagetab{$key};
                   9692:     my $unikey;
                   9693:     $unikey='parameter_0_'.$name;
1.599     albertel 9694:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9695:     $$metathesekeys{$unikey}=1;
1.599     albertel 9696:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9697: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9698:     }
1.599     albertel 9699:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9700: 	$metaentry{':'.$unikey}=
                   9701: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9702:     }
                   9703: }
                   9704: 
1.261     albertel 9705: sub metadata_generate_part0 {
                   9706:     my ($metadata,$metacache,$uri) = @_;
                   9707:     my %allnames;
1.737     albertel 9708:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9709: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9710: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9711: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9712: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9713: 	    $allnames{$name}=$part;
                   9714: 	  }
                   9715: 	}
                   9716:     }
                   9717:     foreach my $name (keys(%allnames)) {
                   9718:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9719:       my $key=":parameter_0_$name";
1.261     albertel 9720:       $$metacache{"$key.part"}='0';
                   9721:       $$metacache{"$key.name"}=$name;
1.428     albertel 9722:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9723: 					   $allnames{$name}.'_'.$name.
                   9724: 					   '.type'};
1.428     albertel 9725:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9726: 			     '.display'};
1.644     www      9727:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9728:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9729:       $$metacache{"$key.display"}=$olddis;
                   9730:     }
1.71      www      9731: }
                   9732: 
1.764     albertel 9733: # ------------------------------------------------------ Devalidate title cache
                   9734: 
                   9735: sub devalidate_title_cache {
                   9736:     my ($url)=@_;
                   9737:     if (!$env{'request.course.id'}) { return; }
                   9738:     my $symb=&symbread($url);
                   9739:     if (!$symb) { return; }
                   9740:     my $key=$env{'request.course.id'}."\0".$symb;
                   9741:     &devalidate_cache_new('title',$key);
                   9742: }
                   9743: 
1.1014    droeschl 9744: # ------------------------------------------------- Get the title of a course
                   9745: 
                   9746: sub current_course_title {
                   9747:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9748: }
1.301     www      9749: # ------------------------------------------------- Get the title of a resource
                   9750: 
                   9751: sub gettitle {
                   9752:     my $urlsymb=shift;
                   9753:     my $symb=&symbread($urlsymb);
1.534     albertel 9754:     if ($symb) {
1.620     albertel 9755: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9756: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9757: 	if (defined($cached)) { 
                   9758: 	    return $result;
                   9759: 	}
1.534     albertel 9760: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9761: 	my $title='';
1.907     albertel 9762: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9763: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9764: 	} else {
                   9765: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9766: 		    &GDBM_READER(),0640)) {
                   9767: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9768: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9769: 		untie(%bighash);
                   9770: 	    }
1.534     albertel 9771: 	}
                   9772: 	$title=~s/\&colon\;/\:/gs;
                   9773: 	if ($title) {
1.1159    www      9774: # Remember both $symb and $title for dynamic metadata
                   9775:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9776:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9777: # Cache this title and then return it
1.599     albertel 9778: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9779: 	}
                   9780: 	$urlsymb=$url;
                   9781:     }
                   9782:     my $title=&metadata($urlsymb,'title');
                   9783:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9784:     return $title;
1.301     www      9785: }
1.613     albertel 9786: 
1.614     albertel 9787: sub get_slot {
                   9788:     my ($which,$cnum,$cdom)=@_;
                   9789:     if (!$cnum || !$cdom) {
1.790     albertel 9790: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9791: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9792: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9793:     }
1.703     albertel 9794:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9795:     my %slotinfo;
                   9796:     if (exists($remembered{$key})) {
                   9797: 	$slotinfo{$which} = $remembered{$key};
                   9798:     } else {
                   9799: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9800: 	&Apache::lonhomework::showhash(%slotinfo);
                   9801: 	my ($tmp)=keys(%slotinfo);
                   9802: 	if ($tmp=~/^error:/) { return (); }
                   9803: 	$remembered{$key} = $slotinfo{$which};
                   9804:     }
1.616     albertel 9805:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9806: 	return %{$slotinfo{$which}};
                   9807:     }
                   9808:     return $slotinfo{$which};
1.614     albertel 9809: }
1.1150    raeburn  9810: 
                   9811: sub get_reservable_slots {
                   9812:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9813:     my $now = time;
                   9814:     my $reservable_info;
                   9815:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9816:     if (exists($remembered{$key})) {
                   9817:         $reservable_info = $remembered{$key};
                   9818:     } else {
                   9819:         my %resv;
                   9820:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9821:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9822:         $reservable_info = \%resv;
                   9823:         $remembered{$key} = $reservable_info;
                   9824:     }
                   9825:     return $reservable_info;
                   9826: }
                   9827: 
                   9828: sub get_course_slots {
                   9829:     my ($cnum,$cdom) = @_;
                   9830:     my $hashid=$cnum.':'.$cdom;
                   9831:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9832:     if (defined($cached)) {
                   9833:         if (ref($result) eq 'HASH') {
                   9834:             return %{$result};
                   9835:         }
                   9836:     } else {
                   9837:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9838:         my ($tmp) = keys(%slots);
                   9839:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9840:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9841:             return %slots;
                   9842:         }
                   9843:     }
                   9844:     return;
                   9845: }
                   9846: 
                   9847: sub devalidate_slots_cache {
                   9848:     my ($cnum,$cdom)=@_;
                   9849:     my $hashid=$cnum.':'.$cdom;
                   9850:     &devalidate_cache_new('allslots',$hashid);
                   9851: }
                   9852: 
1.1181  ! raeburn  9853: sub get_coursechange {
        !          9854:     my ($cdom,$cnum) = @_;
        !          9855:     if ($cdom eq '' || $cnum eq '') {
        !          9856:         return unless ($env{'request.course.id'});
        !          9857:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
        !          9858:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
        !          9859:     }
        !          9860:     my $hashid=$cdom.'_'.$cnum;
        !          9861:     my ($change,$cached)=&is_cached_new('crschange',$hashid);
        !          9862:     if ((defined($cached)) && ($change ne '')) {
        !          9863:         return $change;
        !          9864:     } else {
        !          9865:         my %crshash;
        !          9866:         %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
        !          9867:         if ($crshash{'internal.contentchange'} eq '') {
        !          9868:             $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
        !          9869:             if ($change eq '') {
        !          9870:                 %crshash = &get('environment',['internal.created'],$cdom,$cnum);
        !          9871:                 $change = $crshash{'internal.created'};
        !          9872:             }
        !          9873:         } else {
        !          9874:             $change = $crshash{'internal.contentchange'};
        !          9875:         }
        !          9876:         my $cachetime = 600;
        !          9877:         &do_cache_new('crschange',$hashid,$change,$cachetime);
        !          9878:     }
        !          9879:     return $change;
        !          9880: }
        !          9881: 
        !          9882: sub devalidate_coursechange_cache {
        !          9883:     my ($cnum,$cdom)=@_;
        !          9884:     my $hashid=$cnum.':'.$cdom;
        !          9885:     &devalidate_cache_new('crschange',$hashid);
        !          9886: }
        !          9887: 
1.31      www      9888: # ------------------------------------------------- Update symbolic store links
                   9889: 
                   9890: sub symblist {
                   9891:     my ($mapname,%newhash)=@_;
1.438     www      9892:     $mapname=&deversion(&declutter($mapname));
1.31      www      9893:     my %hash;
1.620     albertel 9894:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9895:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9896:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9897: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9898: 		next if ($url eq 'last_known'
                   9899: 			 && $env{'form.no_update_last_known'});
                   9900: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9901: 						    $newhash{$url}->[1],
                   9902: 						    $newhash{$url}->[0]);
1.191     harris41 9903:             }
1.31      www      9904:             if (untie(%hash)) {
                   9905: 		return 'ok';
                   9906:             }
                   9907:         }
                   9908:     }
                   9909:     return 'error';
1.212     www      9910: }
                   9911: 
                   9912: # --------------------------------------------------------------- Verify a symb
                   9913: 
                   9914: sub symbverify {
1.510     www      9915:     my ($symb,$thisurl)=@_;
                   9916:     my $thisfn=$thisurl;
1.439     www      9917:     $thisfn=&declutter($thisfn);
1.215     www      9918: # direct jump to resource in page or to a sequence - will construct own symbs
                   9919:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9920: # check URL part
1.409     www      9921:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9922: 
1.431     www      9923:     unless ($url eq $thisfn) { return 0; }
1.213     www      9924: 
1.216     www      9925:     $symb=&symbclean($symb);
1.510     www      9926:     $thisurl=&deversion($thisurl);
1.439     www      9927:     $thisfn=&deversion($thisfn);
1.213     www      9928: 
                   9929:     my %bighash;
                   9930:     my $okay=0;
1.431     www      9931: 
1.620     albertel 9932:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9933:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9934:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9935:             $thisurl =~ s/\?.+$//;
                   9936:         }
1.510     www      9937:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9938:         unless ($ids) {
                   9939:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9940:             $ids=$bighash{$idkey};
1.216     www      9941:         }
                   9942:         if ($ids) {
                   9943: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9944: 	    foreach my $id (split(/\,/,$ids)) {
                   9945: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9946:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9947:                    $symb =~ s/\?.+$//;
                   9948:                }
1.216     www      9949:                if (
                   9950:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9951:    eq $symb) { 
1.620     albertel 9952: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9953: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9954:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9955: 		       $okay=1; 
                   9956: 		   }
                   9957: 	       }
1.216     www      9958: 	   }
                   9959:         }
1.213     www      9960: 	untie(%bighash);
                   9961:     }
                   9962:     return $okay;
1.31      www      9963: }
                   9964: 
1.210     www      9965: # --------------------------------------------------------------- Clean-up symb
                   9966: 
                   9967: sub symbclean {
                   9968:     my $symb=shift;
1.568     albertel 9969:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9970: # remove version from map
                   9971:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9972: 
1.210     www      9973: # remove version from URL
                   9974:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9975: 
1.507     www      9976: # remove wrapper
                   9977: 
1.510     www      9978:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9979:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9980:     return $symb;
1.409     www      9981: }
                   9982: 
                   9983: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9984: 
                   9985: sub encode_symb {
                   9986:     my ($map,$resid,$url)=@_;
                   9987:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9988: }
1.409     www      9989: 
                   9990: sub decode_symb {
1.568     albertel 9991:     my $symb=shift;
                   9992:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9993:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9994:     return (&fixversion($map),$resid,&fixversion($url));
                   9995: }
                   9996: 
                   9997: sub fixversion {
                   9998:     my $fn=shift;
1.609     banghart 9999:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      10000:     my %bighash;
                   10001:     my $uri=&clutter($fn);
1.620     albertel 10002:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      10003: # is this cached?
1.599     albertel 10004:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      10005:     if (defined($cached)) { return $result; }
                   10006: # unfortunately not cached, or expired
1.620     albertel 10007:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      10008: 	    &GDBM_READER(),0640)) {
                   10009:  	if ($bighash{'version_'.$uri}) {
                   10010:  	    my $version=$bighash{'version_'.$uri};
1.444     www      10011:  	    unless (($version eq 'mostrecent') || 
                   10012: 		    ($version==&getversion($uri))) {
1.440     www      10013:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   10014:  	    }
                   10015:  	}
                   10016:  	untie %bighash;
1.413     www      10017:     }
1.599     albertel 10018:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      10019: }
                   10020: 
                   10021: sub deversion {
                   10022:     my $url=shift;
                   10023:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   10024:     return $url;
1.210     www      10025: }
                   10026: 
1.31      www      10027: # ------------------------------------------------------ Return symb list entry
                   10028: 
                   10029: sub symbread {
1.249     www      10030:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 10031:     my $cache_str='request.symbread.cached.'.$thisfn;
1.1179    raeburn  10032:     if (defined($env{$cache_str})) {
                   10033:         if (($thisfn) || ($env{$cache_str} ne '')) {
                   10034:             return $env{$cache_str};
                   10035:         }
                   10036:     }
1.242     www      10037: # no filename provided? try from environment
1.44      www      10038:     unless ($thisfn) {
1.620     albertel 10039:         if ($env{'request.symb'}) {
                   10040: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 10041: 	}
1.620     albertel 10042: 	$thisfn=$env{'request.filename'};
1.44      www      10043:     }
1.569     albertel 10044:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      10045: # is that filename actually a symb? Verify, clean, and return
                   10046:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 10047: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 10048: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 10049: 	}
1.242     www      10050:     }
1.44      www      10051:     $thisfn=declutter($thisfn);
1.31      www      10052:     my %hash;
1.37      www      10053:     my %bighash;
                   10054:     my $syval='';
1.620     albertel 10055:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  10056:         my $targetfn = $thisfn;
1.609     banghart 10057:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  10058:             $targetfn = 'adm/wrapper/'.$thisfn;
                   10059:         }
1.687     albertel 10060: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   10061: 	    $targetfn=$1;
                   10062: 	}
1.620     albertel 10063:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 10064:                       &GDBM_READER(),0640)) {
1.481     raeburn  10065: 	    $syval=$hash{$targetfn};
1.37      www      10066:             untie(%hash);
                   10067:         }
                   10068: # ---------------------------------------------------------- There was an entry
                   10069:         if ($syval) {
1.601     albertel 10070: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 10071: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  10072: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10073: 		    #return $env{$cache_str}='';
1.601     albertel 10074: 		#}    
                   10075: 		#$syval.=$1;
                   10076: 	    #}
1.37      www      10077:         } else {
                   10078: # ------------------------------------------------------- Was not in symb table
1.620     albertel 10079:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 10080:                             &GDBM_READER(),0640)) {
1.37      www      10081: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      10082:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10083:               unless ($ids) { 
                   10084:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10085:               }
                   10086:               unless ($ids) {
                   10087: # alias?
                   10088: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10089:               }
1.37      www      10090:               if ($ids) {
                   10091: # ------------------------------------------------------------------- Has ID(s)
                   10092:                  my @possibilities=split(/\,/,$ids);
1.39      www      10093:                  if ($#possibilities==0) {
                   10094: # ----------------------------------------------- There is only one possibility
1.37      www      10095: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10096: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10097: 						    $resid,$thisfn);
1.249     www      10098:                  } elsif (!$donotrecurse) {
1.39      www      10099: # ------------------------------------------ There is more than one possibility
                   10100:                      my $realpossible=0;
1.800     albertel 10101:                      foreach my $id (@possibilities) {
                   10102: 			 my $file=$bighash{'src_'.$id};
1.39      www      10103:                          if (&allowed('bre',$file)) {
1.800     albertel 10104:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10105:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10106: 				$realpossible++;
1.626     albertel 10107:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10108: 						    $resid,$thisfn);
1.39      www      10109:                             }
                   10110: 			 }
1.191     harris41 10111:                      }
1.39      www      10112: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10113:                  } else {
                   10114:                      $syval='';
1.37      www      10115:                  }
                   10116: 	      }
                   10117:               untie(%bighash)
1.481     raeburn  10118:            }
1.31      www      10119:         }
1.62      www      10120:         if ($syval) {
1.620     albertel 10121: 	    return $env{$cache_str}=$syval;
1.62      www      10122:         }
1.31      www      10123:     }
1.949     raeburn  10124:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10125:     return $env{$cache_str}='';
1.31      www      10126: }
                   10127: 
                   10128: # ---------------------------------------------------------- Return random seed
                   10129: 
1.32      www      10130: sub numval {
                   10131:     my $txt=shift;
                   10132:     $txt=~tr/A-J/0-9/;
                   10133:     $txt=~tr/a-j/0-9/;
                   10134:     $txt=~tr/K-T/0-9/;
                   10135:     $txt=~tr/k-t/0-9/;
                   10136:     $txt=~tr/U-Z/0-5/;
                   10137:     $txt=~tr/u-z/0-5/;
                   10138:     $txt=~s/\D//g;
1.564     albertel 10139:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10140:     return int($txt);
1.368     albertel 10141: }
                   10142: 
1.484     albertel 10143: sub numval2 {
                   10144:     my $txt=shift;
                   10145:     $txt=~tr/A-J/0-9/;
                   10146:     $txt=~tr/a-j/0-9/;
                   10147:     $txt=~tr/K-T/0-9/;
                   10148:     $txt=~tr/k-t/0-9/;
                   10149:     $txt=~tr/U-Z/0-5/;
                   10150:     $txt=~tr/u-z/0-5/;
                   10151:     $txt=~s/\D//g;
                   10152:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10153:     my $total;
                   10154:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10155:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10156:     return int($total);
                   10157: }
                   10158: 
1.575     albertel 10159: sub numval3 {
                   10160:     use integer;
                   10161:     my $txt=shift;
                   10162:     $txt=~tr/A-J/0-9/;
                   10163:     $txt=~tr/a-j/0-9/;
                   10164:     $txt=~tr/K-T/0-9/;
                   10165:     $txt=~tr/k-t/0-9/;
                   10166:     $txt=~tr/U-Z/0-5/;
                   10167:     $txt=~tr/u-z/0-5/;
                   10168:     $txt=~s/\D//g;
                   10169:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10170:     my $total;
                   10171:     foreach my $val (@txts) { $total+=$val; }
                   10172:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10173:     return $total;
                   10174: }
                   10175: 
1.675     albertel 10176: sub digest {
                   10177:     my ($data)=@_;
                   10178:     my $digest=&Digest::MD5::md5($data);
                   10179:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10180:     my ($e,$f);
                   10181:     {
                   10182:         use integer;
                   10183:         $e=($a+$b);
                   10184:         $f=($c+$d);
                   10185:         if ($_64bit) {
                   10186:             $e=(($e<<32)>>32);
                   10187:             $f=(($f<<32)>>32);
                   10188:         }
                   10189:     }
                   10190:     if (wantarray) {
                   10191: 	return ($e,$f);
                   10192:     } else {
                   10193: 	my $g;
                   10194: 	{
                   10195: 	    use integer;
                   10196: 	    $g=($e+$f);
                   10197: 	    if ($_64bit) {
                   10198: 		$g=(($g<<32)>>32);
                   10199: 	    }
                   10200: 	}
                   10201: 	return $g;
                   10202:     }
                   10203: }
                   10204: 
1.368     albertel 10205: sub latest_rnd_algorithm_id {
1.675     albertel 10206:     return '64bit5';
1.366     albertel 10207: }
1.32      www      10208: 
1.503     albertel 10209: sub get_rand_alg {
                   10210:     my ($courseid)=@_;
1.790     albertel 10211:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10212:     if ($courseid) {
1.620     albertel 10213: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10214:     }
                   10215:     return &latest_rnd_algorithm_id();
                   10216: }
                   10217: 
1.562     albertel 10218: sub validCODE {
                   10219:     my ($CODE)=@_;
                   10220:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10221:     return 0;
                   10222: }
                   10223: 
1.491     albertel 10224: sub getCODE {
1.620     albertel 10225:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10226:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10227: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10228: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10229: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10230:     }
                   10231:     return undef;
                   10232: }
1.1133    foxr     10233: #
                   10234: #  Determines the random seed for a specific context:
                   10235: #
                   10236: # parameters:
                   10237: #   symb      - in course context the symb for the seed.
                   10238: #   course_id - The course id of the form domain_coursenum.
                   10239: #   domain    - Domain for the user.
                   10240: #   course    - Course for the user.
                   10241: #   cenv      - environment of the course.
                   10242: #
                   10243: # NOTE:
                   10244: #   All parameters are picked out of the environment if missing
                   10245: #   or not defined.
                   10246: #   If a symb cannot be determined the current time is used instead.
                   10247: #
                   10248: #  For a given well defined symb, courside, domain, username,
                   10249: #  and course environment, the seed is reproducible.
                   10250: #
1.31      www      10251: sub rndseed {
1.1133    foxr     10252:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10253:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10254:     if (!defined($symb)) {
1.366     albertel 10255: 	unless ($symb=$wsymb) { return time; }
                   10256:     }
1.1146    foxr     10257:     if (!defined $courseid) { 
                   10258: 	$courseid=$wcourseid; 
                   10259:     }
                   10260:     if (!defined $domain) { $domain=$wdomain; }
                   10261:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10262: 
                   10263:     my $which;
                   10264:     if (defined($cenv->{'rndseed'})) {
                   10265: 	$which = $cenv->{'rndseed'};
                   10266:     } else {
                   10267: 	$which =&get_rand_alg($courseid);
                   10268:     }
1.491     albertel 10269:     if (defined(&getCODE())) {
1.1133    foxr     10270: 
1.675     albertel 10271: 	if ($which eq '64bit5') {
                   10272: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10273: 	} elsif ($which eq '64bit4') {
1.575     albertel 10274: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10275: 	} else {
                   10276: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10277: 	}
1.675     albertel 10278:     } elsif ($which eq '64bit5') {
                   10279: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10280:     } elsif ($which eq '64bit4') {
                   10281: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10282:     } elsif ($which eq '64bit3') {
                   10283: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10284:     } elsif ($which eq '64bit2') {
                   10285: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10286:     } elsif ($which eq '64bit') {
                   10287: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10288:     }
                   10289:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10290: }
                   10291: 
                   10292: sub rndseed_32bit {
                   10293:     my ($symb,$courseid,$domain,$username)=@_;
                   10294:     {
                   10295: 	use integer;
                   10296: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10297: 	my $symbseed=numval($symb) << 22;
                   10298: 	my $namechck=unpack("%32C*",$username) << 17;
                   10299: 	my $nameseed=numval($username) << 12;
                   10300: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10301: 	my $courseseed=unpack("%32C*",$courseid);
                   10302: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10303: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10304: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10305: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10306: 	return $num;
                   10307:     }
                   10308: }
                   10309: 
                   10310: sub rndseed_64bit {
                   10311:     my ($symb,$courseid,$domain,$username)=@_;
                   10312:     {
                   10313: 	use integer;
                   10314: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10315: 	my $symbseed=numval($symb) << 10;
                   10316: 	my $namechck=unpack("%32S*",$username);
                   10317: 	
                   10318: 	my $nameseed=numval($username) << 21;
                   10319: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10320: 	my $courseseed=unpack("%32S*",$courseid);
                   10321: 	
                   10322: 	my $num1=$symbchck+$symbseed+$namechck;
                   10323: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10324: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10325: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10326: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10327: 	return "$num1,$num2";
1.155     albertel 10328:     }
1.366     albertel 10329: }
                   10330: 
1.443     albertel 10331: sub rndseed_64bit2 {
                   10332:     my ($symb,$courseid,$domain,$username)=@_;
                   10333:     {
                   10334: 	use integer;
                   10335: 	# strings need to be an even # of cahracters long, it it is odd the
                   10336:         # last characters gets thrown away
                   10337: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10338: 	my $symbseed=numval($symb) << 10;
                   10339: 	my $namechck=unpack("%32S*",$username.' ');
                   10340: 	
                   10341: 	my $nameseed=numval($username) << 21;
1.501     albertel 10342: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10343: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10344: 	
                   10345: 	my $num1=$symbchck+$symbseed+$namechck;
                   10346: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10347: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10348: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10349: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10350: 	return "$num1,$num2";
                   10351:     }
                   10352: }
                   10353: 
                   10354: sub rndseed_64bit3 {
                   10355:     my ($symb,$courseid,$domain,$username)=@_;
                   10356:     {
                   10357: 	use integer;
                   10358: 	# strings need to be an even # of cahracters long, it it is odd the
                   10359:         # last characters gets thrown away
                   10360: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10361: 	my $symbseed=numval2($symb) << 10;
                   10362: 	my $namechck=unpack("%32S*",$username.' ');
                   10363: 	
                   10364: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10365: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10366: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10367: 	
                   10368: 	my $num1=$symbchck+$symbseed+$namechck;
                   10369: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10370: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10371: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10372: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10373: 	
1.503     albertel 10374: 	return "$num1:$num2";
1.443     albertel 10375:     }
                   10376: }
                   10377: 
1.575     albertel 10378: sub rndseed_64bit4 {
                   10379:     my ($symb,$courseid,$domain,$username)=@_;
                   10380:     {
                   10381: 	use integer;
                   10382: 	# strings need to be an even # of cahracters long, it it is odd the
                   10383:         # last characters gets thrown away
                   10384: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10385: 	my $symbseed=numval3($symb) << 10;
                   10386: 	my $namechck=unpack("%32S*",$username.' ');
                   10387: 	
                   10388: 	my $nameseed=numval3($username) << 21;
                   10389: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10390: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10391: 	
                   10392: 	my $num1=$symbchck+$symbseed+$namechck;
                   10393: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10394: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10395: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10396: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10397: 	
1.575     albertel 10398: 	return "$num1:$num2";
                   10399:     }
                   10400: }
                   10401: 
1.675     albertel 10402: sub rndseed_64bit5 {
                   10403:     my ($symb,$courseid,$domain,$username)=@_;
                   10404:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10405:     return "$num1:$num2";
                   10406: }
                   10407: 
1.366     albertel 10408: sub rndseed_CODE_64bit {
                   10409:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10410:     {
1.366     albertel 10411: 	use integer;
1.443     albertel 10412: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10413: 	my $symbseed=numval2($symb);
1.491     albertel 10414: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10415: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10416: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10417: 	my $num1=$symbseed+$CODEchck;
                   10418: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10419: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10420: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10421: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10422: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10423: 	return "$num1:$num2";
1.366     albertel 10424:     }
                   10425: }
                   10426: 
1.575     albertel 10427: sub rndseed_CODE_64bit4 {
                   10428:     my ($symb,$courseid,$domain,$username)=@_;
                   10429:     {
                   10430: 	use integer;
                   10431: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10432: 	my $symbseed=numval3($symb);
                   10433: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10434: 	my $CODEseed=numval3(&getCODE());
                   10435: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10436: 	my $num1=$symbseed+$CODEchck;
                   10437: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10438: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10439: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10440: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10441: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10442: 	return "$num1:$num2";
                   10443:     }
                   10444: }
                   10445: 
1.675     albertel 10446: sub rndseed_CODE_64bit5 {
                   10447:     my ($symb,$courseid,$domain,$username)=@_;
                   10448:     my $code = &getCODE();
                   10449:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10450:     return "$num1:$num2";
                   10451: }
                   10452: 
1.366     albertel 10453: sub setup_random_from_rndseed {
                   10454:     my ($rndseed)=@_;
1.503     albertel 10455:     if ($rndseed =~/([,:])/) {
                   10456: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10457: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10458:     } else {
                   10459: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10460:     }
1.36      albertel 10461: }
                   10462: 
1.474     albertel 10463: sub latest_receipt_algorithm_id {
1.835     albertel 10464:     return 'receipt3';
1.474     albertel 10465: }
                   10466: 
1.480     www      10467: sub recunique {
                   10468:     my $fucourseid=shift;
                   10469:     my $unique;
1.835     albertel 10470:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10471: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10472: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10473:     } else {
                   10474: 	$unique=$perlvar{'lonReceipt'};
                   10475:     }
                   10476:     return unpack("%32C*",$unique);
                   10477: }
                   10478: 
                   10479: sub recprefix {
                   10480:     my $fucourseid=shift;
                   10481:     my $prefix;
1.835     albertel 10482:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10483: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10484: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10485:     } else {
                   10486: 	$prefix=$perlvar{'lonHostID'};
                   10487:     }
                   10488:     return unpack("%32C*",$prefix);
                   10489: }
                   10490: 
1.76      www      10491: sub ireceipt {
1.474     albertel 10492:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10493: 
                   10494:     my $return =&recprefix($fucourseid).'-';
                   10495: 
                   10496:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10497: 	$env{'request.state'} eq 'construct') {
                   10498: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10499: 	return $return;
                   10500:     }
                   10501: 
1.76      www      10502:     my $cuname=unpack("%32C*",$funame);
                   10503:     my $cudom=unpack("%32C*",$fudom);
                   10504:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10505:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10506:     my $cunique=&recunique($fucourseid);
1.474     albertel 10507:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10508:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10509: 
1.790     albertel 10510: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10511: 			       
                   10512: 	$return.= ($cunique%$cuname+
                   10513: 		   $cunique%$cudom+
                   10514: 		   $cusymb%$cuname+
                   10515: 		   $cusymb%$cudom+
                   10516: 		   $cucourseid%$cuname+
                   10517: 		   $cucourseid%$cudom+
                   10518: 		   $cpart%$cuname+
                   10519: 		   $cpart%$cudom);
                   10520:     } else {
                   10521: 	$return.= ($cunique%$cuname+
                   10522: 		   $cunique%$cudom+
                   10523: 		   $cusymb%$cuname+
                   10524: 		   $cusymb%$cudom+
                   10525: 		   $cucourseid%$cuname+
                   10526: 		   $cucourseid%$cudom);
                   10527:     }
                   10528:     return $return;
1.76      www      10529: }
                   10530: 
                   10531: sub receipt {
1.474     albertel 10532:     my ($part)=@_;
1.790     albertel 10533:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10534:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10535: }
1.260     ng       10536: 
1.790     albertel 10537: sub whichuser {
                   10538:     my ($passedsymb)=@_;
                   10539:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10540:     if (defined($env{'form.grade_symb'})) {
                   10541: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10542: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10543: 	if (!$allowed &&
                   10544: 	    exists($env{'request.course.sec'}) &&
                   10545: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10546: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10547: 			      '/'.$env{'request.course.sec'});
                   10548: 	}
                   10549: 	if ($allowed) {
                   10550: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10551: 	    $courseid=$tmp_courseid;
                   10552: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10553: 	    ($name)=&get_env_multiple('form.grade_username');
                   10554: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10555: 	}
                   10556:     }
                   10557:     if (!$passedsymb) {
                   10558: 	$symb=&symbread();
                   10559:     } else {
                   10560: 	$symb=$passedsymb;
                   10561:     }
                   10562:     $courseid=$env{'request.course.id'};
                   10563:     $domain=$env{'user.domain'};
                   10564:     $name=$env{'user.name'};
                   10565:     if ($name eq 'public' && $domain eq 'public') {
                   10566: 	if (!defined($env{'form.username'})) {
                   10567: 	    $env{'form.username'}.=time.rand(10000000);
                   10568: 	}
                   10569: 	$name.=$env{'form.username'};
                   10570:     }
                   10571:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10572: 
                   10573: }
                   10574: 
1.36      albertel 10575: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10576: # returns either the contents of the file or 
                   10577: # -1 if the file doesn't exist
1.481     raeburn  10578: #
                   10579: # if the target is a file that was uploaded via DOCS, 
                   10580: # a check will be made to see if a current copy exists on the local server,
                   10581: # if it does this will be served, otherwise a copy will be retrieved from
                   10582: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10583: # the local server.   
1.472     albertel 10584: 
1.36      albertel 10585: sub getfile {
1.538     albertel 10586:     my ($file) = @_;
1.609     banghart 10587:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10588:     &repcopy($file);
                   10589:     return &readfile($file);
                   10590: }
                   10591: 
                   10592: sub repcopy_userfile {
                   10593:     my ($file)=@_;
1.1142    raeburn  10594:     my $londocroot = $perlvar{'lonDocRoot'};
                   10595:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10596:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10597:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10598: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10599:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10600:     if (-e "$file") {
1.828     www      10601: # we already have a local copy, check it out
1.538     albertel 10602: 	my @fileinfo = stat($file);
1.828     www      10603: 	my $rtncode;
                   10604: 	my $info;
1.538     albertel 10605: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10606: 	if ($lwpresp ne 'ok') {
1.828     www      10607: # there is no such file anymore, even though we had a local copy
1.482     albertel 10608: 	    if ($rtncode eq '404') {
1.538     albertel 10609: 		unlink($file);
1.482     albertel 10610: 	    }
                   10611: 	    return -1;
                   10612: 	}
                   10613: 	if ($info < $fileinfo[9]) {
1.828     www      10614: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10615: 	    return 'ok';
1.828     www      10616: 	} else {
                   10617: # the file is outdated, get rid of it
                   10618: 	    unlink($file);
1.482     albertel 10619: 	}
1.828     www      10620:     }
                   10621: # one way or the other, at this point, we don't have the file
                   10622: # construct the correct path for the file
                   10623:     my @parts = ($cdom,$cnum); 
                   10624:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10625: 	push @parts, split(/\//,$1);
                   10626:     }
                   10627:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10628:     foreach my $part (@parts) {
                   10629: 	$path .= '/'.$part;
                   10630: 	if (!-e $path) {
                   10631: 	    mkdir($path,0770);
1.482     albertel 10632: 	}
                   10633:     }
1.828     www      10634: # now the path exists for sure
                   10635: # get a user agent
                   10636:     my $ua=new LWP::UserAgent;
                   10637:     my $transferfile=$file.'.in.transfer';
                   10638: # FIXME: this should flock
                   10639:     if (-e $transferfile) { return 'ok'; }
                   10640:     my $request;
                   10641:     $uri=~s/^\///;
1.980     raeburn  10642:     my $homeserver = &homeserver($cnum,$cdom);
                   10643:     my $protocol = $protocol{$homeserver};
                   10644:     $protocol = 'http' if ($protocol ne 'https');
                   10645:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10646:     my $response=$ua->request($request,$transferfile);
                   10647: # did it work?
                   10648:     if ($response->is_error()) {
                   10649: 	unlink($transferfile);
                   10650: 	&logthis("Userfile repcopy failed for $uri");
                   10651: 	return -1;
                   10652:     }
                   10653: # worked, rename the transfer file
                   10654:     rename($transferfile,$file);
1.607     raeburn  10655:     return 'ok';
1.481     raeburn  10656: }
                   10657: 
1.517     albertel 10658: sub tokenwrapper {
                   10659:     my $uri=shift;
1.980     raeburn  10660:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10661:     $uri=~s|^/||;
1.620     albertel 10662:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10663:     my $token=$1;
1.552     albertel 10664:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10665:     if ($udom && $uname && $file) {
                   10666: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10667:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10668:         my $homeserver = &homeserver($uname,$udom);
                   10669:         my $protocol = $protocol{$homeserver};
                   10670:         $protocol = 'http' if ($protocol ne 'https');
                   10671:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10672:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10673:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10674:     } else {
                   10675:         return '/adm/notfound.html';
                   10676:     }
                   10677: }
                   10678: 
1.828     www      10679: # call with reqtype HEAD: get last modification time
                   10680: # call with reqtype GET: get the file contents
                   10681: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10682: #
1.481     raeburn  10683: sub getuploaded {
                   10684:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10685:     $uri=~s/^\///;
1.980     raeburn  10686:     my $homeserver = &homeserver($cnum,$cdom);
                   10687:     my $protocol = $protocol{$homeserver};
                   10688:     $protocol = 'http' if ($protocol ne 'https');
                   10689:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10690:     my $ua=new LWP::UserAgent;
                   10691:     my $request=new HTTP::Request($reqtype,$uri);
                   10692:     my $response=$ua->request($request);
                   10693:     $$rtncode = $response->code;
1.482     albertel 10694:     if (! $response->is_success()) {
                   10695: 	return 'failed';
                   10696:     }      
                   10697:     if ($reqtype eq 'HEAD') {
1.486     www      10698: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10699:     } elsif ($reqtype eq 'GET') {
                   10700: 	$$info = $response->content;
1.472     albertel 10701:     }
1.482     albertel 10702:     return 'ok';
1.36      albertel 10703: }
                   10704: 
1.481     raeburn  10705: sub readfile {
                   10706:     my $file = shift;
                   10707:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10708:     my $fh;
                   10709:     open($fh,"<$file");
                   10710:     my $a='';
1.800     albertel 10711:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10712:     return $a;
                   10713: }
                   10714: 
1.36      albertel 10715: sub filelocation {
1.590     banghart 10716:     my ($dir,$file) = @_;
                   10717:     my $location;
                   10718:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10719: 
                   10720:     if ($file =~ m-^/adm/-) {
                   10721: 	$file=~s-^/adm/wrapper/-/-;
                   10722: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10723:     }
1.882     albertel 10724: 
1.1139    www      10725:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10726:         $location = $file;
1.609     banghart 10727:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10728:         my ($udom,$uname,$filename)=
1.811     albertel 10729:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10730:         my $home=&homeserver($uname,$udom);
                   10731:         my $is_me=0;
                   10732:         my @ids=&current_machine_ids();
                   10733:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10734:         if ($is_me) {
1.1117    foxr     10735:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10736:         } else {
                   10737:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10738:   	      $udom.'/'.$uname.'/'.$filename;
                   10739:         }
1.882     albertel 10740:     } elsif ($file =~ m-^/adm/-) {
                   10741: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10742:     } else {
                   10743:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10744:         $file=~s:^/(res|priv)/:/:;
                   10745:         my $space=$1;
1.590     banghart 10746:         if ( !( $file =~ m:^/:) ) {
                   10747:             $location = $dir. '/'.$file;
                   10748:         } else {
1.1142    raeburn  10749:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10750:         }
1.59      albertel 10751:     }
1.590     banghart 10752:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10753:     while ($location=~m{/\.\./}) {
                   10754: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10755: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10756: 	} else {
                   10757: 	    $location=~ s{/\.\./}{/}g;
                   10758: 	}
                   10759:     } #remove dir/..
1.590     banghart 10760:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10761:     return $location;
1.46      www      10762: }
1.36      albertel 10763: 
1.46      www      10764: sub hreflocation {
                   10765:     my ($dir,$file)=@_;
1.980     raeburn  10766:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10767: 	$file=filelocation($dir,$file);
1.700     albertel 10768:     } elsif ($file=~m-^/adm/-) {
                   10769: 	$file=~s-^/adm/wrapper/-/-;
                   10770: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10771:     }
                   10772:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10773: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10774:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10775: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10776: 	        {/uploaded/$1/$2/}x;
1.46      www      10777:     }
1.913     albertel 10778:     if ($file=~ m{^/userfiles/}) {
                   10779: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10780:     }
1.462     albertel 10781:     return $file;
1.465     albertel 10782: }
                   10783: 
1.1139    www      10784: 
                   10785: 
                   10786: 
                   10787: 
1.465     albertel 10788: sub current_machine_domains {
1.853     albertel 10789:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10790: }
                   10791: 
                   10792: sub machine_domains {
                   10793:     my ($hostname) = @_;
1.465     albertel 10794:     my @domains;
1.838     albertel 10795:     my %hostname = &all_hostnames();
1.465     albertel 10796:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10797: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10798: 	if ($hostname eq $name) {
1.844     albertel 10799: 	    push(@domains,&host_domain($id));
1.465     albertel 10800: 	}
                   10801:     }
                   10802:     return @domains;
                   10803: }
                   10804: 
                   10805: sub current_machine_ids {
1.853     albertel 10806:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10807: }
                   10808: 
                   10809: sub machine_ids {
                   10810:     my ($hostname) = @_;
                   10811:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10812:     my @ids;
1.888     albertel 10813:     my %name_to_host = &all_names();
1.889     albertel 10814:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10815: 	return @{ $name_to_host{$hostname} };
                   10816:     }
                   10817:     return;
1.31      www      10818: }
                   10819: 
1.824     raeburn  10820: sub additional_machine_domains {
                   10821:     my @domains;
                   10822:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10823:     while( my $line = <$fh>) {
                   10824:         $line =~ s/\s//g;
                   10825:         push(@domains,$line);
                   10826:     }
                   10827:     return @domains;
                   10828: }
                   10829: 
                   10830: sub default_login_domain {
                   10831:     my $domain = $perlvar{'lonDefDomain'};
                   10832:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10833:     foreach my $posdom (&current_machine_domains(),
                   10834:                         &additional_machine_domains()) {
                   10835:         if (lc($posdom) eq lc($testdomain)) {
                   10836:             $domain=$posdom;
                   10837:             last;
                   10838:         }
                   10839:     }
                   10840:     return $domain;
                   10841: }
                   10842: 
1.31      www      10843: # ------------------------------------------------------------- Declutters URLs
                   10844: 
                   10845: sub declutter {
                   10846:     my $thisfn=shift;
1.569     albertel 10847:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10848:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10849:     $thisfn=~s/^\///;
1.697     albertel 10850:     $thisfn=~s|^adm/wrapper/||;
                   10851:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10852:     $thisfn=~s/^res\///;
1.1172    bisitz   10853:     $thisfn=~s/^priv\///;
1.1032    raeburn  10854:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10855:         $thisfn=~s/\?.+$//;
                   10856:     }
1.268     www      10857:     return $thisfn;
                   10858: }
                   10859: 
                   10860: # ------------------------------------------------------------- Clutter up URLs
                   10861: 
                   10862: sub clutter {
                   10863:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10864:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10865: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10866:        $thisfn='/res'.$thisfn; 
                   10867:     }
1.1031    raeburn  10868:     if ($thisfn !~m|^/adm|) {
                   10869: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10870: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10871: 	} else {
                   10872: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10873: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10874: 	    if ($embstyle eq 'ssi'
                   10875: 		|| ($embstyle eq 'hdn')
                   10876: 		|| ($embstyle eq 'rat')
                   10877: 		|| ($embstyle eq 'prv')
                   10878: 		|| ($embstyle eq 'ign')) {
                   10879: 		#do nothing with these
                   10880: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10881: 		|| ($embstyle eq 'emb')
                   10882: 		|| ($embstyle eq 'wrp')) {
                   10883: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10884: 	    } elsif ($embstyle eq 'unk'
                   10885: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10886: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10887: 	    } else {
1.718     www      10888: #		&logthis("Got a blank emb style");
1.695     albertel 10889: 	    }
1.694     albertel 10890: 	}
                   10891:     }
1.31      www      10892:     return $thisfn;
1.12      www      10893: }
                   10894: 
1.787     albertel 10895: sub clutter_with_no_wrapper {
                   10896:     my $uri = &clutter(shift);
                   10897:     if ($uri =~ m-^/adm/-) {
                   10898: 	$uri =~ s-^/adm/wrapper/-/-;
                   10899: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10900:     }
                   10901:     return $uri;
                   10902: }
                   10903: 
1.557     albertel 10904: sub freeze_escape {
                   10905:     my ($value)=@_;
                   10906:     if (ref($value)) {
                   10907: 	$value=&nfreeze($value);
                   10908: 	return '__FROZEN__'.&escape($value);
                   10909:     }
                   10910:     return &escape($value);
                   10911: }
                   10912: 
1.11      www      10913: 
1.557     albertel 10914: sub thaw_unescape {
                   10915:     my ($value)=@_;
                   10916:     if ($value =~ /^__FROZEN__/) {
                   10917: 	substr($value,0,10,undef);
                   10918: 	$value=&unescape($value);
                   10919: 	return &thaw($value);
                   10920:     }
                   10921:     return &unescape($value);
                   10922: }
                   10923: 
1.436     albertel 10924: sub correct_line_ends {
                   10925:     my ($result)=@_;
                   10926:     $$result =~s/\r\n/\n/mg;
                   10927:     $$result =~s/\r/\n/mg;
1.415     albertel 10928: }
1.1       albertel 10929: # ================================================================ Main Program
                   10930: 
1.184     www      10931: sub goodbye {
1.204     albertel 10932:    &logthis("Starting Shut down");
1.443     albertel 10933: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10934:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10935: #converted
1.599     albertel 10936: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10937:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10938: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10939: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10940: #1.1 only
1.870     albertel 10941: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10942: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10943: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10944: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10945:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10946:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10947:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10948:    &flushcourselogs();
                   10949:    &logthis("Shutting down");
                   10950: }
                   10951: 
1.852     albertel 10952: sub get_dns {
1.869     albertel 10953:     my ($url,$func,$ignore_cache) = @_;
                   10954:     if (!$ignore_cache) {
                   10955: 	my ($content,$cached)=
                   10956: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10957: 	if ($cached) {
                   10958: 	    &$func($content);
                   10959: 	    return;
                   10960: 	}
                   10961:     }
                   10962: 
                   10963:     my %alldns;
1.852     albertel 10964:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10965:     foreach my $dns (<$config>) {
                   10966: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10967:         my $line = $1;
                   10968:         my ($host,$protocol) = split(/:/,$line);
                   10969:         if ($protocol ne 'https') {
                   10970:             $protocol = 'http';
                   10971:         }
                   10972: 	$alldns{$host} = $protocol;
1.869     albertel 10973:     }
                   10974:     while (%alldns) {
                   10975: 	my ($dns) = keys(%alldns);
1.852     albertel 10976: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10977:         $ua->timeout(30);
1.979     raeburn  10978: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10979: 	my $response=$ua->request($request);
1.979     raeburn  10980:         delete($alldns{$dns});
1.852     albertel 10981: 	next if ($response->is_error());
                   10982: 	my @content = split("\n",$response->content);
1.869     albertel 10983: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10984: 	&$func(\@content);
1.869     albertel 10985: 	return;
1.852     albertel 10986:     }
                   10987:     close($config);
1.871     albertel 10988:     my $which = (split('/',$url))[3];
                   10989:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10990:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10991:     my @content = <$config>;
                   10992:     &$func(\@content);
                   10993:     return;
1.852     albertel 10994: }
1.327     albertel 10995: # ------------------------------------------------------------ Read domain file
                   10996: {
1.852     albertel 10997:     my $loaded;
1.846     albertel 10998:     my %domain;
                   10999: 
1.852     albertel 11000:     sub parse_domain_tab {
                   11001: 	my ($lines) = @_;
                   11002: 	foreach my $line (@$lines) {
                   11003: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      11004: 
1.846     albertel 11005: 	    chomp($line);
1.852     albertel 11006: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 11007: 	    my %this_domain;
                   11008: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   11009: 			       'lang_def', 'city', 'longi', 'lati',
                   11010: 			       'primary') {
                   11011: 		$this_domain{$field} = shift(@elements);
                   11012: 	    }
                   11013: 	    $domain{$name} = \%this_domain;
1.852     albertel 11014: 	}
                   11015:     }
1.864     albertel 11016: 
                   11017:     sub reset_domain_info {
                   11018: 	undef($loaded);
                   11019: 	undef(%domain);
                   11020:     }
                   11021: 
1.852     albertel 11022:     sub load_domain_tab {
1.869     albertel 11023: 	my ($ignore_cache) = @_;
                   11024: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 11025: 	my $fh;
                   11026: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   11027: 	    my @lines = <$fh>;
                   11028: 	    &parse_domain_tab(\@lines);
1.448     albertel 11029: 	}
1.852     albertel 11030: 	close($fh);
                   11031: 	$loaded = 1;
1.327     albertel 11032:     }
1.846     albertel 11033: 
                   11034:     sub domain {
1.852     albertel 11035: 	&load_domain_tab() if (!$loaded);
                   11036: 
1.846     albertel 11037: 	my ($name,$what) = @_;
                   11038: 	return if ( !exists($domain{$name}) );
                   11039: 
                   11040: 	if (!$what) {
                   11041: 	    return $domain{$name}{'description'};
                   11042: 	}
                   11043: 	return $domain{$name}{$what};
                   11044:     }
1.974     raeburn  11045: 
                   11046:     sub domain_info {
                   11047:         &load_domain_tab() if (!$loaded);
                   11048:         return %domain;
                   11049:     }
                   11050: 
1.327     albertel 11051: }
                   11052: 
                   11053: 
1.1       albertel 11054: # ------------------------------------------------------------- Read hosts file
                   11055: {
1.838     albertel 11056:     my %hostname;
1.844     albertel 11057:     my %hostdom;
1.845     albertel 11058:     my %libserv;
1.852     albertel 11059:     my $loaded;
1.888     albertel 11060:     my %name_to_host;
1.1074    raeburn  11061:     my %internetdom;
1.1107    raeburn  11062:     my %LC_dns_serv;
1.852     albertel 11063: 
                   11064:     sub parse_hosts_tab {
                   11065: 	my ($file) = @_;
                   11066: 	foreach my $configline (@$file) {
                   11067: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  11068:             chomp($configline);
                   11069: 	    if ($configline =~ /^\^/) {
                   11070:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   11071:                     $LC_dns_serv{$1} = 1;
                   11072:                 }
                   11073:                 next;
                   11074:             }
1.1074    raeburn  11075: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 11076: 	    $name=~s/\s//g;
                   11077: 	    if ($id && $domain && $role && $name) {
                   11078: 		$hostname{$id}=$name;
1.888     albertel 11079: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 11080: 		$hostdom{$id}=$domain;
                   11081: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  11082:                 if (defined($protocol)) {
                   11083:                     if ($protocol eq 'https') {
                   11084:                         $protocol{$id} = $protocol;
                   11085:                     } else {
                   11086:                         $protocol{$id} = 'http'; 
                   11087:                     }
1.968     raeburn  11088:                 } else {
1.969     raeburn  11089:                     $protocol{$id} = 'http';
1.968     raeburn  11090:                 }
1.1074    raeburn  11091:                 if (defined($intdom)) {
                   11092:                     $internetdom{$id} = $intdom;
                   11093:                 }
1.852     albertel 11094: 	    }
                   11095: 	}
                   11096:     }
1.864     albertel 11097:     
                   11098:     sub reset_hosts_info {
1.897     albertel 11099: 	&purge_remembered();
1.864     albertel 11100: 	&reset_domain_info();
                   11101: 	&reset_hosts_ip_info();
1.892     albertel 11102: 	undef(%name_to_host);
1.864     albertel 11103: 	undef(%hostname);
                   11104: 	undef(%hostdom);
                   11105: 	undef(%libserv);
                   11106: 	undef($loaded);
                   11107:     }
1.1       albertel 11108: 
1.852     albertel 11109:     sub load_hosts_tab {
1.869     albertel 11110: 	my ($ignore_cache) = @_;
                   11111: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11112: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11113: 	my @config = <$config>;
                   11114: 	&parse_hosts_tab(\@config);
                   11115: 	close($config);
                   11116: 	$loaded=1;
1.1       albertel 11117:     }
1.852     albertel 11118: 
1.838     albertel 11119:     sub hostname {
1.852     albertel 11120: 	&load_hosts_tab() if (!$loaded);
                   11121: 
1.838     albertel 11122: 	my ($lonid) = @_;
                   11123: 	return $hostname{$lonid};
                   11124:     }
1.845     albertel 11125: 
1.838     albertel 11126:     sub all_hostnames {
1.852     albertel 11127: 	&load_hosts_tab() if (!$loaded);
                   11128: 
1.838     albertel 11129: 	return %hostname;
                   11130:     }
1.845     albertel 11131: 
1.888     albertel 11132:     sub all_names {
                   11133: 	&load_hosts_tab() if (!$loaded);
                   11134: 
                   11135: 	return %name_to_host;
                   11136:     }
                   11137: 
1.974     raeburn  11138:     sub all_host_domain {
                   11139:         &load_hosts_tab() if (!$loaded);
                   11140:         return %hostdom;
                   11141:     }
                   11142: 
1.845     albertel 11143:     sub is_library {
1.852     albertel 11144: 	&load_hosts_tab() if (!$loaded);
                   11145: 
1.845     albertel 11146: 	return exists($libserv{$_[0]});
                   11147:     }
                   11148: 
                   11149:     sub all_library {
1.852     albertel 11150: 	&load_hosts_tab() if (!$loaded);
                   11151: 
1.845     albertel 11152: 	return %libserv;
                   11153:     }
                   11154: 
1.1062    droeschl 11155:     sub unique_library {
                   11156: 	#2x reverse removes all hostnames that appear more than once
                   11157:         my %unique = reverse &all_library();
                   11158:         return reverse %unique;
                   11159:     }
                   11160: 
1.841     albertel 11161:     sub get_servers {
1.852     albertel 11162: 	&load_hosts_tab() if (!$loaded);
                   11163: 
1.841     albertel 11164: 	my ($domain,$type) = @_;
                   11165: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11166: 	                                          : %hostname;
                   11167: 	my %result;
1.842     albertel 11168: 	if (ref($domain) eq 'ARRAY') {
                   11169: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11170: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11171: 		    $result{$host} = $hostname;
                   11172: 		}
                   11173: 	    }
                   11174: 	} else {
                   11175: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11176: 		if ($hostdom{$host} eq $domain) {
                   11177: 		    $result{$host} = $hostname;
                   11178: 		}
1.841     albertel 11179: 	    }
                   11180: 	}
                   11181: 	return %result;
                   11182:     }
1.845     albertel 11183: 
1.1062    droeschl 11184:     sub get_unique_servers {
                   11185:         my %unique = reverse &get_servers(@_);
                   11186: 	return reverse %unique;
                   11187:     }
                   11188: 
1.844     albertel 11189:     sub host_domain {
1.852     albertel 11190: 	&load_hosts_tab() if (!$loaded);
                   11191: 
1.844     albertel 11192: 	my ($lonid) = @_;
                   11193: 	return $hostdom{$lonid};
                   11194:     }
                   11195: 
1.841     albertel 11196:     sub all_domains {
1.852     albertel 11197: 	&load_hosts_tab() if (!$loaded);
                   11198: 
1.841     albertel 11199: 	my %seen;
                   11200: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11201: 	return @uniq;
                   11202:     }
1.1074    raeburn  11203: 
                   11204:     sub internet_dom {
                   11205:         &load_hosts_tab() if (!$loaded);
                   11206: 
                   11207:         my ($lonid) = @_;
                   11208:         return $internetdom{$lonid};
                   11209:     }
1.1107    raeburn  11210: 
                   11211:     sub is_LC_dns {
                   11212:         &load_hosts_tab() if (!$loaded);
                   11213: 
                   11214:         my ($hostname) = @_;
                   11215:         return exists($LC_dns_serv{$hostname});
                   11216:     }
                   11217: 
1.1       albertel 11218: }
                   11219: 
1.847     albertel 11220: { 
                   11221:     my %iphost;
1.856     albertel 11222:     my %name_to_ip;
                   11223:     my %lonid_to_ip;
1.869     albertel 11224: 
1.847     albertel 11225:     sub get_hosts_from_ip {
                   11226: 	my ($ip) = @_;
                   11227: 	my %iphosts = &get_iphost();
                   11228: 	if (ref($iphosts{$ip})) {
                   11229: 	    return @{$iphosts{$ip}};
                   11230: 	}
                   11231: 	return;
1.839     albertel 11232:     }
1.864     albertel 11233:     
                   11234:     sub reset_hosts_ip_info {
                   11235: 	undef(%iphost);
                   11236: 	undef(%name_to_ip);
                   11237: 	undef(%lonid_to_ip);
                   11238:     }
1.856     albertel 11239: 
                   11240:     sub get_host_ip {
                   11241: 	my ($lonid) = @_;
                   11242: 	if (exists($lonid_to_ip{$lonid})) {
                   11243: 	    return $lonid_to_ip{$lonid};
                   11244: 	}
                   11245: 	my $name=&hostname($lonid);
                   11246:    	my $ip = gethostbyname($name);
                   11247: 	return if (!$ip || length($ip) ne 4);
                   11248: 	$ip=inet_ntoa($ip);
                   11249: 	$name_to_ip{$name}   = $ip;
                   11250: 	$lonid_to_ip{$lonid} = $ip;
                   11251: 	return $ip;
                   11252:     }
1.847     albertel 11253:     
                   11254:     sub get_iphost {
1.869     albertel 11255: 	my ($ignore_cache) = @_;
1.894     albertel 11256: 
1.869     albertel 11257: 	if (!$ignore_cache) {
                   11258: 	    if (%iphost) {
                   11259: 		return %iphost;
                   11260: 	    }
                   11261: 	    my ($ip_info,$cached)=
                   11262: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11263: 	    if ($cached) {
                   11264: 		%iphost      = %{$ip_info->[0]};
                   11265: 		%name_to_ip  = %{$ip_info->[1]};
                   11266: 		%lonid_to_ip = %{$ip_info->[2]};
                   11267: 		return %iphost;
                   11268: 	    }
                   11269: 	}
1.894     albertel 11270: 
                   11271: 	# get yesterday's info for fallback
                   11272: 	my %old_name_to_ip;
                   11273: 	my ($ip_info,$cached)=
                   11274: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11275: 	if ($cached) {
                   11276: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11277: 	}
                   11278: 
1.888     albertel 11279: 	my %name_to_host = &all_names();
                   11280: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11281: 	    my $ip;
                   11282: 	    if (!exists($name_to_ip{$name})) {
                   11283: 		$ip = gethostbyname($name);
                   11284: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11285: 		    if (defined($old_name_to_ip{$name})) {
                   11286: 			$ip = $old_name_to_ip{$name};
                   11287: 			&logthis("Can't find $name defaulting to old $ip");
                   11288: 		    } else {
                   11289: 			&logthis("Name $name no IP found");
                   11290: 			next;
                   11291: 		    }
                   11292: 		} else {
                   11293: 		    $ip=inet_ntoa($ip);
1.847     albertel 11294: 		}
                   11295: 		$name_to_ip{$name} = $ip;
                   11296: 	    } else {
                   11297: 		$ip = $name_to_ip{$name};
1.653     albertel 11298: 	    }
1.888     albertel 11299: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11300: 		$lonid_to_ip{$id} = $ip;
                   11301: 	    }
                   11302: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11303: 	}
1.869     albertel 11304: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11305: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11306: 				      48*60*60);
1.869     albertel 11307: 
1.847     albertel 11308: 	return %iphost;
1.598     albertel 11309:     }
                   11310: 
1.992     raeburn  11311:     #
                   11312:     #  Given a DNS returns the loncapa host name for that DNS 
                   11313:     # 
                   11314:     sub host_from_dns {
                   11315:         my ($dns) = @_;
                   11316:         my @hosts;
                   11317:         my $ip;
                   11318: 
1.993     raeburn  11319:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11320:             $ip = $name_to_ip{$dns};
                   11321:         }
                   11322:         if (!$ip) {
                   11323:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11324:             if (length($ip) == 4) { 
                   11325: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11326:             }
                   11327:         }
                   11328:         if ($ip) {
                   11329: 	    @hosts = get_hosts_from_ip($ip);
                   11330: 	    return $hosts[0];
                   11331:         }
                   11332:         return undef;
1.986     foxr     11333:     }
1.992     raeburn  11334: 
1.1074    raeburn  11335:     sub get_internet_names {
                   11336:         my ($lonid) = @_;
                   11337:         return if ($lonid eq '');
                   11338:         my ($idnref,$cached)=
                   11339:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11340:         if ($cached) {
                   11341:             return $idnref;
                   11342:         }
                   11343:         my $ip = &get_host_ip($lonid);
                   11344:         my @hosts = &get_hosts_from_ip($ip);
                   11345:         my %iphost = &get_iphost();
                   11346:         my (@idns,%seen);
                   11347:         foreach my $id (@hosts) {
                   11348:             my $dom = &host_domain($id);
                   11349:             my $prim_id = &domain($dom,'primary');
                   11350:             my $prim_ip = &get_host_ip($prim_id);
                   11351:             next if ($seen{$prim_ip});
                   11352:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11353:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11354:                     my $intdom = &internet_dom($id);
                   11355:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11356:                         push(@idns,$intdom);
                   11357:                     }
                   11358:                 }
                   11359:             }
                   11360:             $seen{$prim_ip} = 1;
                   11361:         }
                   11362:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11363:     }
                   11364: 
1.986     foxr     11365: }
                   11366: 
1.1079    raeburn  11367: sub all_loncaparevs {
                   11368:     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);
                   11369: }
                   11370: 
1.862     albertel 11371: BEGIN {
                   11372: 
                   11373: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11374:     unless ($readit) {
                   11375: {
                   11376:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11377:     %perlvar = (%perlvar,%{$configvars});
                   11378: }
                   11379: 
                   11380: 
1.1       albertel 11381: # ------------------------------------------------------ Read spare server file
                   11382: {
1.448     albertel 11383:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11384: 
                   11385:     while (my $configline=<$config>) {
                   11386:        chomp($configline);
1.284     matthew  11387:        if ($configline) {
1.784     albertel 11388: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11389: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11390: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11391:        }
                   11392:     }
1.448     albertel 11393:     close($config);
1.1       albertel 11394: }
1.11      www      11395: # ------------------------------------------------------------ Read permissions
                   11396: {
1.448     albertel 11397:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11398: 
                   11399:     while (my $configline=<$config>) {
1.448     albertel 11400: 	chomp($configline);
                   11401: 	if ($configline) {
                   11402: 	    my ($role,$perm)=split(/ /,$configline);
                   11403: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11404: 	}
1.11      www      11405:     }
1.448     albertel 11406:     close($config);
1.11      www      11407: }
                   11408: 
                   11409: # -------------------------------------------- Read plain texts for permissions
                   11410: {
1.448     albertel 11411:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11412: 
                   11413:     while (my $configline=<$config>) {
1.448     albertel 11414: 	chomp($configline);
                   11415: 	if ($configline) {
1.742     raeburn  11416: 	    my ($short,@plain)=split(/:/,$configline);
                   11417:             %{$prp{$short}} = ();
                   11418: 	    if (@plain > 0) {
                   11419:                 $prp{$short}{'std'} = $plain[0];
                   11420:                 for (my $i=1; $i<@plain; $i++) {
                   11421:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11422:                 }
                   11423:             }
1.448     albertel 11424: 	}
1.135     www      11425:     }
1.448     albertel 11426:     close($config);
1.135     www      11427: }
                   11428: 
                   11429: # ---------------------------------------------------------- Read package table
                   11430: {
1.448     albertel 11431:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11432: 
                   11433:     while (my $configline=<$config>) {
1.483     albertel 11434: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11435: 	chomp($configline);
                   11436: 	my ($short,$plain)=split(/:/,$configline);
                   11437: 	my ($pack,$name)=split(/\&/,$short);
                   11438: 	if ($plain ne '') {
                   11439: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11440: 	    $packagetab{$short}=$plain; 
                   11441: 	}
1.11      www      11442:     }
1.448     albertel 11443:     close($config);
1.329     matthew  11444: }
                   11445: 
1.1073    raeburn  11446: # ---------------------------------------------------------- Read loncaparev table
                   11447: {
                   11448:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11449:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11450:             while (my $configline=<$config>) {
                   11451:                 chomp($configline);
                   11452:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11453:                 $loncaparevs{$hostid}=$loncaparev;
                   11454:             }
                   11455:             close($config);
                   11456:         }
                   11457:     }
                   11458: }
                   11459: 
1.1074    raeburn  11460: # ---------------------------------------------------------- Read serverhostID table
                   11461: {
                   11462:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11463:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11464:             while (my $configline=<$config>) {
                   11465:                 chomp($configline);
                   11466:                 my ($name,$id)=split(/:/,$configline);
                   11467:                 $serverhomeIDs{$name}=$id;
                   11468:             }
                   11469:             close($config);
                   11470:         }
                   11471:     }
                   11472: }
                   11473: 
1.1079    raeburn  11474: {
                   11475:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11476:     if (-e $file) {
                   11477:         my $parser = HTML::LCParser->new($file);
                   11478:         while (my $token = $parser->get_token()) {
                   11479:             if ($token->[0] eq 'S') {
                   11480:                 my $item = $token->[1];
                   11481:                 my $name = $token->[2]{'name'};
                   11482:                 my $value = $token->[2]{'value'};
                   11483:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11484:                     my $release = $parser->get_text();
                   11485:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11486:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11487:                 }
                   11488:             }
                   11489:         }
                   11490:     }
1.1073    raeburn  11491: }
                   11492: 
1.1138    raeburn  11493: # ---------------------------------------------------------- Read managers table
                   11494: {
                   11495:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11496:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11497:             while (my $configline=<$config>) {
                   11498:                 chomp($configline);
                   11499:                 next if ($configline =~ /^\#/);
                   11500:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11501:                     $managerstab{$configline} = 1;
                   11502:                 }
                   11503:             }
                   11504:             close($config);
                   11505:         }
                   11506:     }
                   11507: }
                   11508: 
1.329     matthew  11509: # ------------- set up temporary directory
                   11510: {
1.1117    foxr     11511:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11512: 
1.11      www      11513: }
                   11514: 
1.794     albertel 11515: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11516: 				'compress_threshold'=> 20_000,
                   11517:  			        });
1.185     www      11518: 
1.281     www      11519: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11520: $dumpcount=0;
1.958     www      11521: $locknum=0;
1.22      www      11522: 
1.163     harris41 11523: &logtouch();
1.672     albertel 11524: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11525: $readit=1;
1.564     albertel 11526:     {
                   11527: 	use integer;
                   11528: 	my $test=(2**32)+1;
1.568     albertel 11529: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11530: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11531:     }
1.195     www      11532: }
1.1       albertel 11533: }
1.179     www      11534: 
1.1       albertel 11535: 1;
1.191     harris41 11536: __END__
                   11537: 
1.243     albertel 11538: =pod
                   11539: 
1.191     harris41 11540: =head1 NAME
                   11541: 
1.243     albertel 11542: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11543: 
                   11544: =head1 SYNOPSIS
                   11545: 
1.243     albertel 11546: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11547: 
                   11548:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11549: 
1.243     albertel 11550: Common parameters:
                   11551: 
                   11552: =over 4
                   11553: 
                   11554: =item *
                   11555: 
                   11556: $uname : an internal username (if $cname expecting a course Id specifically)
                   11557: 
                   11558: =item *
                   11559: 
                   11560: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11561: 
                   11562: =item *
                   11563: 
                   11564: $symb : a resource instance identifier
                   11565: 
                   11566: =item *
                   11567: 
                   11568: $namespace : the name of a .db file that contains the data needed or
                   11569: being set.
                   11570: 
                   11571: =back
                   11572: 
1.394     bowersj2 11573: =head1 OVERVIEW
1.191     harris41 11574: 
1.394     bowersj2 11575: lonnet provides subroutines which interact with the
                   11576: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11577: about classes, users, and resources.
1.243     albertel 11578: 
                   11579: For many of these objects you can also use this to store data about
                   11580: them or modify them in various ways.
1.191     harris41 11581: 
1.394     bowersj2 11582: =head2 Symbs
1.191     harris41 11583: 
1.394     bowersj2 11584: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11585: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11586: map, the resource number of the resource in the map, and the URL of
                   11587: the resource itself. The latter is somewhat redundant, but might help
                   11588: if maps change.
                   11589: 
                   11590: An example is
                   11591: 
                   11592:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11593: 
                   11594: The respective map entry is
                   11595: 
                   11596:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11597:   title="Problem 2">
                   11598:  </resource>
                   11599: 
                   11600: Symbs are used by the random number generator, as well as to store and
                   11601: restore data specific to a certain instance of for example a problem.
                   11602: 
                   11603: =head2 Storing And Retrieving Data
                   11604: 
                   11605: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11606: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11607: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11608: is is the non-critical message twin of cstore. These functions are for
                   11609: handlers to store a perl hash to a user's permanent data space in an
                   11610: easy manner, and to retrieve it again on another call. It is expected
                   11611: that a handler would use this once at the beginning to retrieve data,
                   11612: and then again once at the end to send only the new data back.
                   11613: 
                   11614: The data is stored in the user's data directory on the user's
                   11615: homeserver under the ID of the course.
                   11616: 
                   11617: The hash that is returned by restore will have all of the previous
                   11618: value for all of the elements of the hash.
                   11619: 
                   11620: Example:
                   11621: 
                   11622:  #creating a hash
                   11623:  my %hash;
                   11624:  $hash{'foo'}='bar';
                   11625: 
                   11626:  #storing it
                   11627:  &Apache::lonnet::cstore(\%hash);
                   11628: 
                   11629:  #changing a value
                   11630:  $hash{'foo'}='notbar';
                   11631: 
                   11632:  #adding a new value
                   11633:  $hash{'bar'}='foo';
                   11634:  &Apache::lonnet::cstore(\%hash);
                   11635: 
                   11636:  #retrieving the hash
                   11637:  my %history=&Apache::lonnet::restore();
                   11638: 
                   11639:  #print the hash
                   11640:  foreach my $key (sort(keys(%history))) {
                   11641:    print("\%history{$key} = $history{$key}");
                   11642:  }
                   11643: 
                   11644: Will print out:
1.191     harris41 11645: 
1.394     bowersj2 11646:  %history{1:foo} = bar
                   11647:  %history{1:keys} = foo:timestamp
                   11648:  %history{1:timestamp} = 990455579
                   11649:  %history{2:bar} = foo
                   11650:  %history{2:foo} = notbar
                   11651:  %history{2:keys} = foo:bar:timestamp
                   11652:  %history{2:timestamp} = 990455580
                   11653:  %history{bar} = foo
                   11654:  %history{foo} = notbar
                   11655:  %history{timestamp} = 990455580
                   11656:  %history{version} = 2
                   11657: 
                   11658: Note that the special hash entries C<keys>, C<version> and
                   11659: C<timestamp> were added to the hash. C<version> will be equal to the
                   11660: total number of versions of the data that have been stored. The
                   11661: C<timestamp> attribute will be the UNIX time the hash was
                   11662: stored. C<keys> is available in every historical section to list which
                   11663: keys were added or changed at a specific historical revision of a
                   11664: hash.
                   11665: 
                   11666: B<Warning>: do not store the hash that restore returns directly. This
                   11667: will cause a mess since it will restore the historical keys as if the
                   11668: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11669: 
1.394     bowersj2 11670: Calling convention:
1.191     harris41 11671: 
1.394     bowersj2 11672:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11673:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11674: 
1.394     bowersj2 11675: For more detailed information, see lonnet specific documentation.
1.191     harris41 11676: 
1.394     bowersj2 11677: =head1 RETURN MESSAGES
1.191     harris41 11678: 
1.394     bowersj2 11679: =over 4
1.191     harris41 11680: 
1.394     bowersj2 11681: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11682: 
1.394     bowersj2 11683: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11684: when the connection is brought back up
1.191     harris41 11685: 
1.394     bowersj2 11686: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11687: for later delivery
1.191     harris41 11688: 
1.967     bisitz   11689: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11690: 
1.394     bowersj2 11691: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11692: that was requested
1.191     harris41 11693: 
1.243     albertel 11694: =back
1.191     harris41 11695: 
1.243     albertel 11696: =head1 PUBLIC SUBROUTINES
1.191     harris41 11697: 
1.243     albertel 11698: =head2 Session Environment Functions
1.191     harris41 11699: 
1.243     albertel 11700: =over 4
1.191     harris41 11701: 
1.394     bowersj2 11702: =item * 
                   11703: X<appenv()>
1.949     raeburn  11704: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11705: the user envirnoment file, and will be restored for each access this
1.620     albertel 11706: user makes during this session, also modifies the %env for the current
1.949     raeburn  11707: process. Optional rolesarrayref - if defined contains a reference to an array
                   11708: of roles which are exempt from the restriction on modifying user.role entries 
                   11709: in the user's environment.db and in %env.    
1.191     harris41 11710: 
                   11711: =item *
1.394     bowersj2 11712: X<delenv()>
1.987     raeburn  11713: B<delenv($delthis,$regexp)>: removes all items from the session
                   11714: environment file that begin with $delthis. If the 
                   11715: optional second arg - $regexp - is true, $delthis is treated as a 
                   11716: regular expression, otherwise \Q$delthis\E is used. 
                   11717: The values are also deleted from the current processes %env.
1.191     harris41 11718: 
1.795     albertel 11719: =item * get_env_multiple($name) 
                   11720: 
                   11721: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11722: values may be defined and end up as an array ref.
                   11723: 
                   11724: returns an array of values
                   11725: 
1.243     albertel 11726: =back
                   11727: 
                   11728: =head2 User Information
1.191     harris41 11729: 
1.243     albertel 11730: =over 4
1.191     harris41 11731: 
                   11732: =item *
1.394     bowersj2 11733: X<queryauthenticate()>
                   11734: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11735: authentication scheme
                   11736: 
                   11737: =item *
1.394     bowersj2 11738: X<authenticate()>
1.1073    raeburn  11739: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11740: authenticate user from domain's lib servers (first use the current
                   11741: one). C<$upass> should be the users password.
1.1073    raeburn  11742: $checkdefauth is optional (value is 1 if a check should be made to
                   11743:    authenticate user using default authentication method, and allow
                   11744:    account creation if username does not have account in the domain).
                   11745: $clientcancheckhost is optional (value is 1 if checking whether the
                   11746:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11747: 
                   11748: =item *
1.394     bowersj2 11749: X<homeserver()>
                   11750: B<homeserver($uname,$udom)>: find the server which has
                   11751: the user's directory and files (there must be only one), this caches
                   11752: the answer, and also caches if there is a borken connection.
1.191     harris41 11753: 
                   11754: =item *
1.394     bowersj2 11755: X<idget()>
                   11756: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11757: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11758: username, and only 1 username per ID in a specific domain) (returns
                   11759: hash: id=>name,id=>name)
1.191     harris41 11760: 
                   11761: =item *
1.394     bowersj2 11762: X<idrget()>
                   11763: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11764: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11765: 
                   11766: =item *
1.394     bowersj2 11767: X<idput()>
                   11768: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11769: 
                   11770: =item *
1.394     bowersj2 11771: X<rolesinit()>
1.1169    droeschl 11772: B<rolesinit($udom,$username)>: get user privileges.
                   11773: returns user role, first access and timer interval hashes
1.243     albertel 11774: 
                   11775: =item *
1.1171    droeschl 11776: X<privileged()>
                   11777: B<privileged($username,$domain)>: returns a true if user has a
                   11778: privileged and active role (i.e. su or dc), false otherwise.
                   11779: 
                   11780: =item *
1.551     albertel 11781: X<getsection()>
                   11782: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11783: course $cname, return section name/number or '' for "not in course"
                   11784: and '-1' for "no section"
                   11785: 
                   11786: =item *
1.394     bowersj2 11787: X<userenvironment()>
                   11788: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11789: passed in @what from the requested user's environment, returns a hash
                   11790: 
1.858     raeburn  11791: =item * 
                   11792: X<userlog_query()>
1.859     albertel 11793: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11794: activity.log file. %filters defines filters applied when parsing the
                   11795: log file. These can be start or end timestamps, or the type of action
                   11796: - log to look for Login or Logout events, check for Checkin or
                   11797: Checkout, role for role selection. The response is in the form
                   11798: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11799: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11800: 
1.243     albertel 11801: =back
                   11802: 
                   11803: =head2 User Roles
                   11804: 
                   11805: =over 4
                   11806: 
                   11807: =item *
                   11808: 
1.810     raeburn  11809: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11810:  F: full access
                   11811:  U,I,K: authentication modes (cxx only)
                   11812:  '': forbidden
                   11813:  1: user needs to choose course
                   11814:  2: browse allowed
1.766     albertel 11815:  A: passphrase authentication needed
1.243     albertel 11816: 
                   11817: =item *
                   11818: 
                   11819: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11820: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11821: and course level
                   11822: 
                   11823: =item *
                   11824: 
1.988     raeburn  11825: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11826: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11827: $type is Course (default) or Community.
1.988     raeburn  11828: If $forcedefault evaluates to true, text returned will be default 
                   11829: text for $type. Otherwise, if this is a course, the text returned 
                   11830: will be a custom name for the role (if defined in the course's 
                   11831: environment).  If no custom name is defined the default is returned.
                   11832:    
1.832     raeburn  11833: =item *
                   11834: 
1.935     raeburn  11835: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11836: All arguments are optional. Returns a hash of a roles, either for
                   11837: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11838: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11839: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11840: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11841: For each key, value is set to colon-separated start and end times for
                   11842: the role.  If no username and domain are specified, will default to
1.934     raeburn  11843: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11844: of role statuses (active, future or previous), roles 
                   11845: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11846: to restrict the list of roles reported. If no array ref is 
                   11847: provided for types, will default to return only active roles.
1.834     albertel 11848: 
1.243     albertel 11849: =back
                   11850: 
                   11851: =head2 User Modification
                   11852: 
                   11853: =over 4
                   11854: 
                   11855: =item *
                   11856: 
1.957     raeburn  11857: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11858: user for the level given by URL.  Optional start and end dates (leave empty
                   11859: string or zero for "no date")
1.191     harris41 11860: 
                   11861: =item *
                   11862: 
1.243     albertel 11863: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11864: change a users, password, possible return values are: ok,
                   11865: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11866: refused
1.191     harris41 11867: 
                   11868: =item *
                   11869: 
1.243     albertel 11870: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11871: 
                   11872: =item *
                   11873: 
1.1058    raeburn  11874: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11875:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11876: 
                   11877: will update user information (firstname,middlename,lastname,generation,
                   11878: permanentemail), and if forceid is true, student/employee ID also.
                   11879: A user's institutional affiliation(s) can also be updated.
                   11880: User information fields will not be overwritten with empty entries 
                   11881: unless the field is included in the $candelete array reference.
                   11882: This array is included when a single user is modified via "Manage Users",
                   11883: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11884: 
                   11885: =item *
                   11886: 
1.286     matthew  11887: modifystudent
                   11888: 
1.957     raeburn  11889: modify a student's enrollment and identification information.
1.286     matthew  11890: The course id is resolved based on the current users environment.  
                   11891: This means the envoking user must be a course coordinator or otherwise
                   11892: associated with a course.
                   11893: 
1.297     matthew  11894: This call is essentially a wrapper for lonnet::modifyuser and
                   11895: lonnet::modify_student_enrollment
1.286     matthew  11896: 
                   11897: Inputs: 
                   11898: 
                   11899: =over 4
                   11900: 
1.957     raeburn  11901: =item B<$udom> Student's loncapa domain
1.286     matthew  11902: 
1.957     raeburn  11903: =item B<$uname> Student's loncapa login name
1.286     matthew  11904: 
1.964     bisitz   11905: =item B<$uid> Student/Employee ID
1.286     matthew  11906: 
1.957     raeburn  11907: =item B<$umode> Student's authentication mode
1.286     matthew  11908: 
1.957     raeburn  11909: =item B<$upass> Student's password
1.286     matthew  11910: 
1.957     raeburn  11911: =item B<$first> Student's first name
1.286     matthew  11912: 
1.957     raeburn  11913: =item B<$middle> Student's middle name
1.286     matthew  11914: 
1.957     raeburn  11915: =item B<$last> Student's last name
1.286     matthew  11916: 
1.957     raeburn  11917: =item B<$gene> Student's generation
1.286     matthew  11918: 
1.957     raeburn  11919: =item B<$usec> Student's section in course
1.286     matthew  11920: 
                   11921: =item B<$end> Unix time of the roles expiration
                   11922: 
                   11923: =item B<$start> Unix time of the roles start date
                   11924: 
                   11925: =item B<$forceid> If defined, allow $uid to be changed
                   11926: 
                   11927: =item B<$desiredhome> server to use as home server for student
                   11928: 
1.957     raeburn  11929: =item B<$email> Student's permanent e-mail address
                   11930: 
                   11931: =item B<$type> Type of enrollment (auto or manual)
                   11932: 
1.963     raeburn  11933: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11934: 
                   11935: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11936: 
1.963     raeburn  11937: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11938: 
1.963     raeburn  11939: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11940: 
1.963     raeburn  11941: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11942: 
1.286     matthew  11943: =back
1.297     matthew  11944: 
                   11945: =item *
                   11946: 
                   11947: modify_student_enrollment
                   11948: 
                   11949: Change a students enrollment status in a class.  The environment variable
                   11950: 'role.request.course' must be defined for this function to proceed.
                   11951: 
                   11952: Inputs:
                   11953: 
                   11954: =over 4
                   11955: 
                   11956: =item $udom, students domain
                   11957: 
                   11958: =item $uname, students name
                   11959: 
                   11960: =item $uid, students user id
                   11961: 
                   11962: =item $first, students first name
                   11963: 
                   11964: =item $middle
                   11965: 
                   11966: =item $last
                   11967: 
                   11968: =item $gene
                   11969: 
                   11970: =item $usec
                   11971: 
                   11972: =item $end
                   11973: 
                   11974: =item $start
                   11975: 
1.957     raeburn  11976: =item $type
                   11977: 
                   11978: =item $locktype
                   11979: 
                   11980: =item $cid
                   11981: 
                   11982: =item $selfenroll
                   11983: 
                   11984: =item $context
                   11985: 
1.297     matthew  11986: =back
                   11987: 
1.191     harris41 11988: 
                   11989: =item *
                   11990: 
1.243     albertel 11991: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11992: custom role; give a custom role to a user for the level given by URL.  Specify
                   11993: name and domain of role author, and role name
1.191     harris41 11994: 
                   11995: =item *
                   11996: 
1.243     albertel 11997: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11998: 
                   11999: =item *
                   12000: 
1.243     albertel 12001: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   12002: 
                   12003: =back
                   12004: 
                   12005: =head2 Course Infomation
                   12006: 
                   12007: =over 4
1.191     harris41 12008: 
                   12009: =item *
                   12010: 
1.1118    foxr     12011: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 12012: specified course id, including all environment settings for the
                   12013: course, the description of the course will be in the hash under the
                   12014: key 'description'
1.191     harris41 12015: 
1.1118    foxr     12016: $options is an optional parameter that if supplied is a hash reference that controls
                   12017: what how this function works.  It has the following key/values:
                   12018: 
                   12019: =over 4
                   12020: 
                   12021: =item freshen_cache
                   12022: 
                   12023: If defined, and the environment cache for the course is valid, it is 
                   12024: returned in the returned hash.
                   12025: 
                   12026: =item one_time
                   12027: 
                   12028: If defined, the last cache time is set to _now_
                   12029: 
                   12030: =item user
                   12031: 
                   12032: If defined, the supplied username is used instead of the current user.
                   12033: 
                   12034: 
                   12035: =back
                   12036: 
1.191     harris41 12037: =item *
                   12038: 
1.624     albertel 12039: resdata($name,$domain,$type,@which) : request for current parameter
                   12040: setting for a specific $type, where $type is either 'course' or 'user',
                   12041: @what should be a list of parameters to ask about. This routine caches
                   12042: answers for 5 minutes.
1.243     albertel 12043: 
1.877     foxr     12044: =item *
                   12045: 
                   12046: get_courseresdata($courseid, $domain) : dump the entire course resource
                   12047: data base, returning a hash that is keyed by the resource name and has
                   12048: values that are the resource value.  I believe that the timestamps and
                   12049: versions are also returned.
                   12050: 
                   12051: 
1.243     albertel 12052: =back
                   12053: 
                   12054: =head2 Course Modification
                   12055: 
                   12056: =over 4
1.191     harris41 12057: 
                   12058: =item *
                   12059: 
1.243     albertel 12060: writecoursepref($courseid,%prefs) : write preferences (environment
                   12061: database) for a course
1.191     harris41 12062: 
                   12063: =item *
                   12064: 
1.1011    raeburn  12065: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   12066: 
                   12067: =item *
                   12068: 
1.1038    raeburn  12069: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 12070: 
1.1167    droeschl 12071: =item *
                   12072: 
                   12073: is_course($courseid), is_course($cdom, $cnum)
                   12074: 
                   12075: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   12076: two component version $cdom, $cnum. It checks if the specified course exists.
                   12077: 
                   12078: Returns:
                   12079:     undef if the course doesn't exist, otherwise
                   12080:     in scalar context the combined courseid.
                   12081:     in list context the two components of the course identifier, domain and 
                   12082:     courseid.    
                   12083: 
1.243     albertel 12084: =back
                   12085: 
                   12086: =head2 Resource Subroutines
                   12087: 
                   12088: =over 4
1.191     harris41 12089: 
                   12090: =item *
                   12091: 
1.243     albertel 12092: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12093: 
                   12094: =item *
                   12095: 
1.243     albertel 12096: repcopy($filename) : subscribes to the requested file, and attempts to
                   12097: replicate from the owning library server, Might return
1.607     raeburn  12098: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12099: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12100: resource. Expects the local filesystem pathname
                   12101: (/home/httpd/html/res/....)
                   12102: 
                   12103: =back
                   12104: 
                   12105: =head2 Resource Information
                   12106: 
                   12107: =over 4
1.191     harris41 12108: 
                   12109: =item *
                   12110: 
1.243     albertel 12111: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12112: a vairety of different possible values, $varname should be a request
                   12113: string, and the other parameters can be used to specify who and what
                   12114: one is asking about.
                   12115: 
                   12116: Possible values for $varname are environment.lastname (or other item
                   12117: from the envirnment hash), user.name (or someother aspect about the
                   12118: user), resource.0.maxtries (or some other part and parameter of a
                   12119: resource)
1.204     albertel 12120: 
                   12121: =item *
                   12122: 
1.243     albertel 12123: directcondval($number) : get current value of a condition; reads from a state
                   12124: string
1.204     albertel 12125: 
                   12126: =item *
                   12127: 
1.243     albertel 12128: condval($condidx) : value of condition index based on state
1.204     albertel 12129: 
                   12130: =item *
                   12131: 
1.243     albertel 12132: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12133: resource's metadata, $what should be either a specific key, or either
                   12134: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12135: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12136: 
                   12137: this function automatically caches all requests
1.191     harris41 12138: 
                   12139: =item *
                   12140: 
1.243     albertel 12141: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12142: network of library servers; returns file handle of where SQL and regex results
                   12143: will be stored for query
1.191     harris41 12144: 
                   12145: =item *
                   12146: 
1.243     albertel 12147: symbread($filename) : return symbolic list entry (filename argument optional);
                   12148: returns the data handle
1.191     harris41 12149: 
                   12150: =item *
                   12151: 
1.243     albertel 12152: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 12153: a possible symb for the URL in $thisfn, and if is an encryypted
                   12154: resource that the user accessed using /enc/ returns a 1 on success, 0
                   12155: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 12156: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 12157: 
1.191     harris41 12158: 
                   12159: =item *
                   12160: 
1.243     albertel 12161: symbclean($symb) : removes versions numbers from a symb, returns the
                   12162: cleaned symb
1.191     harris41 12163: 
                   12164: =item *
                   12165: 
1.243     albertel 12166: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12167: course map, user must be in a course for it to work.
1.191     harris41 12168: 
                   12169: =item *
                   12170: 
1.243     albertel 12171: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12172: 
                   12173: =item *
                   12174: 
1.243     albertel 12175: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12176: a random seed, all arguments are optional, if they aren't sent it uses the
                   12177: environment to derive them. Note: if symb isn't sent and it can't get one
                   12178: from &symbread it will use the current time as its return value
1.191     harris41 12179: 
                   12180: =item *
                   12181: 
1.243     albertel 12182: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12183: unfakeable, receipt
1.191     harris41 12184: 
                   12185: =item *
                   12186: 
1.620     albertel 12187: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12188: 
                   12189: =item *
                   12190: 
1.243     albertel 12191: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12192: 
                   12193: =item *
                   12194: 
1.243     albertel 12195: 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 12196: 
                   12197: =item *
                   12198: 
1.243     albertel 12199: 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 12200: 
                   12201: =item *
                   12202: 
1.243     albertel 12203: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12204: 
                   12205: =item *
                   12206: 
1.243     albertel 12207: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12208: forcing spreadsheet to reevaluate the resource scores next time.
                   12209: 
                   12210: =back
                   12211: 
                   12212: =head2 Storing/Retreiving Data
                   12213: 
                   12214: =over 4
1.191     harris41 12215: 
                   12216: =item *
                   12217: 
1.243     albertel 12218: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12219: for this url; hashref needs to be given and should be a \%hashname; the
                   12220: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12221: be derived from the env
1.191     harris41 12222: 
                   12223: =item *
                   12224: 
1.243     albertel 12225: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12226: uses critical subroutine
1.191     harris41 12227: 
                   12228: =item *
                   12229: 
1.243     albertel 12230: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12231: all args are optional
1.191     harris41 12232: 
                   12233: =item *
                   12234: 
1.717     albertel 12235: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12236: dumps the complete (or key matching regexp) namespace into a hash
                   12237: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12238: normally &store()ed into
                   12239: 
                   12240: $range should be either an integer '100' (give me the first 100
                   12241:                                            matching records)
                   12242:               or be  two integers sperated by a - with no spaces
                   12243:                  '30-50' (give me the 30th through the 50th matching
                   12244:                           records)
                   12245: 
                   12246: 
                   12247: =item *
                   12248: 
                   12249: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12250: replaces a &store() version of data with a replacement set of data
                   12251: for a particular resource in a namespace passed in the $storehash hash 
                   12252: reference
                   12253: 
                   12254: =item *
                   12255: 
1.243     albertel 12256: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12257: works very similar to store/cstore, but all data is stored in a
                   12258: temporary location and can be reset using tmpreset, $storehash should
                   12259: be a hash reference, returns nothing on success
1.191     harris41 12260: 
                   12261: =item *
                   12262: 
1.243     albertel 12263: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12264: similar to restore, but all data is stored in a temporary location and
                   12265: can be reset using tmpreset. Returns a hash of values on success,
                   12266: error string otherwise.
1.191     harris41 12267: 
                   12268: =item *
                   12269: 
1.243     albertel 12270: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12271: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12272: 
                   12273: =item *
                   12274: 
1.243     albertel 12275: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12276: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12277: 
                   12278: =item *
                   12279: 
1.243     albertel 12280: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12281: namesp ($udom and $uname are optional)
1.191     harris41 12282: 
                   12283: =item *
                   12284: 
1.702     albertel 12285: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12286: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12287: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12288: 
1.702     albertel 12289: $range should be either an integer '100' (give me the first 100
                   12290:                                            matching records)
                   12291:               or be  two integers sperated by a - with no spaces
                   12292:                  '30-50' (give me the 30th through the 50th matching
                   12293:                           records)
1.449     matthew  12294: =item *
                   12295: 
                   12296: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12297: $store can be a scalar, an array reference, or if the amount to be 
                   12298: incremented is > 1, a hash reference.
                   12299: 
                   12300: ($udom and $uname are optional)
1.191     harris41 12301: 
                   12302: =item *
                   12303: 
1.243     albertel 12304: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12305: ($udom and $uname are optional)
1.191     harris41 12306: 
                   12307: =item *
                   12308: 
1.243     albertel 12309: cput($namespace,$storehash,$udom,$uname) : critical put
                   12310: ($udom and $uname are optional)
1.191     harris41 12311: 
                   12312: =item *
                   12313: 
1.748     albertel 12314: newput($namespace,$storehash,$udom,$uname) :
                   12315: 
                   12316: Attempts to store the items in the $storehash, but only if they don't
                   12317: currently exist, if this succeeds you can be certain that you have 
                   12318: successfully created a new key value pair in the $namespace db.
                   12319: 
                   12320: 
                   12321: Args:
                   12322:  $namespace: name of database to store values to
                   12323:  $storehash: hashref to store to the db
                   12324:  $udom: (optional) domain of user containing the db
                   12325:  $uname: (optional) name of user caontaining the db
                   12326: 
                   12327: Returns:
                   12328:  'ok' -> succeeded in storing all keys of $storehash
                   12329:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12330:                         least <key> already existed in the db (other
                   12331:                         requested keys may also already exist)
1.967     bisitz   12332:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12333:  'con_lost' -> unable to contact request server
                   12334:  'refused' -> action was not allowed by remote machine
                   12335: 
                   12336: 
                   12337: =item *
                   12338: 
1.243     albertel 12339: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12340: reference filled in from namesp (encrypts the return communication)
                   12341: ($udom and $uname are optional)
1.191     harris41 12342: 
                   12343: =item *
                   12344: 
1.243     albertel 12345: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12346: critical subroutine
                   12347: 
1.806     raeburn  12348: =item *
                   12349: 
1.860     raeburn  12350: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12351: array reference filled in from namespace found in domain level on either
                   12352: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12353: 
                   12354: =item *
                   12355: 
1.860     raeburn  12356: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12357: domain level either on specified domain server ($uhome) or primary domain 
                   12358: server ($udom and $uhome are optional)
1.806     raeburn  12359: 
1.943     raeburn  12360: =item * 
                   12361: 
                   12362: get_domain_defaults($target_domain) : returns hash with defaults for
                   12363: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12364: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12365: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12366: Values are retrieved from cache (if current), or from domain's configuration.db
                   12367: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12368: or lonTabs/domain.tab. 
                   12369: 
                   12370: %domdefaults = &get_auth_defaults($target_domain);
                   12371: 
1.243     albertel 12372: =back
                   12373: 
                   12374: =head2 Network Status Functions
                   12375: 
                   12376: =over 4
1.191     harris41 12377: 
                   12378: =item *
                   12379: 
1.1137    raeburn  12380: dirlist() : return directory list based on URI (first arg).
                   12381: 
                   12382: Inputs: 1 required, 5 optional.
                   12383: 
                   12384: =over
                   12385: 
                   12386: =item 
                   12387: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12388: 
                   12389: =item
                   12390: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12391: 
                   12392: =item
                   12393: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12394: 
                   12395: =item
                   12396: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12397: 
                   12398: =item
                   12399: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12400: 
                   12401: =item 
                   12402: $alternateRoot - path to prepend in place of path from $uri.
                   12403: 
                   12404: =back
                   12405: 
                   12406: Returns: Array of up to two items.
                   12407: 
                   12408: =over
                   12409: 
                   12410: a reference to an array of files/subdirectories
                   12411: 
                   12412: =over
                   12413: 
                   12414: Each element in the array of files/subdirectories is a & separated list of
                   12415: item name and the result of running stat on the item.  If dirlist was requested
                   12416: for a file instead of a directory, the item name will be ''. For a directory 
                   12417: listing, if the item is a metadata file, the element will end &N&M 
                   12418: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12419: default copyright set (1).  
                   12420: 
                   12421: =back
                   12422: 
                   12423: a scalar containing error condition (if encountered).
                   12424: 
                   12425: =over
                   12426: 
                   12427: =item 
                   12428: no_host (no homeserver identified for $username:$domain).
                   12429: 
                   12430: =item 
                   12431: no_such_host (server contacted for listing not identified as valid host).
                   12432: 
                   12433: =item 
                   12434: con_lost (connection to remote server failed).
                   12435: 
                   12436: =item 
                   12437: refused (invalid $username:$domain received on lond side).
                   12438: 
                   12439: =item 
                   12440: no_such_dir (directory at specified path on lond side does not exist). 
                   12441: 
                   12442: =item 
                   12443: empty (directory at specified path on lond side is empty).
                   12444: 
                   12445: =over
                   12446: 
                   12447: This is currently not encountered because the &ls3, &ls2, 
                   12448: &ls (_handler) routines on the lond side do not filter out
                   12449: . and .. from a directory listing. 
                   12450: 
                   12451: =back
                   12452: 
                   12453: =back
                   12454: 
                   12455: =back
1.191     harris41 12456: 
                   12457: =item *
                   12458: 
1.243     albertel 12459: spareserver() : find server with least workload from spare.tab
                   12460: 
1.986     foxr     12461: 
                   12462: =item *
                   12463: 
                   12464: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12465: if there is no corresponding loncapa host.
                   12466: 
1.243     albertel 12467: =back
                   12468: 
1.986     foxr     12469: 
1.243     albertel 12470: =head2 Apache Request
                   12471: 
                   12472: =over 4
1.191     harris41 12473: 
                   12474: =item *
                   12475: 
1.243     albertel 12476: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12477: localhost, posts hash
                   12478: 
                   12479: =back
                   12480: 
                   12481: =head2 Data to String to Data
                   12482: 
                   12483: =over 4
1.191     harris41 12484: 
                   12485: =item *
                   12486: 
1.243     albertel 12487: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12488: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12489: 
                   12490: =item *
                   12491: 
1.243     albertel 12492: hashref2str($hashref) : convert a hashref into a string complete with
                   12493: escaping and '=' and '&' separators, supports elements that are
                   12494: arrayrefs and hashrefs
1.191     harris41 12495: 
                   12496: =item *
                   12497: 
1.243     albertel 12498: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12499: with escaping and '&' separators, supports elements that are arrayrefs
                   12500: and hashrefs
1.191     harris41 12501: 
                   12502: =item *
                   12503: 
1.243     albertel 12504: str2hash($string) : convert string to hash using unescaping and
                   12505: splitting on '=' and '&', supports elements that are arrayrefs and
                   12506: hashrefs
1.191     harris41 12507: 
                   12508: =item *
                   12509: 
1.243     albertel 12510: str2array($string) : convert string to hash using unescaping and
                   12511: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12512: 
                   12513: =back
                   12514: 
                   12515: =head2 Logging Routines
                   12516: 
                   12517: 
                   12518: These routines allow one to make log messages in the lonnet.log and
                   12519: lonnet.perm logfiles.
1.191     harris41 12520: 
1.1119    foxr     12521: =over 4
                   12522: 
1.191     harris41 12523: =item *
                   12524: 
1.243     albertel 12525: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12526: 
                   12527: =item *
                   12528: 
1.243     albertel 12529: logthis() : append message to the normal lonnet.log file, it gets
                   12530: preiodically rolled over and deleted.
1.191     harris41 12531: 
                   12532: =item *
                   12533: 
1.243     albertel 12534: logperm() : append a permanent message to lonnet.perm.log, this log
                   12535: file never gets deleted by any automated portion of the system, only
                   12536: messages of critical importance should go in here.
                   12537: 
1.1119    foxr     12538: 
1.243     albertel 12539: =back
                   12540: 
                   12541: =head2 General File Helper Routines
                   12542: 
                   12543: =over 4
1.191     harris41 12544: 
                   12545: =item *
                   12546: 
1.481     raeburn  12547: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12548: (a) files in /uploaded
                   12549:   (i) If a local copy of the file exists - 
                   12550:       compares modification date of local copy with last-modified date for 
                   12551:       definitive version stored on home server for course. If local copy is 
                   12552:       stale, requests a new version from the home server and stores it. 
                   12553:       If the original has been removed from the home server, then local copy 
                   12554:       is unlinked.
                   12555:   (ii) If local copy does not exist -
                   12556:       requests the file from the home server and stores it. 
                   12557:   
                   12558:   If $caller is 'uploadrep':  
                   12559:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12560:     for request for files originally uploaded via DOCS. 
                   12561:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12562:   
                   12563:   Otherwise:
                   12564:      This indicates a call from the content generation phase of the request.
                   12565:      -  returns the entire contents of the file or -1.
                   12566:      
                   12567: (b) files in /res
                   12568:    - returns the entire contents of a file or -1; 
                   12569:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12570: 
1.712     albertel 12571: 
                   12572: =item *
                   12573: 
                   12574: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12575:                   reference
                   12576: 
                   12577: returns either a stat() list of data about the file or an empty list
                   12578: if the file doesn't exist or couldn't find out about it (connection
                   12579: problems or user unknown)
                   12580: 
1.191     harris41 12581: =item *
                   12582: 
1.243     albertel 12583: filelocation($dir,$file) : returns file system location of a file
                   12584: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12585: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12586: and a file of ../bob will become /a/bob)
1.191     harris41 12587: 
                   12588: =item *
                   12589: 
                   12590: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12591: filelocation except for hrefs
                   12592: 
                   12593: =item *
                   12594: 
                   12595: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12596: 
1.243     albertel 12597: =back
                   12598: 
1.608     albertel 12599: =head2 Usererfile file routines (/uploaded*)
                   12600: 
                   12601: =over 4
                   12602: 
                   12603: =item *
                   12604: 
                   12605: userfileupload(): main rotine for putting a file in a user or course's
                   12606:                   filespace, arguments are,
                   12607: 
1.620     albertel 12608:  formname - required - this is the name of the element in $env where the
1.608     albertel 12609:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12610:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12611:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12612:  context - if coursedoc, store the file in the course of the active role
                   12613:              of the current user; 
                   12614:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12615:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12616:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12617:          if undefined, it will be placed in "unknown"
                   12618: 
                   12619:  (This routine calls clean_filename() to remove any dangerous
                   12620:  characters from the filename, and then calls finuserfileupload() to
                   12621:  complete the transaction)
                   12622: 
                   12623:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12624:  and /adm/notfound.html if unsuccessful
                   12625: 
                   12626: =item *
                   12627: 
                   12628: clean_filename(): routine for cleaing a filename up for storage in
                   12629:                  userfile space, argument is:
                   12630: 
                   12631:  filename - proposed filename
                   12632: 
                   12633: returns: the new clean filename
                   12634: 
                   12635: =item *
                   12636: 
1.1090    raeburn  12637: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12638: userspace, probably shouldn't be called directly
                   12639: 
                   12640:   docuname: username or courseid of destination for the file
                   12641:   docudom: domain of user/course of destination for the file
                   12642:   formname: same as for userfileupload()
1.1090    raeburn  12643:   fname: filename (including subdirectories) for the file
                   12644:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12645:   allfiles: reference to hash used to store objects found by parser
                   12646:   codebase: reference to hash used for codebases of java objects found by parser
                   12647:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12648:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12649:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12650:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12651:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12652:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12653:   mimetype: reference to scalar to accommodate mime type determined
                   12654:             from File::MMagic if $parser = parse.
1.608     albertel 12655: 
                   12656:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12657:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12658:  was 'overwrite').
                   12659:  
1.608     albertel 12660: 
                   12661: =item *
                   12662: 
                   12663: renameuserfile(): renames an existing userfile to a new name
                   12664: 
                   12665:   Args:
                   12666:    docuname: username or courseid of destination for the file
                   12667:    docudom: domain of user/course of destination for the file
                   12668:    old: current file name (including any subdirs under userfiles)
                   12669:    new: desired file name (including any subdirs under userfiles)
                   12670: 
                   12671: =item *
                   12672: 
                   12673: mkdiruserfile(): creates a directory is a userfiles dir
                   12674: 
                   12675:   Args:
                   12676:    docuname: username or courseid of destination for the file
                   12677:    docudom: domain of user/course of destination for the file
                   12678:    dir: dir to create (including any subdirs under userfiles)
                   12679: 
                   12680: =item *
                   12681: 
                   12682: removeuserfile(): removes a file that exists in userfiles
                   12683: 
                   12684:   Args:
                   12685:    docuname: username or courseid of destination for the file
                   12686:    docudom: domain of user/course of destination for the file
                   12687:    fname: filname to delete (including any subdirs under userfiles)
                   12688: 
                   12689: =item *
                   12690: 
                   12691: removeuploadedurl(): convience function for removeuserfile()
                   12692: 
                   12693:   Args:
                   12694:    url:  a full /uploaded/... url to delete
                   12695: 
1.747     albertel 12696: =item * 
                   12697: 
                   12698: get_portfile_permissions():
                   12699:   Args:
                   12700:     domain: domain of user or course contain the portfolio files
                   12701:     user: name of user or num of course contain the portfolio files
                   12702:   Returns:
                   12703:     hashref of a dump of the proper file_permissions.db
                   12704:    
                   12705: 
                   12706: =item * 
                   12707: 
                   12708: get_access_controls():
                   12709: 
                   12710: Args:
                   12711:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12712:   group: (optional) the group you want the files associated with
                   12713:   file: (optional) the file you want access info on
                   12714: 
                   12715: Returns:
1.749     raeburn  12716:     a hash (keys are file names) of hashes containing
                   12717:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12718:         values are XML containing access control settings (see below) 
1.747     albertel 12719: 
                   12720: Internal notes:
                   12721: 
1.749     raeburn  12722:  access controls are stored in file_permissions.db as key=value pairs.
                   12723:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12724:         where scope -> public,guest,course,group,domains or users.
                   12725:               end -> UNIX time for end of access (0 -> no end date)
                   12726:               start -> UNIX time for start of access
                   12727: 
                   12728:     value -> XML description of access control
                   12729:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12730:             <start></start>
                   12731:             <end></end>
                   12732: 
                   12733:             <password></password>  for scope type = guest
                   12734: 
                   12735:             <domain></domain>     for scope type = course or group
                   12736:             <number></number>
                   12737:             <roles id="">
                   12738:              <role></role>
                   12739:              <access></access>
                   12740:              <section></section>
                   12741:              <group></group>
                   12742:             </roles>
                   12743: 
                   12744:             <dom></dom>         for scope type = domains
                   12745: 
                   12746:             <users>             for scope type = users
                   12747:              <user>
                   12748:               <uname></uname>
                   12749:               <udom></udom>
                   12750:              </user>
                   12751:             </users>
                   12752:            </scope> 
                   12753:               
                   12754:  Access data is also aggregated for each file in an additional key=value pair:
                   12755:  key -> path to file/file_name\0accesscontrol 
                   12756:  value -> reference to hash
                   12757:           hash contains key = value pairs
                   12758:           where key = uniqueID:scope_end_start
                   12759:                 value = UNIX time record was last updated
                   12760: 
                   12761:           Used to improve speed of look-ups of access controls for each file.  
                   12762:  
                   12763:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12764: 
                   12765: modify_access_controls():
                   12766: 
                   12767: Modifies access controls for a portfolio file
                   12768: Args
                   12769: 1. file name
                   12770: 2. reference to hash of required changes,
                   12771: 3. domain
                   12772: 4. username
                   12773:   where domain,username are the domain of the portfolio owner 
                   12774:   (either a user or a course) 
                   12775: 
                   12776: Returns:
                   12777: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12778: 2. result of deletions ('ok' or 'error', with error message).
                   12779: 3. reference to hash of any new or updated access controls.
                   12780: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12781:    key = integer (inbound ID)
                   12782:    value = uniqueID  
1.747     albertel 12783: 
1.608     albertel 12784: =back
                   12785: 
1.243     albertel 12786: =head2 HTTP Helper Routines
                   12787: 
                   12788: =over 4
                   12789: 
1.191     harris41 12790: =item *
                   12791: 
                   12792: escape() : unpack non-word characters into CGI-compatible hex codes
                   12793: 
                   12794: =item *
                   12795: 
                   12796: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12797: 
1.243     albertel 12798: =back
                   12799: 
                   12800: =head1 PRIVATE SUBROUTINES
                   12801: 
                   12802: =head2 Underlying communication routines (Shouldn't call)
                   12803: 
                   12804: =over 4
                   12805: 
                   12806: =item *
                   12807: 
                   12808: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12809: 
                   12810: =item *
                   12811: 
                   12812: reply() : uses subreply to send a message to remote machine, logs all failures
                   12813: 
                   12814: =item *
                   12815: 
                   12816: critical() : passes a critical message to another server; if cannot
                   12817: get through then place message in connection buffer directory and
                   12818: returns con_delayed, if incapable of saving message, returns
                   12819: con_failed
                   12820: 
                   12821: =item *
                   12822: 
                   12823: reconlonc() : tries to reconnect lonc client processes.
                   12824: 
                   12825: =back
                   12826: 
                   12827: =head2 Resource Access Logging
                   12828: 
                   12829: =over 4
                   12830: 
                   12831: =item *
                   12832: 
                   12833: flushcourselogs() : flush (save) buffer logs and access logs
                   12834: 
                   12835: =item *
                   12836: 
                   12837: courselog($what) : save message for course in hash
                   12838: 
                   12839: =item *
                   12840: 
                   12841: courseacclog($what) : save message for course using &courselog().  Perform
                   12842: special processing for specific resource types (problems, exams, quizzes, etc).
                   12843: 
1.191     harris41 12844: =item *
                   12845: 
                   12846: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12847: as a PerlChildExitHandler
1.243     albertel 12848: 
                   12849: =back
                   12850: 
                   12851: =head2 Other
                   12852: 
                   12853: =over 4
                   12854: 
                   12855: =item *
                   12856: 
                   12857: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12858: 
                   12859: =back
                   12860: 
                   12861: =cut
1.877     foxr     12862: 

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