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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1172.2.1! raeburn     4: # $Id: lonnet.pm,v 1.1172 2012/05/21 18:35:30 bisitz 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.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1160    www        99: use LONCAPA::lonmetadata;
1.1117    foxr      100: 
1.1090    raeburn   101: use File::Copy;
1.676     albertel  102: 
1.195     www       103: my $readit;
1.550     foxr      104: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  105: 
1.619     albertel  106: require Exporter;
                    107: 
                    108: our @ISA = qw (Exporter);
                    109: our @EXPORT = qw(%env);
                    110: 
1.449     matthew   111: 
1.1       albertel  112: # --------------------------------------------------------------------- Logging
1.729     www       113: {
                    114:     my $logid;
                    115:     sub instructor_log {
1.957     raeburn   116: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    117:         if (($cnum eq '') || ($cdom eq '')) {
                    118:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    119:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    120:         }
1.729     www       121: 	$logid++;
1.957     raeburn   122:         my $now = time();
                    123: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       124: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       125: 				    { $id => {
                    126: 					'exe_uname' => $env{'user.name'},
                    127: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   128: 					'exe_time'  => $now,
1.730     www       129: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    130: 					'delflag'   => $delflag,
                    131: 					'logentry'  => $storehash,
                    132: 					'uname'     => $uname,
                    133: 					'udom'      => $udom,
                    134: 				    }
1.957     raeburn   135: 				  },$cdom,$cnum);
1.729     www       136:     }
                    137: }
1.1       albertel  138: 
1.163     harris41  139: sub logtouch {
                    140:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  141:     unless (-e "$execdir/logs/lonnet.log") {	
                    142: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  143: 	close $fh;
                    144:     }
                    145:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    146:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    147: }
                    148: 
1.1       albertel  149: sub logthis {
                    150:     my $message=shift;
                    151:     my $execdir=$perlvar{'lonDaemons'};
                    152:     my $now=time;
                    153:     my $local=localtime($now);
1.448     albertel  154:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      155: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    156: 	print $fh $logstring;
1.448     albertel  157: 	close($fh);
                    158:     }
1.1       albertel  159:     return 1;
                    160: }
                    161: 
                    162: sub logperm {
                    163:     my $message=shift;
                    164:     my $execdir=$perlvar{'lonDaemons'};
                    165:     my $now=time;
                    166:     my $local=localtime($now);
1.448     albertel  167:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    168: 	print $fh "$now:$message:$local\n";
                    169: 	close($fh);
                    170:     }
1.1       albertel  171:     return 1;
                    172: }
                    173: 
1.850     albertel  174: sub create_connection {
1.853     albertel  175:     my ($hostname,$lonid) = @_;
1.851     albertel  176:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  177: 				     Type    => SOCK_STREAM,
                    178: 				     Timeout => 10);
                    179:     return 0 if (!$client);
1.890     albertel  180:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  181:     my $result = <$client>;
                    182:     chomp($result);
                    183:     return 1 if ($result eq 'done');
                    184:     return 0;
                    185: }
                    186: 
1.983     raeburn   187: sub get_server_timezone {
                    188:     my ($cnum,$cdom) = @_;
                    189:     my $home=&homeserver($cnum,$cdom);
                    190:     if ($home ne 'no_host') {
                    191:         my $cachetime = 24*3600;
                    192:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    193:         if (defined($cached)) {
                    194:             return $timezone;
                    195:         } else {
                    196:             my $timezone = &reply('servertimezone',$home);
                    197:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    198:         }
                    199:     }
                    200: }
1.850     albertel  201: 
1.1106    raeburn   202: sub get_server_distarch {
                    203:     my ($lonhost,$ignore_cache) = @_;
                    204:     if (defined($lonhost)) {
                    205:         if (!defined(&hostname($lonhost))) {
                    206:             return;
                    207:         }
                    208:         my $cachetime = 12*3600;
                    209:         if (!$ignore_cache) {
                    210:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    211:             if (defined($cached)) {
                    212:                 return $distarch;
                    213:             }
                    214:         }
                    215:         my $rep = &reply('serverdistarch',$lonhost);
                    216:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    217:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    218:                 $rep eq '') {
                    219:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    220:         }
                    221:     }
                    222:     return;
                    223: }
                    224: 
1.993     raeburn   225: sub get_server_loncaparev {
1.1073    raeburn   226:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   227:     if (defined($lonhost)) {
                    228:         if (!defined(&hostname($lonhost))) {
                    229:             undef($lonhost);
                    230:         }
                    231:     }
                    232:     if (!defined($lonhost)) {
                    233:         if (defined(&domain($dom,'primary'))) {
                    234:             $lonhost=&domain($dom,'primary');
                    235:             if ($lonhost eq 'no_host') {
                    236:                 undef($lonhost);
                    237:             }
                    238:         }
                    239:     }
                    240:     if (defined($lonhost)) {
1.1073    raeburn   241:         my $cachetime = 12*3600;
                    242:         if (!$ignore_cache) {
                    243:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    244:             if (defined($cached)) {
                    245:                 return $loncaparev;
                    246:             }
                    247:         }
                    248:         my ($answer,$loncaparev);
                    249:         my @ids=&current_machine_ids();
                    250:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    251:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   252:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   253:                 $loncaparev = $1;
                    254:             }
                    255:         } else {
                    256:             $answer = &reply('serverloncaparev',$lonhost);
                    257:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    258:                 if ($caller eq 'loncron') {
                    259:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   260:                     $ua->timeout(4);
1.1073    raeburn   261:                     my $protocol = $protocol{$lonhost};
                    262:                     $protocol = 'http' if ($protocol ne 'https');
                    263:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    264:                     my $request=new HTTP::Request('GET',$url);
                    265:                     my $response=$ua->request($request);
                    266:                     unless ($response->is_error()) {
                    267:                         my $content = $response->content;
1.1081    raeburn   268:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   269:                             $loncaparev = $1;
                    270:                         }
                    271:                     }
                    272:                 } else {
                    273:                     $loncaparev = $loncaparevs{$lonhost};
                    274:                 }
1.1081    raeburn   275:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   276:                 $loncaparev = $1;
                    277:             }
1.993     raeburn   278:         }
1.1073    raeburn   279:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   280:     }
                    281: }
                    282: 
1.1074    raeburn   283: sub get_server_homeID {
                    284:     my ($hostname,$ignore_cache,$caller) = @_;
                    285:     unless ($ignore_cache) {
                    286:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    287:         if (defined($cached)) {
                    288:             return $serverhomeID;
                    289:         }
                    290:     }
                    291:     my $cachetime = 12*3600;
                    292:     my $serverhomeID;
                    293:     if ($caller eq 'loncron') { 
                    294:         my @machine_ids = &machine_ids($hostname);
                    295:         foreach my $id (@machine_ids) {
                    296:             my $response = &reply('serverhomeID',$id);
                    297:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    298:                 $serverhomeID = $response;
                    299:                 last;
                    300:             }
                    301:         }
                    302:         if ($serverhomeID eq '') {
                    303:             $serverhomeID = $machine_ids[-1];
                    304:         }
                    305:     } else {
                    306:         $serverhomeID = $serverhomeIDs{$hostname};
                    307:     }
                    308:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    309: }
                    310: 
1.1121    raeburn   311: sub get_remote_globals {
                    312:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   313:     my ($result,%returnhash,%whatneeded);
                    314:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   315:         foreach my $what (sort(keys(%{$whathash}))) {
                    316:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   317:             my ($response,$cached);
1.1121    raeburn   318:             unless ($ignore_cache) {
1.1125    raeburn   319:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   320:             }
                    321:             if (defined($cached)) {
1.1125    raeburn   322:                 $returnhash{$what} = $response;
1.1121    raeburn   323:             } else {
1.1125    raeburn   324:                 $whatneeded{$what} = 1;
1.1121    raeburn   325:             }
                    326:         }
1.1125    raeburn   327:         if (keys(%whatneeded) == 0) {
                    328:             $result = 'ok';
                    329:         } else {
1.1121    raeburn   330:             my $requested = &freeze_escape(\%whatneeded);
                    331:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   332:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    333:                 ($rep eq 'unknown_cmd')) {
                    334:                 $result = $rep;
                    335:             } else {
                    336:                 $result = 'ok';
1.1121    raeburn   337:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   338:                 foreach my $item (@pairs) {
                    339:                     my ($key,$value)=split(/=/,$item,2);
                    340:                     my $what = &unescape($key);
                    341:                     my $hashid = $lonhost.'-'.$what;
                    342:                     $returnhash{$what}=&thaw_unescape($value);
                    343:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   344:                 }
                    345:             }
                    346:         }
                    347:     }
1.1125    raeburn   348:     return ($result,\%returnhash);
1.1121    raeburn   349: }
                    350: 
1.1124    raeburn   351: sub remote_devalidate_cache {
                    352:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   353:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   354:     return $response;
                    355: }
                    356: 
1.1       albertel  357: # -------------------------------------------------- Non-critical communication
                    358: sub subreply {
                    359:     my ($cmd,$server)=@_;
1.838     albertel  360:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      361:     #
                    362:     #  With loncnew process trimming, there's a timing hole between lonc server
                    363:     #  process exit and the master server picking up the listen on the AF_UNIX
                    364:     #  socket.  In that time interval, a lock file will exist:
                    365: 
                    366:     my $lockfile=$peerfile.".lock";
                    367:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    368: 	sleep(1);
                    369:     }
                    370:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      371:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      372:     #
1.550     foxr      373:     #   We'll give the connection a few tries before abandoning it.  If
                    374:     #   connection is not possible, we'll con_lost back to the client.
                    375:     #   
                    376:     my $client;
                    377:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    378: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    379: 				      Type    => SOCK_STREAM,
                    380: 				      Timeout => 10);
1.869     albertel  381: 	if ($client) {
1.550     foxr      382: 	    last;		# Connected!
1.850     albertel  383: 	} else {
1.853     albertel  384: 	    &create_connection(&hostname($server),$server);
1.550     foxr      385: 	}
1.850     albertel  386:         sleep(1);		# Try again later if failed connection.
1.550     foxr      387:     }
                    388:     my $answer;
                    389:     if ($client) {
1.704     albertel  390: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      391: 	$answer=<$client>;
                    392: 	if (!$answer) { $answer="con_lost"; }
                    393: 	chomp($answer);
                    394:     } else {
                    395: 	$answer = 'con_lost';	# Failed connection.
                    396:     }
1.1       albertel  397:     return $answer;
                    398: }
                    399: 
                    400: sub reply {
                    401:     my ($cmd,$server)=@_;
1.838     albertel  402:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  403:     my $answer=subreply($cmd,$server);
1.65      www       404:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  405:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       406:                 " $cmd to $server returned $answer</font>");
                    407:     }
1.1       albertel  408:     return $answer;
                    409: }
                    410: 
                    411: # ----------------------------------------------------------- Send USR1 to lonc
                    412: 
                    413: sub reconlonc {
1.891     albertel  414:     my ($lonid) = @_;
                    415:     my $hostname = &hostname($lonid);
                    416:     if ($lonid) {
                    417: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    418: 	if ($hostname && -e $peerfile) {
                    419: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    420: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    421: 					     Type    => SOCK_STREAM,
                    422: 					     Timeout => 10);
                    423: 	    if ($client) {
                    424: 		print $client ("reset_retries\n");
                    425: 		my $answer=<$client>;
                    426: 		#reset just this one.
                    427: 	    }
                    428: 	}
                    429: 	return;
                    430:     }
                    431: 
1.836     www       432:     &logthis("Trying to reconnect lonc");
1.1       albertel  433:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  434:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  435: 	my $loncpid=<$fh>;
                    436:         chomp($loncpid);
                    437:         if (kill 0 => $loncpid) {
                    438: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    439:             kill USR1 => $loncpid;
                    440:             sleep 1;
1.836     www       441:          } else {
1.12      www       442: 	    &logthis(
1.672     albertel  443:                "<font color=\"blue\">WARNING:".
1.12      www       444:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  445:         }
                    446:     } else {
1.836     www       447: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  448:     }
                    449: }
                    450: 
                    451: # ------------------------------------------------------ Critical communication
1.12      www       452: 
1.1       albertel  453: sub critical {
                    454:     my ($cmd,$server)=@_;
1.838     albertel  455:     unless (&hostname($server)) {
1.672     albertel  456:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       457:                " Critical message to unknown server ($server)</font>");
                    458:         return 'no_such_host';
                    459:     }
1.1       albertel  460:     my $answer=reply($cmd,$server);
                    461:     if ($answer eq 'con_lost') {
                    462: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  463: 	my $answer=reply($cmd,$server);
1.1       albertel  464:         if ($answer eq 'con_lost') {
                    465:             my $now=time;
                    466:             my $middlename=$cmd;
1.5       www       467:             $middlename=substr($middlename,0,16);
1.1       albertel  468:             $middlename=~s/\W//g;
                    469:             my $dfilename=
1.305     www       470:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    471:             $dumpcount++;
1.1       albertel  472:             {
1.448     albertel  473: 		my $dfh;
                    474: 		if (open($dfh,">$dfilename")) {
                    475: 		    print $dfh "$cmd\n"; 
                    476: 		    close($dfh);
                    477: 		}
1.1       albertel  478:             }
                    479:             sleep 2;
                    480:             my $wcmd='';
                    481:             {
1.448     albertel  482: 		my $dfh;
                    483: 		if (open($dfh,"<$dfilename")) {
                    484: 		    $wcmd=<$dfh>; 
                    485: 		    close($dfh);
                    486: 		}
1.1       albertel  487:             }
                    488:             chomp($wcmd);
1.7       www       489:             if ($wcmd eq $cmd) {
1.672     albertel  490: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       491:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  492:                 &logperm("D:$server:$cmd");
                    493: 	        return 'con_delayed';
                    494:             } else {
1.672     albertel  495:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       496:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  497:                 &logperm("F:$server:$cmd");
                    498:                 return 'con_failed';
                    499:             }
                    500:         }
                    501:     }
                    502:     return $answer;
1.405     albertel  503: }
                    504: 
1.755     albertel  505: # ------------------------------------------- check if return value is an error
                    506: 
                    507: sub error {
                    508:     my ($result) = @_;
1.756     albertel  509:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  510: 	if ($2 == 2) { return undef; }
                    511: 	return $1;
                    512:     }
                    513:     return undef;
                    514: }
                    515: 
1.783     albertel  516: sub convert_and_load_session_env {
                    517:     my ($lonidsdir,$handle)=@_;
                    518:     my @profile;
                    519:     {
1.917     albertel  520: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    521: 	if (!$opened) {
1.915     albertel  522: 	    return 0;
                    523: 	}
1.783     albertel  524: 	flock($idf,LOCK_SH);
                    525: 	@profile=<$idf>;
                    526: 	close($idf);
                    527:     }
                    528:     my %temp_env;
                    529:     foreach my $line (@profile) {
1.786     albertel  530: 	if ($line !~ m/=/) {
                    531: 	    return 0;
                    532: 	}
1.783     albertel  533: 	chomp($line);
                    534: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    535: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    536:     }
                    537:     unlink("$lonidsdir/$handle.id");
                    538:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    539: 	    0640)) {
                    540: 	%disk_env = %temp_env;
                    541: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    542: 	untie(%disk_env);
                    543:     }
1.786     albertel  544:     return 1;
1.783     albertel  545: }
                    546: 
1.374     www       547: # ------------------------------------------- Transfer profile into environment
1.780     albertel  548: my $env_loaded;
                    549: sub transfer_profile_to_env {
1.788     albertel  550:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    551:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       552: 
1.720     albertel  553:     if (!defined($lonidsdir)) {
                    554: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    555:     }
                    556:     if (!defined($handle)) {
                    557:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    558:     }
                    559: 
1.786     albertel  560:     my $convert;
                    561:     {
1.917     albertel  562:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    563: 	if (!$opened) {
1.915     albertel  564: 	    return;
                    565: 	}
1.786     albertel  566: 	flock($idf,LOCK_SH);
                    567: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    568: 		&GDBM_READER(),0640)) {
                    569: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    570: 	    untie(%disk_env);
                    571: 	} else {
                    572: 	    $convert = 1;
                    573: 	}
                    574:     }
                    575:     if ($convert) {
                    576: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    577: 	    &logthis("Failed to load session, or convert session.");
                    578: 	}
1.374     www       579:     }
1.783     albertel  580: 
1.786     albertel  581:     my %remove;
1.783     albertel  582:     while ( my $envname = each(%env) ) {
1.433     matthew   583:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    584:             if ($time < time-300) {
1.783     albertel  585:                 $remove{$key}++;
1.433     matthew   586:             }
                    587:         }
                    588:     }
1.783     albertel  589: 
1.619     albertel  590:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  591:     $env_loaded=1;
1.783     albertel  592:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   593:         &delenv($expired_key);
1.374     www       594:     }
1.1       albertel  595: }
                    596: 
1.916     albertel  597: # ---------------------------------------------------- Check for valid session 
                    598: sub check_for_valid_session {
1.1155    raeburn   599:     my ($r,$name) = @_;
1.916     albertel  600:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   601:     if ($name eq '') {
                    602:         $name = 'lonID';
                    603:     }
                    604:     my $lonid=$cookies{$name};
1.916     albertel  605:     return undef if (!$lonid);
                    606: 
                    607:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   608:     my $lonidsdir;
                    609:     if ($name eq 'lonDAV') {
                    610:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    611:     } else {
                    612:         $lonidsdir=$r->dir_config('lonIDsDir');
                    613:     }
1.916     albertel  614:     return undef if (!-e "$lonidsdir/$handle.id");
                    615: 
1.917     albertel  616:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    617:     return undef if (!$opened);
1.916     albertel  618: 
                    619:     flock($idf,LOCK_SH);
                    620:     my %disk_env;
                    621:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    622: 	    &GDBM_READER(),0640)) {
                    623: 	return undef;	
                    624:     }
                    625: 
                    626:     if (!defined($disk_env{'user.name'})
                    627: 	|| !defined($disk_env{'user.domain'})) {
                    628: 	return undef;
                    629:     }
                    630:     return $handle;
                    631: }
                    632: 
1.830     albertel  633: sub timed_flock {
                    634:     my ($file,$lock_type) = @_;
                    635:     my $failed=0;
                    636:     eval {
                    637: 	local $SIG{__DIE__}='DEFAULT';
                    638: 	local $SIG{ALRM}=sub {
                    639: 	    $failed=1;
                    640: 	    die("failed lock");
                    641: 	};
                    642: 	alarm(13);
                    643: 	flock($file,$lock_type);
                    644: 	alarm(0);
                    645:     };
                    646:     if ($failed) {
                    647: 	return undef;
                    648:     } else {
                    649: 	return 1;
                    650:     }
                    651: }
                    652: 
1.5       www       653: # ---------------------------------------------------------- Append Environment
                    654: 
                    655: sub appenv {
1.949     raeburn   656:     my ($newenv,$roles) = @_;
                    657:     if (ref($newenv) eq 'HASH') {
                    658:         foreach my $key (keys(%{$newenv})) {
                    659:             my $refused = 0;
                    660: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    661:                 $refused = 1;
                    662:                 if (ref($roles) eq 'ARRAY') {
                    663:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    664:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    665:                         $refused = 0;
                    666:                     }
                    667:                 }
                    668:             }
                    669:             if ($refused) {
                    670:                 &logthis("<font color=\"blue\">WARNING: ".
                    671:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    672:                          .'</font>');
                    673: 	        delete($newenv->{$key});
                    674:             } else {
                    675:                 $env{$key}=$newenv->{$key};
                    676:             }
                    677:         }
                    678:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    679:         if ($opened
                    680: 	    && &timed_flock($env_file,LOCK_EX)
                    681: 	    &&
                    682: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    683: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    684: 	    while (my ($key,$value) = each(%{$newenv})) {
                    685: 	        $disk_env{$key} = $value;
                    686: 	    }
                    687: 	    untie(%disk_env);
1.35      www       688:         }
1.191     harris41  689:     }
1.56      www       690:     return 'ok';
                    691: }
                    692: # ----------------------------------------------------- Delete from Environment
                    693: 
                    694: sub delenv {
1.1104    raeburn   695:     my ($delthis,$regexp,$roles) = @_;
                    696:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    697:         my $refused = 1;
                    698:         if (ref($roles) eq 'ARRAY') {
                    699:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    700:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    701:                 $refused = 0;
                    702:             }
                    703:         }
                    704:         if ($refused) {
                    705:             &logthis("<font color=\"blue\">WARNING: ".
                    706:                      "Attempt to delete from environment ".$delthis);
                    707:             return 'error';
                    708:         }
1.56      www       709:     }
1.917     albertel  710:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    711:     if ($opened
1.915     albertel  712: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  713: 	&&
                    714: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    715: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  716: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   717: 	    if ($regexp) {
                    718:                 if ($key=~/^$delthis/) {
                    719:                     delete($env{$key});
                    720:                     delete($disk_env{$key});
                    721:                 } 
                    722:             } else {
                    723:                 if ($key=~/^\Q$delthis\E/) {
                    724: 		    delete($env{$key});
                    725: 		    delete($disk_env{$key});
                    726: 	        }
                    727:             }
1.448     albertel  728: 	}
1.783     albertel  729: 	untie(%disk_env);
1.5       www       730:     }
                    731:     return 'ok';
1.369     albertel  732: }
                    733: 
1.790     albertel  734: sub get_env_multiple {
                    735:     my ($name) = @_;
                    736:     my @values;
                    737:     if (defined($env{$name})) {
                    738:         # exists is it an array
                    739:         if (ref($env{$name})) {
                    740:             @values=@{ $env{$name} };
                    741:         } else {
                    742:             $values[0]=$env{$name};
                    743:         }
                    744:     }
                    745:     return(@values);
                    746: }
                    747: 
1.958     www       748: # ------------------------------------------------------------------- Locking
                    749: 
                    750: sub set_lock {
                    751:     my ($text)=@_;
                    752:     $locknum++;
                    753:     my $id=$$.'-'.$locknum;
                    754:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    755:              'session.lock.'.$id => $text});
                    756:     return $id;
                    757: }
                    758: 
                    759: sub get_locks {
                    760:     my $num=0;
                    761:     my %texts=();
                    762:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    763:        if ($lock=~/\w/) {
                    764:           $num++;
                    765:           $texts{$lock}=$env{'session.lock.'.$lock};
                    766:        }
                    767:    }
                    768:    return ($num,%texts);
                    769: }
                    770: 
                    771: sub remove_lock {
                    772:     my ($id)=@_;
                    773:     my $newlocks='';
                    774:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    775:        if (($lock=~/\w/) && ($lock ne $id)) {
                    776:           $newlocks.=','.$lock;
                    777:        }
                    778:     }
                    779:     &appenv({'session.locks' => $newlocks});
                    780:     &delenv('session.lock.'.$id);
                    781: }
                    782: 
                    783: sub remove_all_locks {
                    784:     my $activelocks=$env{'session.locks'};
                    785:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    786:        if ($lock=~/\w/) {
                    787:           &remove_lock($lock);
                    788:        }
                    789:     }
                    790: }
                    791: 
                    792: 
1.369     albertel  793: # ------------------------------------------ Find out current server userload
                    794: sub userload {
                    795:     my $numusers=0;
                    796:     {
                    797: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    798: 	my $filename;
                    799: 	my $curtime=time;
                    800: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  801: 	    next if ($filename eq '.' || $filename eq '..');
                    802: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  803: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  804: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  805: 	}
                    806: 	closedir(LONIDS);
                    807:     }
                    808:     my $userloadpercent=0;
                    809:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    810:     if ($maxuserload) {
1.371     albertel  811: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  812:     }
1.372     albertel  813:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  814:     return $userloadpercent;
1.283     www       815: }
                    816: 
1.1       albertel  817: # ------------------------------ Find server with least workload from spare.tab
1.11      www       818: 
1.1       albertel  819: sub spareserver {
1.1083    raeburn   820:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  821:     my $spare_server;
1.370     albertel  822:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  823:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    824:                                                      :  $userloadpercent;
1.1083    raeburn   825:     my ($uint_dom,$remotesessions);
                    826:     if (($udom ne '') && (&domain($udom) ne '')) {
                    827:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    828:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    829:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    830:         $remotesessions = $udomdefaults{'remotesessions'};
                    831:     }
1.1123    raeburn   832:     my $spareshash = &this_host_spares($udom);
                    833:     if (ref($spareshash) eq 'HASH') {
                    834:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    835:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    836:                 if ($uint_dom) {
                    837:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    838:                                                  $try_server));
                    839:                 }
                    840: 	        ($spare_server, $lowest_load) =
                    841: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    842:             }
1.1083    raeburn   843:         }
1.784     albertel  844: 
1.1123    raeburn   845:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    846: 
                    847:         if (!$found_server) {
                    848:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    849: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    850:                     if ($uint_dom) {
                    851:                         next unless (&spare_can_host($udom,$uint_dom,
                    852:                                                      $remotesessions,$try_server));
                    853:                     }
                    854: 	            ($spare_server, $lowest_load) =
                    855: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    856:                 }
                    857: 	    }
                    858:         }
1.784     albertel  859:     }
                    860: 
                    861:     if (!$want_server_name) {
1.968     raeburn   862:         my $protocol = 'http';
                    863:         if ($protocol{$spare_server} eq 'https') {
                    864:             $protocol = $protocol{$spare_server};
                    865:         }
1.1001    raeburn   866:         if (defined($spare_server)) {
                    867:             my $hostname = &hostname($spare_server);
1.1083    raeburn   868:             if (defined($hostname)) {
1.1001    raeburn   869: 	        $spare_server = $protocol.'://'.$hostname;
                    870:             }
                    871:         }
1.784     albertel  872:     }
                    873:     return $spare_server;
                    874: }
                    875: 
                    876: sub compare_server_load {
                    877:     my ($try_server, $spare_server, $lowest_load) = @_;
                    878: 
                    879:     my $loadans     = &reply('load',    $try_server);
                    880:     my $userloadans = &reply('userload',$try_server);
                    881: 
                    882:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   883: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  884:     }
                    885: 
                    886:     my $load;
                    887:     if ($loadans =~ /\d/) {
                    888: 	if ($userloadans =~ /\d/) {
                    889: 	    #both are numbers, pick the bigger one
                    890: 	    $load = ($loadans > $userloadans) ? $loadans 
                    891: 		                              : $userloadans;
1.411     albertel  892: 	} else {
1.784     albertel  893: 	    $load = $loadans;
1.411     albertel  894: 	}
1.784     albertel  895:     } else {
                    896: 	$load = $userloadans;
                    897:     }
                    898: 
                    899:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    900: 	$spare_server = $try_server;
                    901: 	$lowest_load  = $load;
1.370     albertel  902:     }
1.784     albertel  903:     return ($spare_server,$lowest_load);
1.202     matthew   904: }
1.914     albertel  905: 
                    906: # --------------------------- ask offload servers if user already has a session
                    907: sub find_existing_session {
                    908:     my ($udom,$uname) = @_;
1.1123    raeburn   909:     my $spareshash = &this_host_spares($udom);
                    910:     if (ref($spareshash) eq 'HASH') {
                    911:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    912:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    913:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    914:             }
                    915:         }
                    916:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    917:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    918:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    919:             }
                    920:         }
1.914     albertel  921:     }
                    922:     return;
                    923: }
                    924: 
                    925: # -------------------------------- ask if server already has a session for user
                    926: sub has_user_session {
                    927:     my ($lonid,$udom,$uname) = @_;
                    928:     my $result = &reply(join(':','userhassession',
                    929: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    930:     return 1 if ($result eq 'ok');
                    931: 
                    932:     return 0;
                    933: }
                    934: 
1.1076    raeburn   935: # --------- determine least loaded server in a user's domain which allows login
                    936: 
                    937: sub choose_server {
1.1115    raeburn   938:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   939:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   940:     my %servers = &get_servers($udom);
1.1076    raeburn   941:     my $lowest_load = 30000;
1.1151    raeburn   942:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   943:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   944:         my $loginvia;
                    945:         if ($checkloginvia) {
                    946:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   947:             if ($loginvia) {
                    948:                 my ($server,$path) = split(/:/,$loginvia);
                    949:                 ($login_host, $lowest_load) =
                    950:                     &compare_server_load($server, $login_host, $lowest_load);
                    951:                 if ($login_host eq $server) {
                    952:                     $portal_path = $path;
1.1151    raeburn   953:                     $isredirect = 1;
1.1116    raeburn   954:                 }
                    955:             } else {
                    956:                 ($login_host, $lowest_load) =
                    957:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    958:                 if ($login_host eq $lonhost) {
                    959:                     $portal_path = '';
1.1151    raeburn   960:                     $isredirect = ''; 
1.1116    raeburn   961:                 }
                    962:             }
                    963:         } else {
1.1076    raeburn   964:             ($login_host, $lowest_load) =
1.1116    raeburn   965:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   966:         }
                    967:     }
                    968:     if ($login_host ne '') {
1.1116    raeburn   969:         $hostname = &hostname($login_host);
1.1076    raeburn   970:     }
1.1151    raeburn   971:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   972: }
                    973: 
1.202     matthew   974: # --------------------------------------------- Try to change a user's password
                    975: 
                    976: sub changepass {
1.799     raeburn   977:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   978:     $currentpass = &escape($currentpass);
                    979:     $newpass     = &escape($newpass);
1.1030    raeburn   980:     my $lonhost = $perlvar{'lonHostID'};
                    981:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   982: 		       $server);
                    983:     if (! $answer) {
                    984: 	&logthis("No reply on password change request to $server ".
                    985: 		 "by $uname in domain $udom.");
                    986:     } elsif ($answer =~ "^ok") {
                    987:         &logthis("$uname in $udom successfully changed their password ".
                    988: 		 "on $server.");
                    989:     } elsif ($answer =~ "^pwchange_failure") {
                    990: 	&logthis("$uname in $udom was unable to change their password ".
                    991: 		 "on $server.  The action was blocked by either lcpasswd ".
                    992: 		 "or pwchange");
                    993:     } elsif ($answer =~ "^non_authorized") {
                    994:         &logthis("$uname in $udom did not get their password correct when ".
                    995: 		 "attempting to change it on $server.");
                    996:     } elsif ($answer =~ "^auth_mode_error") {
                    997:         &logthis("$uname in $udom attempted to change their password despite ".
                    998: 		 "not being locally or internally authenticated on $server.");
                    999:     } elsif ($answer =~ "^unknown_user") {
                   1000:         &logthis("$uname in $udom attempted to change their password ".
                   1001: 		 "on $server but were unable to because $server is not ".
                   1002: 		 "their home server.");
                   1003:     } elsif ($answer =~ "^refused") {
                   1004: 	&logthis("$server refused to change $uname in $udom password because ".
                   1005: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1006:     } elsif ($answer =~ "invalid_client") {
                   1007:         &logthis("$server refused to change $uname in $udom password because ".
                   1008:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1009:     }
                   1010:     return $answer;
1.1       albertel 1011: }
                   1012: 
1.169     harris41 1013: # ----------------------- Try to determine user's current authentication scheme
                   1014: 
                   1015: sub queryauthenticate {
                   1016:     my ($uname,$udom)=@_;
1.456     albertel 1017:     my $uhome=&homeserver($uname,$udom);
                   1018:     if (!$uhome) {
                   1019: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1020: 	return 'no_host';
                   1021:     }
                   1022:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1023:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1024: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1025:     }
1.456     albertel 1026:     return $answer;
1.169     harris41 1027: }
                   1028: 
1.1       albertel 1029: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1030: 
1.1       albertel 1031: sub authenticate {
1.1073    raeburn  1032:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1033:     $upass=&escape($upass);
                   1034:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1035:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1036:     my $newhome;
1.836     www      1037:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1038: # Maybe the machine was offline and only re-appeared again recently?
                   1039:         &reconlonc();
                   1040: # One more
1.952     raeburn  1041: 	$uhome=&homeserver($uname,$udom,1);
                   1042:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1043:             if (defined(&domain($udom,'primary'))) {
                   1044:                 $newhome=&domain($udom,'primary');
                   1045:             }
                   1046:             if ($newhome ne '') {
                   1047:                 $uhome = $newhome;
                   1048:             }
                   1049:         }
1.836     www      1050: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1051: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1052: 	    return 'no_host';
                   1053:         }
1.1       albertel 1054:     }
1.1073    raeburn  1055:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1056:     if ($answer eq 'authorized') {
1.952     raeburn  1057:         if ($newhome) {
                   1058:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1059:             return 'no_account_on_host'; 
                   1060:         } else {
                   1061:             &logthis("User $uname at $udom authorized by $uhome");
                   1062:             return $uhome;
                   1063:         }
1.471     albertel 1064:     }
                   1065:     if ($answer eq 'non_authorized') {
                   1066: 	&logthis("User $uname at $udom rejected by $uhome");
                   1067: 	return 'no_host'; 
1.9       www      1068:     }
1.471     albertel 1069:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1070:     return 'no_host';
                   1071: }
                   1072: 
1.1073    raeburn  1073: sub can_host_session {
1.1074    raeburn  1074:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1075:     my $canhost = 1;
1.1074    raeburn  1076:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1077:     if (ref($remotesessions) eq 'HASH') {
                   1078:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1079:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1080:                 $canhost = 0;
                   1081:             } else {
                   1082:                 $canhost = 1;
                   1083:             }
                   1084:         }
                   1085:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1086:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1087:                 $canhost = 1;
                   1088:             } else {
                   1089:                 $canhost = 0;
                   1090:             }
                   1091:         }
                   1092:         if ($canhost) {
                   1093:             if ($remotesessions->{'version'} ne '') {
                   1094:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1095:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1096:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1097:                         my $major = $1;
                   1098:                         my $minor = $2;
                   1099:                         if (($major < $reqmajor ) ||
                   1100:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1101:                             $canhost = 0;
                   1102:                         }
                   1103:                     } else {
                   1104:                         $canhost = 0;
                   1105:                     }
                   1106:                 }
                   1107:             }
                   1108:         }
                   1109:     }
                   1110:     if ($canhost) {
                   1111:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1112:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1113:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1114:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1115:                 if (($uint_dom ne '') && 
                   1116:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1117:                     $canhost = 0;
                   1118:                 } else {
                   1119:                     $canhost = 1;
                   1120:                 }
                   1121:             }
                   1122:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1123:                 if (($uint_dom ne '') && 
                   1124:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1125:                     $canhost = 1;
                   1126:                 } else {
                   1127:                     $canhost = 0;
                   1128:                 }
                   1129:             }
                   1130:         }
                   1131:     }
                   1132:     return $canhost;
                   1133: }
                   1134: 
1.1083    raeburn  1135: sub spare_can_host {
                   1136:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1137:     my $canhost=1;
                   1138:     my @intdoms;
                   1139:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1140:     if (ref($internet_names) eq 'ARRAY') {
                   1141:         @intdoms = @{$internet_names};
                   1142:     }
                   1143:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1144:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1145:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1146:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1147:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1148:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1149:                                      $remotesessions,
                   1150:                                      $defdomdefaults{'hostedsessions'});
                   1151:     }
                   1152:     return $canhost;
                   1153: }
                   1154: 
1.1123    raeburn  1155: sub this_host_spares {
                   1156:     my ($dom) = @_;
1.1126    raeburn  1157:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1158:     my @hosts = &current_machine_ids();
                   1159:     foreach my $lonhost (@hosts) {
                   1160:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1161:             $dom_in_use = $dom;
                   1162:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1163:             last;
                   1164:         }
                   1165:     }
1.1126    raeburn  1166:     if ($dom_in_use ne '') {
                   1167:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1168:     }
                   1169:     if (ref($result) ne 'HASH') {
                   1170:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1171:         $dom_in_use = &host_domain($lonhost_in_use);
                   1172:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1173:         if (ref($result) ne 'HASH') {
                   1174:             $result = \%spareid;
                   1175:         }
                   1176:     }
                   1177:     return $result;
                   1178: }
                   1179: 
                   1180: sub spares_for_offload  {
                   1181:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1182:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1183:     if (defined($cached)) {
                   1184:         return $result;
                   1185:     } else {
1.1126    raeburn  1186:         my $cachetime = 60*60*24;
                   1187:         my %domconfig =
                   1188:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1189:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1190:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1191:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1192:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1193:                 }
                   1194:             }
                   1195:         }
                   1196:     }
1.1126    raeburn  1197:     return;
1.1123    raeburn  1198: }
                   1199: 
1.1129    raeburn  1200: sub get_lonbalancer_config {
                   1201:     my ($servers) = @_;
                   1202:     my ($currbalancer,$currtargets);
                   1203:     if (ref($servers) eq 'HASH') {
                   1204:         foreach my $server (keys(%{$servers})) {
                   1205:             my %what = (
                   1206:                          spareid => 1,
                   1207:                          perlvar => 1,
                   1208:                        );
                   1209:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1210:             if ($result eq 'ok') {
                   1211:                 if (ref($returnhash) eq 'HASH') {
                   1212:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1213:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1214:                             $currbalancer = $server;
                   1215:                             $currtargets = {};
                   1216:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1217:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1218:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1219:                                 }
                   1220:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1221:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1222:                                 }
                   1223:                             }
                   1224:                             last;
                   1225:                         }
                   1226:                     }
                   1227:                 }
                   1228:             }
                   1229:         }
                   1230:     }
                   1231:     return ($currbalancer,$currtargets);
                   1232: }
                   1233: 
                   1234: sub check_loadbalancing {
                   1235:     my ($uname,$udom) = @_;
                   1236:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1237:         $offloadto,$otherserver);
                   1238:     my $lonhost = $perlvar{'lonHostID'};
                   1239:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1240:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1241:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1242:     my $serverhomedom = &host_domain($lonhost);
                   1243: 
                   1244:     my $cachetime = 60*60*24;
                   1245: 
                   1246:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1247:         $dom_in_use = $udom;
                   1248:         $homeintdom = 1;
                   1249:     } else {
                   1250:         $dom_in_use = $serverhomedom;
                   1251:     }
                   1252:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1253:     unless (defined($cached)) {
                   1254:         my %domconfig =
                   1255:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1256:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1257:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1258:         }
                   1259:     }
                   1260:     if (ref($result) eq 'HASH') {
                   1261:         my $currbalancer = $result->{'lonhost'};
                   1262:         my $currtargets = $result->{'targets'};
                   1263:         my $currrules = $result->{'rules'};
                   1264:         if ($currbalancer ne '') {
                   1265:             my @hosts = &current_machine_ids();
                   1266:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1267:                 $is_balancer = 1;
                   1268:             }
                   1269:         }
                   1270:         if ($is_balancer) {
                   1271:             if (ref($currrules) eq 'HASH') {
                   1272:                 if ($homeintdom) {
                   1273:                     if ($uname ne '') {
                   1274:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1275:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1276:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1277:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1278:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1279:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1280:                             }
                   1281:                         }
                   1282:                         if ($rule_in_effect eq '') {
                   1283:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1284:                             if ($userenv{'inststatus'} ne '') {
                   1285:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1286:                                 my ($othertitle,$usertypes,$types) =
                   1287:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1288:                                 if (ref($types) eq 'ARRAY') {
                   1289:                                     foreach my $type (@{$types}) {
                   1290:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1291:                                             if (exists($currrules->{$type})) {
                   1292:                                                 $rule_in_effect = $currrules->{$type};
                   1293:                                             }
                   1294:                                         }
                   1295:                                     }
                   1296:                                 }
                   1297:                             } else {
                   1298:                                 if (exists($currrules->{'default'})) {
                   1299:                                     $rule_in_effect = $currrules->{'default'};
                   1300:                                 }
                   1301:                             }
                   1302:                         }
                   1303:                     } else {
                   1304:                         if (exists($currrules->{'default'})) {
                   1305:                             $rule_in_effect = $currrules->{'default'};
                   1306:                         }
                   1307:                     }
                   1308:                 } else {
                   1309:                     if ($currrules->{'_LC_external'} ne '') {
                   1310:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1311:                     }
                   1312:                 }
                   1313:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1314:                                                        $uname,$udom);
                   1315:             }
                   1316:         }
                   1317:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1318:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1319:         unless (defined($cached)) {
                   1320:             my %domconfig =
                   1321:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1322:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1323:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1324:             }
                   1325:         }
                   1326:         if (ref($result) eq 'HASH') {
                   1327:             my $currbalancer = $result->{'lonhost'};
                   1328:             my $currtargets = $result->{'targets'};
                   1329:             my $currrules = $result->{'rules'};
                   1330: 
                   1331:             if ($currbalancer eq $lonhost) {
                   1332:                 $is_balancer = 1;
                   1333:                 if (ref($currrules) eq 'HASH') {
                   1334:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1335:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1336:                     }
                   1337:                 }
                   1338:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1339:                                                        $uname,$udom);
                   1340:             }
                   1341:         } else {
                   1342:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1343:                 $is_balancer = 1;
                   1344:                 $offloadto = &this_host_spares($dom_in_use);
                   1345:             }
                   1346:         }
                   1347:     } else {
                   1348:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1349:             $is_balancer = 1;
                   1350:             $offloadto = &this_host_spares($dom_in_use);
                   1351:         }
                   1352:     }
                   1353:     my $lowest_load = 30000;
                   1354:     if (ref($offloadto) eq 'HASH') {
                   1355:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1356:             foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1357:                 ($otherserver,$lowest_load) =
                   1358:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1359:             }
                   1360:         }
                   1361:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
                   1362: 
                   1363:         if (!$found_server) {
                   1364:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1365:                 foreach my $try_server (@{$offloadto->{'default'}}) {
                   1366:                     ($otherserver,$lowest_load) =
                   1367:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1368:                 }
                   1369:             }
                   1370:         }
                   1371:     } elsif (ref($offloadto) eq 'ARRAY') {
                   1372:         if (@{$offloadto} == 1) {
                   1373:             $otherserver = $offloadto->[0];
                   1374:         } elsif (@{$offloadto} > 1) {
                   1375:             foreach my $try_server (@{$offloadto}) {
                   1376:                 ($otherserver,$lowest_load) =
                   1377:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1378:             }
                   1379:         }
                   1380:     }
                   1381:     return ($is_balancer,$otherserver);
                   1382: }
                   1383: 
                   1384: sub get_loadbalancer_targets {
                   1385:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1386:     my $offloadto;
                   1387:     if ($rule_in_effect eq '') {
                   1388:         $offloadto = $currtargets;
                   1389:     } else {
                   1390:         if ($rule_in_effect eq 'homeserver') {
                   1391:             my $homeserver = &homeserver($uname,$udom);
                   1392:             if ($homeserver ne 'no_host') {
                   1393:                 $offloadto = [$homeserver];
                   1394:             }
                   1395:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1396:             my %domconfig =
                   1397:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1398:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1399:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1400:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1401:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1402:                     }
                   1403:                 }
                   1404:             } else {
                   1405:                 my %servers = &dom_servers($udom);
                   1406:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1407:                 if (&hostname($remotebalancer) ne '') {
                   1408:                     $offloadto = [$remotebalancer];
                   1409:                 }
                   1410:             }
                   1411:         } elsif (&hostname($rule_in_effect) ne '') {
                   1412:             $offloadto = [$rule_in_effect];
                   1413:         }
                   1414:     }
                   1415:     return $offloadto;
                   1416: }
                   1417: 
1.1127    raeburn  1418: sub internet_dom_servers {
                   1419:     my ($dom) = @_;
                   1420:     my (%uniqservers,%servers);
                   1421:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1422:     my @machinedoms = &machine_domains($primaryserver);
                   1423:     foreach my $mdom (@machinedoms) {
                   1424:         my %currservers = %servers;
                   1425:         my %server = &get_servers($mdom);
                   1426:         %servers = (%currservers,%server);
                   1427:     }
                   1428:     my %by_hostname;
                   1429:     foreach my $id (keys(%servers)) {
                   1430:         push(@{$by_hostname{$servers{$id}}},$id);
                   1431:     }
                   1432:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1433:         if (@{$by_hostname{$hostname}} > 1) {
                   1434:             my $match = 0;
                   1435:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1436:                 if (&host_domain($id) eq $dom) {
                   1437:                     $uniqservers{$id} = $hostname;
                   1438:                     $match = 1;
                   1439:                 }
                   1440:             }
                   1441:             unless ($match) {
                   1442:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1443:             }
                   1444:         } else {
                   1445:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1446:         }
                   1447:     }
                   1448:     return %uniqservers;
                   1449: }
                   1450: 
1.1       albertel 1451: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1452: 
1.599     albertel 1453: my %homecache;
1.1       albertel 1454: sub homeserver {
1.230     stredwic 1455:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1456:     my $index="$uname:$udom";
1.426     albertel 1457: 
1.599     albertel 1458:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1459: 
                   1460:     my %servers = &get_servers($udom,'library');
                   1461:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1462:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1463: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1464: 
                   1465: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1466: 	if ($answer eq 'found') {
                   1467: 	    delete($badServerCache{$tryserver}); 
                   1468: 	    return $homecache{$index}=$tryserver;
                   1469: 	} elsif ($answer eq 'no_host') {
                   1470: 	    $badServerCache{$tryserver}=1;
                   1471: 	}
1.1       albertel 1472:     }    
                   1473:     return 'no_host';
1.70      www      1474: }
                   1475: 
                   1476: # ------------------------------------- Find the usernames behind a list of IDs
                   1477: 
                   1478: sub idget {
                   1479:     my ($udom,@ids)=@_;
                   1480:     my %returnhash=();
                   1481:     
1.841     albertel 1482:     my %servers = &get_servers($udom,'library');
                   1483:     foreach my $tryserver (keys(%servers)) {
                   1484: 	my $idlist=join('&',@ids);
                   1485: 	$idlist=~tr/A-Z/a-z/; 
                   1486: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1487: 	my @answer=();
                   1488: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1489: 	    @answer=split(/\&/,$reply);
                   1490: 	}                    ;
                   1491: 	my $i;
                   1492: 	for ($i=0;$i<=$#ids;$i++) {
                   1493: 	    if ($answer[$i]) {
                   1494: 		$returnhash{$ids[$i]}=$answer[$i];
                   1495: 	    } 
                   1496: 	}
                   1497:     } 
1.70      www      1498:     return %returnhash;
                   1499: }
                   1500: 
                   1501: # ------------------------------------- Find the IDs behind a list of usernames
                   1502: 
                   1503: sub idrget {
                   1504:     my ($udom,@unames)=@_;
                   1505:     my %returnhash=();
1.800     albertel 1506:     foreach my $uname (@unames) {
                   1507:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1508:     }
1.70      www      1509:     return %returnhash;
                   1510: }
                   1511: 
                   1512: # ------------------------------- Store away a list of names and associated IDs
                   1513: 
                   1514: sub idput {
                   1515:     my ($udom,%ids)=@_;
                   1516:     my %servers=();
1.800     albertel 1517:     foreach my $uname (keys(%ids)) {
                   1518: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1519:         my $uhom=&homeserver($uname,$udom);
1.70      www      1520:         if ($uhom ne 'no_host') {
1.800     albertel 1521:             my $id=&escape($ids{$uname});
1.70      www      1522:             $id=~tr/A-Z/a-z/;
1.800     albertel 1523:             my $esc_unam=&escape($uname);
1.70      www      1524: 	    if ($servers{$uhom}) {
1.800     albertel 1525: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1526:             } else {
1.800     albertel 1527:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1528:             }
                   1529:         }
1.191     harris41 1530:     }
1.800     albertel 1531:     foreach my $server (keys(%servers)) {
                   1532:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1533:     }
1.344     www      1534: }
                   1535: 
1.1023    raeburn  1536: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1537: sub dump_dom {
1.1165    droeschl 1538:     my ($namespace, $udom, $regexp) = @_;
                   1539: 
                   1540:     $udom ||= $env{'user.domain'};
                   1541: 
                   1542:     return () unless $udom;
                   1543: 
                   1544:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1545: }
                   1546: 
1.1023    raeburn  1547: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1548: 
                   1549: sub get_dom {
1.860     raeburn  1550:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1551:     my $items='';
                   1552:     foreach my $item (@$storearr) {
                   1553:         $items.=&escape($item).'&';
                   1554:     }
                   1555:     $items=~s/\&$//;
1.860     raeburn  1556:     if (!$udom) {
                   1557:         $udom=$env{'user.domain'};
                   1558:         if (defined(&domain($udom,'primary'))) {
                   1559:             $uhome=&domain($udom,'primary');
                   1560:         } else {
1.874     albertel 1561:             undef($uhome);
1.860     raeburn  1562:         }
                   1563:     } else {
                   1564:         if (!$uhome) {
                   1565:             if (defined(&domain($udom,'primary'))) {
                   1566:                 $uhome=&domain($udom,'primary');
                   1567:             }
                   1568:         }
                   1569:     }
                   1570:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1571:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1572:         my %returnhash;
1.875     albertel 1573:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1574:             return %returnhash;
                   1575:         }
1.806     raeburn  1576:         my @pairs=split(/\&/,$rep);
                   1577:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1578:             return @pairs;
                   1579:         }
                   1580:         my $i=0;
                   1581:         foreach my $item (@$storearr) {
                   1582:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1583:             $i++;
                   1584:         }
                   1585:         return %returnhash;
                   1586:     } else {
1.880     banghart 1587:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1588:     }
                   1589: }
                   1590: 
                   1591: # -------------------------------------------- put items in domain db files 
                   1592: 
                   1593: sub put_dom {
1.860     raeburn  1594:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1595:     if (!$udom) {
                   1596:         $udom=$env{'user.domain'};
                   1597:         if (defined(&domain($udom,'primary'))) {
                   1598:             $uhome=&domain($udom,'primary');
                   1599:         } else {
1.874     albertel 1600:             undef($uhome);
1.860     raeburn  1601:         }
                   1602:     } else {
                   1603:         if (!$uhome) {
                   1604:             if (defined(&domain($udom,'primary'))) {
                   1605:                 $uhome=&domain($udom,'primary');
                   1606:             }
                   1607:         }
                   1608:     } 
                   1609:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1610:         my $items='';
                   1611:         foreach my $item (keys(%$storehash)) {
                   1612:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1613:         }
                   1614:         $items=~s/\&$//;
                   1615:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1616:     } else {
1.860     raeburn  1617:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1618:     }
                   1619: }
                   1620: 
1.1023    raeburn  1621: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1622: sub newput_dom {
1.1023    raeburn  1623:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1624:     my $result;
                   1625:     if (!$udom) {
                   1626:         $udom=$env{'user.domain'};
                   1627:     }
1.1023    raeburn  1628:     if ($udom) {
                   1629:         my $uname = &get_domainconfiguser($udom);
                   1630:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1631:     }
                   1632:     return $result;
                   1633: }
                   1634: 
1.1023    raeburn  1635: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1636: sub del_dom {
1.1023    raeburn  1637:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1638:     if (ref($storearr) eq 'ARRAY') {
                   1639:         if (!$udom) {
                   1640:             $udom=$env{'user.domain'};
                   1641:         }
1.1023    raeburn  1642:         if ($udom) {
                   1643:             my $uname = &get_domainconfiguser($udom); 
                   1644:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1645:         }
                   1646:     }
                   1647: }
                   1648: 
1.1023    raeburn  1649: # ----------------------------------construct domainconfig user for a domain 
                   1650: sub get_domainconfiguser {
                   1651:     my ($udom) = @_;
                   1652:     return $udom.'-domainconfig';
                   1653: }
                   1654: 
1.837     raeburn  1655: sub retrieve_inst_usertypes {
                   1656:     my ($udom) = @_;
                   1657:     my (%returnhash,@order);
1.989     raeburn  1658:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1659:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1660:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1661:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1662:         @order = @{$domdefs{'inststatusorder'}};
                   1663:     } else {
                   1664:         if (defined(&domain($udom,'primary'))) {
                   1665:             my $uhome=&domain($udom,'primary');
                   1666:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1667:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1668:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1669:                 return (\%returnhash,\@order);
                   1670:             }
                   1671:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1672:             my @pairs=split(/\&/,$hashitems);
                   1673:             foreach my $item (@pairs) {
                   1674:                 my ($key,$value)=split(/=/,$item,2);
                   1675:                 $key = &unescape($key);
                   1676:                 next if ($key =~ /^error: 2 /);
                   1677:                 $returnhash{$key}=&thaw_unescape($value);
                   1678:             }
                   1679:             my @esc_order = split(/\&/,$orderitems);
                   1680:             foreach my $item (@esc_order) {
                   1681:                 push(@order,&unescape($item));
                   1682:             }
                   1683:         } else {
                   1684:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1685:         }
                   1686:     }
                   1687:     return (\%returnhash,\@order);
                   1688: }
                   1689: 
1.868     raeburn  1690: sub is_domainimage {
                   1691:     my ($url) = @_;
                   1692:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1693:         if (&domain($1) ne '') {
                   1694:             return '1';
                   1695:         }
                   1696:     }
                   1697:     return;
                   1698: }
                   1699: 
1.899     raeburn  1700: sub inst_directory_query {
                   1701:     my ($srch) = @_;
                   1702:     my $udom = $srch->{'srchdomain'};
                   1703:     my %results;
                   1704:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1705:     my $outcome;
1.899     raeburn  1706:     if ($homeserver ne '') {
1.904     albertel 1707: 	my $queryid=&reply("querysend:instdirsearch:".
                   1708: 			   &escape($srch->{'srchby'}).':'.
                   1709: 			   &escape($srch->{'srchterm'}).':'.
                   1710: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1711: 	my $host=&hostname($homeserver);
                   1712: 	if ($queryid !~/^\Q$host\E\_/) {
                   1713: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1714: 	    return;
                   1715: 	}
                   1716: 	my $response = &get_query_reply($queryid);
                   1717: 	my $maxtries = 5;
                   1718: 	my $tries = 1;
                   1719: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1720: 	    $response = &get_query_reply($queryid);
                   1721: 	    $tries ++;
                   1722: 	}
                   1723: 
                   1724:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1725:             if ($response eq 'unavailable') {
                   1726:                 $outcome = $response;
                   1727:             } else {
                   1728:                 $outcome = 'ok';
                   1729:                 my @matches = split(/\n/,$response);
                   1730:                 foreach my $match (@matches) {
                   1731:                     my ($key,$value) = split(/=/,$match);
                   1732:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1733:                 }
1.899     raeburn  1734:             }
                   1735:         }
                   1736:     }
1.909     raeburn  1737:     return ($outcome,%results);
1.899     raeburn  1738: }
                   1739: 
                   1740: sub usersearch {
                   1741:     my ($srch) = @_;
                   1742:     my $dom = $srch->{'srchdomain'};
                   1743:     my %results;
                   1744:     my %libserv = &all_library();
                   1745:     my $query = 'usersearch';
                   1746:     foreach my $tryserver (keys(%libserv)) {
                   1747:         if (&host_domain($tryserver) eq $dom) {
                   1748:             my $host=&hostname($tryserver);
                   1749:             my $queryid=
1.911     raeburn  1750:                 &reply("querysend:".&escape($query).':'.
                   1751:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1752:                        &escape($srch->{'srchtype'}).':'.
                   1753:                        &escape($srch->{'srchterm'}),$tryserver);
                   1754:             if ($queryid !~/^\Q$host\E\_/) {
                   1755:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1756:                 next;
1.899     raeburn  1757:             }
                   1758:             my $reply = &get_query_reply($queryid);
                   1759:             my $maxtries = 1;
                   1760:             my $tries = 1;
                   1761:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1762:                 $reply = &get_query_reply($queryid);
                   1763:                 $tries ++;
                   1764:             }
                   1765:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1766:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1767:             } else {
1.911     raeburn  1768:                 my @matches;
                   1769:                 if ($reply =~ /\n/) {
                   1770:                     @matches = split(/\n/,$reply);
                   1771:                 } else {
                   1772:                     @matches = split(/\&/,$reply);
                   1773:                 }
1.899     raeburn  1774:                 foreach my $match (@matches) {
                   1775:                     my ($uname,$udom,%userhash);
1.911     raeburn  1776:                     foreach my $entry (split(/:/,$match)) {
                   1777:                         my ($key,$value) =
                   1778:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1779:                         $userhash{$key} = $value;
                   1780:                         if ($key eq 'username') {
                   1781:                             $uname = $value;
                   1782:                         } elsif ($key eq 'domain') {
                   1783:                             $udom = $value;
1.911     raeburn  1784:                         }
1.899     raeburn  1785:                     }
                   1786:                     $results{$uname.':'.$udom} = \%userhash;
                   1787:                 }
                   1788:             }
                   1789:         }
                   1790:     }
                   1791:     return %results;
                   1792: }
                   1793: 
1.912     raeburn  1794: sub get_instuser {
                   1795:     my ($udom,$uname,$id) = @_;
                   1796:     my $homeserver = &domain($udom,'primary');
                   1797:     my ($outcome,%results);
                   1798:     if ($homeserver ne '') {
                   1799:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1800:                            &escape($id).':'.&escape($udom),$homeserver);
                   1801:         my $host=&hostname($homeserver);
                   1802:         if ($queryid !~/^\Q$host\E\_/) {
                   1803:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1804:             return;
                   1805:         }
                   1806:         my $response = &get_query_reply($queryid);
                   1807:         my $maxtries = 5;
                   1808:         my $tries = 1;
                   1809:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1810:             $response = &get_query_reply($queryid);
                   1811:             $tries ++;
                   1812:         }
                   1813:         if (!&error($response) && $response ne 'refused') {
                   1814:             if ($response eq 'unavailable') {
                   1815:                 $outcome = $response;
                   1816:             } else {
                   1817:                 $outcome = 'ok';
                   1818:                 my @matches = split(/\n/,$response);
                   1819:                 foreach my $match (@matches) {
                   1820:                     my ($key,$value) = split(/=/,$match);
                   1821:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1822:                 }
                   1823:             }
                   1824:         }
                   1825:     }
                   1826:     my %userinfo;
                   1827:     if (ref($results{$uname}) eq 'HASH') {
                   1828:         %userinfo = %{$results{$uname}};
                   1829:     } 
                   1830:     return ($outcome,%userinfo);
                   1831: }
                   1832: 
                   1833: sub inst_rulecheck {
1.923     raeburn  1834:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1835:     my %returnhash;
                   1836:     if ($udom ne '') {
                   1837:         if (ref($rules) eq 'ARRAY') {
                   1838:             @{$rules} = map {&escape($_);} (@{$rules});
                   1839:             my $rulestr = join(':',@{$rules});
                   1840:             my $homeserver=&domain($udom,'primary');
                   1841:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1842:                 my $response;
                   1843:                 if ($item eq 'username') {                
                   1844:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1845:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1846:                                               $homeserver));
1.923     raeburn  1847:                 } elsif ($item eq 'id') {
                   1848:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1849:                                               ':'.&escape($id).':'.$rulestr,
                   1850:                                               $homeserver));
1.945     raeburn  1851:                 } elsif ($item eq 'selfcreate') {
                   1852:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1853:                                                &escape($udom).':'.&escape($uname).
                   1854:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1855:                 }
1.912     raeburn  1856:                 if ($response ne 'refused') {
                   1857:                     my @pairs=split(/\&/,$response);
                   1858:                     foreach my $item (@pairs) {
                   1859:                         my ($key,$value)=split(/=/,$item,2);
                   1860:                         $key = &unescape($key);
                   1861:                         next if ($key =~ /^error: 2 /);
                   1862:                         $returnhash{$key}=&thaw_unescape($value);
                   1863:                     }
                   1864:                 }
                   1865:             }
                   1866:         }
                   1867:     }
                   1868:     return %returnhash;
                   1869: }
                   1870: 
                   1871: sub inst_userrules {
1.923     raeburn  1872:     my ($udom,$check) = @_;
1.912     raeburn  1873:     my (%ruleshash,@ruleorder);
                   1874:     if ($udom ne '') {
                   1875:         my $homeserver=&domain($udom,'primary');
                   1876:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1877:             my $response;
                   1878:             if ($check eq 'id') {
                   1879:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1880:                                  $homeserver);
1.943     raeburn  1881:             } elsif ($check eq 'email') {
                   1882:                 $response=&reply('instemailrules:'.&escape($udom),
                   1883:                                  $homeserver);
1.923     raeburn  1884:             } else {
                   1885:                 $response=&reply('instuserrules:'.&escape($udom),
                   1886:                                  $homeserver);
                   1887:             }
1.912     raeburn  1888:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1889:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1890:                 ($response ne 'no_such_host')) {
                   1891:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1892:                 my @pairs=split(/\&/,$hashitems);
                   1893:                 foreach my $item (@pairs) {
                   1894:                     my ($key,$value)=split(/=/,$item,2);
                   1895:                     $key = &unescape($key);
                   1896:                     next if ($key =~ /^error: 2 /);
                   1897:                     $ruleshash{$key}=&thaw_unescape($value);
                   1898:                 }
                   1899:                 my @esc_order = split(/\&/,$orderitems);
                   1900:                 foreach my $item (@esc_order) {
                   1901:                     push(@ruleorder,&unescape($item));
                   1902:                 }
                   1903:             }
                   1904:         }
                   1905:     }
                   1906:     return (\%ruleshash,\@ruleorder);
                   1907: }
                   1908: 
1.976     raeburn  1909: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1910: 
                   1911: sub get_domain_defaults {
                   1912:     my ($domain) = @_;
                   1913:     my $cachetime = 60*60*24;
                   1914:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1915:     if (defined($cached)) {
                   1916:         if (ref($result) eq 'HASH') {
                   1917:             return %{$result};
                   1918:         }
                   1919:     }
                   1920:     my %domdefaults;
                   1921:     my %domconfig =
1.989     raeburn  1922:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1923:                                   'requestcourses','inststatus',
1.1073    raeburn  1924:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1925:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1926:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1927:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1928:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1929:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1930:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1931:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1932:     } else {
                   1933:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1934:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1935:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1936:     }
1.976     raeburn  1937:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1938:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1939:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1940:         } else {
                   1941:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1942:         } 
                   1943:         my @usertools = ('aboutme','blog','portfolio');
                   1944:         foreach my $item (@usertools) {
                   1945:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1946:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1947:             }
                   1948:         }
                   1949:     }
1.985     raeburn  1950:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1951:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1952:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1953:         }
                   1954:     }
1.989     raeburn  1955:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1956:         foreach my $item ('inststatustypes','inststatusorder') {
                   1957:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1958:         }
                   1959:     }
1.1047    raeburn  1960:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1961:         foreach my $item ('canuse_pdfforms') {
                   1962:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1963:         }
                   1964:     }
1.1073    raeburn  1965:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1966:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1967:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1968:         }
                   1969:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1970:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1971:         }
                   1972:     }
1.943     raeburn  1973:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1974:                                   $cachetime);
                   1975:     return %domdefaults;
                   1976: }
                   1977: 
1.344     www      1978: # --------------------------------------------------- Assign a key to a student
                   1979: 
                   1980: sub assign_access_key {
1.364     www      1981: #
                   1982: # a valid key looks like uname:udom#comments
                   1983: # comments are being appended
                   1984: #
1.498     www      1985:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1986:     $kdom=
1.620     albertel 1987:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1988:     $knum=
1.620     albertel 1989:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1990:     $cdom=
1.620     albertel 1991:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1992:     $cnum=
1.620     albertel 1993:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1994:     $udom=$env{'user.name'} unless (defined($udom));
                   1995:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1996:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1997:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1998:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1999:                                                   # assigned to this person
                   2000:                                                   # - this should not happen,
1.345     www      2001:                                                   # unless something went wrong
                   2002:                                                   # the first time around
                   2003: # ready to assign
1.364     www      2004:         $logentry=$1.'; '.$logentry;
1.496     www      2005:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2006:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2007: # key now belongs to user
1.346     www      2008: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2009:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2010:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2011:                 return 'ok';
                   2012:             } else {
                   2013:                 return 
                   2014:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2015: 	    }
                   2016:         } else {
                   2017:             return 'error: Could not assign key, try again later.';
                   2018:         }
1.364     www      2019:     } elsif (!$existing{$ckey}) {
1.345     www      2020: # the key does not exist
                   2021: 	return 'error: The key does not exist';
                   2022:     } else {
                   2023: # the key is somebody else's
                   2024: 	return 'error: The key is already in use';
                   2025:     }
1.344     www      2026: }
                   2027: 
1.364     www      2028: # ------------------------------------------ put an additional comment on a key
                   2029: 
                   2030: sub comment_access_key {
                   2031: #
                   2032: # a valid key looks like uname:udom#comments
                   2033: # comments are being appended
                   2034: #
                   2035:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2036:     $cdom=
1.620     albertel 2037:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2038:     $cnum=
1.620     albertel 2039:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2040:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2041:     if ($existing{$ckey}) {
                   2042:         $existing{$ckey}.='; '.$logentry;
                   2043: # ready to assign
1.367     www      2044:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2045:                                                  $cdom,$cnum) eq 'ok') {
                   2046: 	    return 'ok';
                   2047:         } else {
                   2048: 	    return 'error: Count not store comment.';
                   2049:         }
                   2050:     } else {
                   2051: # the key does not exist
                   2052: 	return 'error: The key does not exist';
                   2053:     }
                   2054: }
                   2055: 
1.344     www      2056: # ------------------------------------------------------ Generate a set of keys
                   2057: 
                   2058: sub generate_access_keys {
1.364     www      2059:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2060:     $cdom=
1.620     albertel 2061:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2062:     $cnum=
1.620     albertel 2063:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2064:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2065:     unless (($cdom) && ($cnum)) { return 0; }
                   2066:     if ($number>10000) { return 0; }
                   2067:     sleep(2); # make sure don't get same seed twice
                   2068:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2069:     my $total=0;
                   2070:     for (my $i=1;$i<=$number;$i++) {
                   2071:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2072:                   sprintf("%lx",int(100000*rand)).'-'.
                   2073:                   sprintf("%lx",int(100000*rand));
                   2074:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2075:        $newkey=~s/0/h/g; # and also 0 and O
                   2076:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2077:        if ($existing{$newkey}) {
                   2078:            $i--;
                   2079:        } else {
1.364     www      2080: 	  if (&put('accesskeys',
                   2081:               { $newkey => '# generated '.localtime().
1.620     albertel 2082:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2083:                            '; '.$logentry },
                   2084: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2085:               $total++;
                   2086: 	  }
                   2087:        }
                   2088:     }
1.620     albertel 2089:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2090:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2091:     return $total;
                   2092: }
                   2093: 
                   2094: # ------------------------------------------------------- Validate an accesskey
                   2095: 
                   2096: sub validate_access_key {
                   2097:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2098:     $cdom=
1.620     albertel 2099:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2100:     $cnum=
1.620     albertel 2101:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2102:     $udom=$env{'user.domain'} unless (defined($udom));
                   2103:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2104:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2105:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2106: }
                   2107: 
                   2108: # ------------------------------------- Find the section of student in a course
1.652     albertel 2109: sub devalidate_getsection_cache {
                   2110:     my ($udom,$unam,$courseid)=@_;
                   2111:     my $hashid="$udom:$unam:$courseid";
                   2112:     &devalidate_cache_new('getsection',$hashid);
                   2113: }
1.298     matthew  2114: 
1.815     albertel 2115: sub courseid_to_courseurl {
                   2116:     my ($courseid) = @_;
                   2117:     #already url style courseid
                   2118:     return $courseid if ($courseid =~ m{^/});
                   2119: 
                   2120:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2121: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2122: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2123: 	return "/$cdom/$cnum";
                   2124:     }
                   2125: 
                   2126:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2127:     if (exists($courseinfo{'num'})) {
                   2128: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2129:     }
                   2130: 
                   2131:     return undef;
                   2132: }
                   2133: 
1.298     matthew  2134: sub getsection {
                   2135:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2136:     my $cachetime=1800;
1.551     albertel 2137: 
                   2138:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2139:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2140:     if (defined($cached)) { return $result; }
                   2141: 
1.298     matthew  2142:     my %Pending; 
                   2143:     my %Expired;
                   2144:     #
                   2145:     # Each role can either have not started yet (pending), be active, 
                   2146:     #    or have expired.
                   2147:     #
                   2148:     # If there is an active role, we are done.
                   2149:     #
                   2150:     # If there is more than one role which has not started yet, 
                   2151:     #     choose the one which will start sooner
                   2152:     # If there is one role which has not started yet, return it.
                   2153:     #
                   2154:     # If there is more than one expired role, choose the one which ended last.
                   2155:     # If there is a role which has expired, return it.
                   2156:     #
1.815     albertel 2157:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2158:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2159:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2160:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2161:         my $section=$1;
                   2162:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2163:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2164:         my $now=time;
1.548     albertel 2165:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2166:             $Expired{$end}=$section;
                   2167:             next;
                   2168:         }
1.548     albertel 2169:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2170:             $Pending{$start}=$section;
                   2171:             next;
                   2172:         }
1.599     albertel 2173:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2174:     }
                   2175:     #
                   2176:     # Presumedly there will be few matching roles from the above
                   2177:     # loop and the sorting time will be negligible.
                   2178:     if (scalar(keys(%Pending))) {
                   2179:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2180:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2181:     } 
                   2182:     if (scalar(keys(%Expired))) {
                   2183:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2184:         my $time = pop(@sorted);
1.599     albertel 2185:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2186:     }
1.599     albertel 2187:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2188: }
1.70      www      2189: 
1.599     albertel 2190: sub save_cache {
                   2191:     &purge_remembered();
1.722     albertel 2192:     #&Apache::loncommon::validate_page();
1.620     albertel 2193:     undef(%env);
1.780     albertel 2194:     undef($env_loaded);
1.599     albertel 2195: }
1.452     albertel 2196: 
1.599     albertel 2197: my $to_remember=-1;
                   2198: my %remembered;
                   2199: my %accessed;
                   2200: my $kicks=0;
                   2201: my $hits=0;
1.849     albertel 2202: sub make_key {
                   2203:     my ($name,$id) = @_;
1.872     albertel 2204:     if (length($id) > 65 
                   2205: 	&& length(&escape($id)) > 200) {
                   2206: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2207:     }
1.849     albertel 2208:     return &escape($name.':'.$id);
                   2209: }
                   2210: 
1.599     albertel 2211: sub devalidate_cache_new {
                   2212:     my ($name,$id,$debug) = @_;
                   2213:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2214:     $id=&make_key($name,$id);
1.599     albertel 2215:     $memcache->delete($id);
                   2216:     delete($remembered{$id});
                   2217:     delete($accessed{$id});
                   2218: }
                   2219: 
                   2220: sub is_cached_new {
                   2221:     my ($name,$id,$debug) = @_;
1.849     albertel 2222:     $id=&make_key($name,$id);
1.599     albertel 2223:     if (exists($remembered{$id})) {
1.1133    foxr     2224: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2225: 	$accessed{$id}=[&gettimeofday()];
                   2226: 	$hits++;
                   2227: 	return ($remembered{$id},1);
                   2228:     }
                   2229:     my $value = $memcache->get($id);
                   2230:     if (!(defined($value))) {
                   2231: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2232: 	return (undef,undef);
1.416     albertel 2233:     }
1.599     albertel 2234:     if ($value eq '__undef__') {
                   2235: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2236: 	$value=undef;
                   2237:     }
                   2238:     &make_room($id,$value,$debug);
                   2239:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2240:     return ($value,1);
                   2241: }
                   2242: 
                   2243: sub do_cache_new {
                   2244:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2245:     $id=&make_key($name,$id);
1.599     albertel 2246:     my $setvalue=$value;
                   2247:     if (!defined($setvalue)) {
                   2248: 	$setvalue='__undef__';
                   2249:     }
1.623     albertel 2250:     if (!defined($time) ) {
                   2251: 	$time=600;
                   2252:     }
1.599     albertel 2253:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2254:     my $result = $memcache->set($id,$setvalue,$time);
                   2255:     if (! $result) {
1.872     albertel 2256: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2257: 	$memcache->disconnect_all();
1.872     albertel 2258:     }
1.600     albertel 2259:     # need to make a copy of $value
1.919     albertel 2260:     &make_room($id,$value,$debug);
1.599     albertel 2261:     return $value;
                   2262: }
                   2263: 
                   2264: sub make_room {
                   2265:     my ($id,$value,$debug)=@_;
1.919     albertel 2266: 
                   2267:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2268:                                     : $value;
1.599     albertel 2269:     if ($to_remember<0) { return; }
                   2270:     $accessed{$id}=[&gettimeofday()];
                   2271:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2272:     my $to_kick;
                   2273:     my $max_time=0;
                   2274:     foreach my $other (keys(%accessed)) {
                   2275: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2276: 	    $to_kick=$other;
                   2277: 	    $max_time=&tv_interval($accessed{$other});
                   2278: 	}
                   2279:     }
                   2280:     delete($remembered{$to_kick});
                   2281:     delete($accessed{$to_kick});
                   2282:     $kicks++;
                   2283:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2284:     return;
                   2285: }
                   2286: 
1.599     albertel 2287: sub purge_remembered {
1.604     albertel 2288:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2289:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2290:     undef(%remembered);
                   2291:     undef(%accessed);
1.428     albertel 2292: }
1.70      www      2293: # ------------------------------------- Read an entry from a user's environment
                   2294: 
                   2295: sub userenvironment {
                   2296:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2297:     my $items;
                   2298:     foreach my $item (@what) {
                   2299:         $items.=&escape($item).'&';
                   2300:     }
                   2301:     $items=~s/\&$//;
1.70      www      2302:     my %returnhash=();
1.1009    raeburn  2303:     my $uhome = &homeserver($unam,$udom);
                   2304:     unless ($uhome eq 'no_host') {
                   2305:         my @answer=split(/\&/, 
                   2306:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2307:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2308:             return %returnhash;
                   2309:         }
1.1009    raeburn  2310:         my $i;
                   2311:         for ($i=0;$i<=$#what;$i++) {
                   2312: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2313:         }
1.70      www      2314:     }
                   2315:     return %returnhash;
1.1       albertel 2316: }
                   2317: 
1.617     albertel 2318: # ---------------------------------------------------------- Get a studentphoto
                   2319: sub studentphoto {
                   2320:     my ($udom,$unam,$ext) = @_;
                   2321:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2322:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2323:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2324:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2325:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2326:             } else {
                   2327:                 my ($result,$perm_reqd)=
1.707     albertel 2328: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2329:                 if ($result eq 'ok') {
                   2330:                     if (!($perm_reqd eq 'yes')) {
                   2331:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2332:                     }
                   2333:                 }
                   2334:             }
                   2335:         }
                   2336:     } else {
                   2337:         my ($result,$perm_reqd) = 
1.707     albertel 2338: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2339:         if ($result eq 'ok') {
                   2340:             if (!($perm_reqd eq 'yes')) {
                   2341:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2342:             }
                   2343:         }
                   2344:     }
                   2345:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2346: }
                   2347: 
                   2348: sub retrievestudentphoto {
                   2349:     my ($udom,$unam,$ext,$type) = @_;
                   2350:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2351:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2352:     if ($ret eq 'ok') {
                   2353:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2354:         if ($type eq 'thumbnail') {
                   2355:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2356:         }
                   2357:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2358:         return $tokenurl;
                   2359:     } else {
                   2360:         if ($type eq 'thumbnail') {
                   2361:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2362:         } else { 
                   2363:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2364:         }
1.617     albertel 2365:     }
                   2366: }
                   2367: 
1.263     www      2368: # -------------------------------------------------------------------- New chat
                   2369: 
                   2370: sub chatsend {
1.724     raeburn  2371:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2372:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2373:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2374:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2375:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2376: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2377: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2378: }
                   2379: 
                   2380: # ------------------------------------------ Find current version of a resource
                   2381: 
                   2382: sub getversion {
                   2383:     my $fname=&clutter(shift);
                   2384:     unless ($fname=~/^\/res\//) { return -1; }
                   2385:     return &currentversion(&filelocation('',$fname));
                   2386: }
                   2387: 
                   2388: sub currentversion {
                   2389:     my $fname=shift;
                   2390:     my $author=$fname;
                   2391:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2392:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2393:     my $home=&homeserver($uname,$udom);
1.292     www      2394:     if ($home eq 'no_host') { 
                   2395:         return -1; 
                   2396:     }
1.1112    www      2397:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2398:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2399: 	return -1;
                   2400:     }
1.1112    www      2401:     return $answer;
1.263     www      2402: }
                   2403: 
1.1111    www      2404: #
                   2405: # Return special version number of resource if set by override, empty otherwise
                   2406: #
                   2407: sub usedversion {
                   2408:     my $fname=shift;
                   2409:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2410:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2411:     if ($urlversion) { return $urlversion; }
                   2412:     return '';
                   2413: }
                   2414: 
1.1       albertel 2415: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2416: 
1.1       albertel 2417: sub subscribe {
                   2418:     my $fname=shift;
1.761     raeburn  2419:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2420:     $fname=~s/[\n\r]//g;
1.1       albertel 2421:     my $author=$fname;
                   2422:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2423:     my ($udom,$uname)=split(/\//,$author);
                   2424:     my $home=homeserver($uname,$udom);
1.335     albertel 2425:     if ($home eq 'no_host') {
                   2426:         return 'not_found';
1.1       albertel 2427:     }
                   2428:     my $answer=reply("sub:$fname",$home);
1.64      www      2429:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2430: 	$answer.=' by '.$home;
                   2431:     }
1.1       albertel 2432:     return $answer;
                   2433: }
                   2434:     
1.8       www      2435: # -------------------------------------------------------------- Replicate file
                   2436: 
                   2437: sub repcopy {
                   2438:     my $filename=shift;
1.23      www      2439:     $filename=~s/\/+/\//g;
1.1142    raeburn  2440:     my $londocroot = $perlvar{'lonDocRoot'};
                   2441:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2442:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2443:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2444: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2445: 	return &repcopy_userfile($filename);
                   2446:     }
1.532     albertel 2447:     $filename=~s/[\n\r]//g;
1.8       www      2448:     my $transname="$filename.in.transfer";
1.828     www      2449: # FIXME: this should flock
1.607     raeburn  2450:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2451:     my $remoteurl=subscribe($filename);
1.64      www      2452:     if ($remoteurl =~ /^con_lost by/) {
                   2453: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2454:            return 'unavailable';
1.8       www      2455:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2456: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2457: 	   return 'not_found';
1.64      www      2458:     } elsif ($remoteurl =~ /^rejected by/) {
                   2459: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2460:            return 'forbidden';
1.20      www      2461:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2462:            return 'ok';
1.8       www      2463:     } else {
1.290     www      2464:         my $author=$filename;
                   2465:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2466:         my ($udom,$uname)=split(/\//,$author);
                   2467:         my $home=homeserver($uname,$udom);
                   2468:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2469:            my @parts=split(/\//,$filename);
                   2470:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2471:            if ($path ne "$londocroot/res") {
1.8       www      2472:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2473: 	       return 'bad_request';
1.8       www      2474:            }
                   2475:            my $count;
                   2476:            for ($count=5;$count<$#parts;$count++) {
                   2477:                $path.="/$parts[$count]";
                   2478:                if ((-e $path)!=1) {
                   2479: 		   mkdir($path,0777);
                   2480:                }
                   2481:            }
                   2482:            my $ua=new LWP::UserAgent;
                   2483:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2484:            my $response=$ua->request($request,$transname);
                   2485:            if ($response->is_error()) {
                   2486: 	       unlink($transname);
                   2487:                my $message=$response->status_line;
1.672     albertel 2488:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2489:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2490:                return 'unavailable';
1.8       www      2491:            } else {
1.16      www      2492: 	       if ($remoteurl!~/\.meta$/) {
                   2493:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2494:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2495:                   if ($mresponse->is_error()) {
                   2496: 		      unlink($filename.'.meta');
                   2497:                       &logthis(
1.672     albertel 2498:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2499:                   }
                   2500: 	       }
1.8       www      2501:                rename($transname,$filename);
1.607     raeburn  2502:                return 'ok';
1.8       www      2503:            }
1.290     www      2504:        }
1.8       www      2505:     }
1.330     www      2506: }
                   2507: 
                   2508: # ------------------------------------------------ Get server side include body
                   2509: sub ssi_body {
1.381     albertel 2510:     my ($filelink,%form)=@_;
1.606     matthew  2511:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2512:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2513:     }
1.953     www      2514:     my $output='';
                   2515:     my $response;
1.980     raeburn  2516:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2517:        ($output,$response)=&externalssi($filelink);
1.953     www      2518:     } else {
1.1004    droeschl 2519:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2520:        $filelink .= 'inhibitmenu=yes';
1.953     www      2521:        ($output,$response)=&ssi($filelink,%form);
                   2522:     }
1.778     albertel 2523:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2524:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2525:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2526:     if (wantarray) {
                   2527:         return ($output, $response);
                   2528:     } else {
                   2529:         return $output;
                   2530:     }
1.8       www      2531: }
                   2532: 
1.15      www      2533: # --------------------------------------------------------- Server Side Include
                   2534: 
1.782     albertel 2535: sub absolute_url {
                   2536:     my ($host_name) = @_;
                   2537:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2538:     if ($host_name eq '') {
                   2539: 	$host_name = $ENV{'SERVER_NAME'};
                   2540:     }
                   2541:     return $protocol.$host_name;
                   2542: }
                   2543: 
1.942     foxr     2544: #
                   2545: #   Server side include.
                   2546: # Parameters:
                   2547: #  fn     Possibly encrypted resource name/id.
                   2548: #  form   Hash that describes how the rendering should be done
                   2549: #         and other things.
1.944     foxr     2550: # Returns:
1.950     raeburn  2551: #   Scalar context: The content of the response.
                   2552: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2553: #     
1.15      www      2554: sub ssi {
                   2555: 
1.944     foxr     2556:     my ($fn,%form)=@_;
1.15      www      2557:     my $ua=new LWP::UserAgent;
1.23      www      2558:     my $request;
1.711     albertel 2559: 
                   2560:     $form{'no_update_last_known'}=1;
1.895     albertel 2561:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2562:     if (%form) {
1.782     albertel 2563:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2564:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2565:     } else {
1.782     albertel 2566:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2567:     }
                   2568: 
1.15      www      2569:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2570:     my $response=$ua->request($request);
                   2571: 
1.944     foxr     2572:     if (wantarray) {
                   2573: 	return ($response->content, $response);
                   2574:     } else {
                   2575: 	return $response->content;
1.942     foxr     2576:     }
1.324     www      2577: }
                   2578: 
                   2579: sub externalssi {
                   2580:     my ($url)=@_;
                   2581:     my $ua=new LWP::UserAgent;
                   2582:     my $request=new HTTP::Request('GET',$url);
                   2583:     my $response=$ua->request($request);
1.954     raeburn  2584:     if (wantarray) {
                   2585:         return ($response->content, $response);
                   2586:     } else {
                   2587:         return $response->content;
                   2588:     }
1.15      www      2589: }
1.254     www      2590: 
1.492     albertel 2591: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2592: 
                   2593: sub allowuploaded {
                   2594:     my ($srcurl,$url)=@_;
                   2595:     $url=&clutter(&declutter($url));
                   2596:     my $dir=$url;
                   2597:     $dir=~s/\/[^\/]+$//;
                   2598:     my %httpref=();
                   2599:     my $httpurl=&hreflocation('',$url);
                   2600:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2601:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2602: }
1.477     raeburn  2603: 
1.478     albertel 2604: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2605: # input: action, courseID, current domain, intended
1.637     raeburn  2606: #        path to file, source of file, instruction to parse file for objects,
                   2607: #        ref to hash for embedded objects,
                   2608: #        ref to hash for codebase of java objects.
1.1095    raeburn  2609: #        reference to scalar to accommodate mime type determined
                   2610: #          from File::MMagic if $parser = parse.
1.637     raeburn  2611: #
1.485     raeburn  2612: # output: url to file (if action was uploaddoc), 
                   2613: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2614: #
1.478     albertel 2615: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2616: # course.
1.477     raeburn  2617: #
1.478     albertel 2618: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2619: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2620: #          course's home server.
1.477     raeburn  2621: #
1.478     albertel 2622: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2623: #          be copied from $source (current location) to 
                   2624: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2625: #         and will then be copied to
                   2626: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2627: #         course's home server.
1.485     raeburn  2628: #
1.481     raeburn  2629: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2630: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2631: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2632: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2633: #         in course's home server.
1.637     raeburn  2634: #
1.477     raeburn  2635: 
                   2636: sub process_coursefile {
1.1095    raeburn  2637:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2638:         $mimetype)=@_;
1.477     raeburn  2639:     my $fetchresult;
1.638     albertel 2640:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2641:     if ($action eq 'propagate') {
1.638     albertel 2642:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2643: 			     $home);
1.481     raeburn  2644:     } else {
1.477     raeburn  2645:         my $fpath = '';
                   2646:         my $fname = $file;
1.478     albertel 2647:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2648:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2649:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2650:         if ($action eq 'copy') {
                   2651:             if ($source eq '') {
                   2652:                 $fetchresult = 'no source file';
                   2653:                 return $fetchresult;
                   2654:             } else {
                   2655:                 my $destination = $filepath.'/'.$fname;
                   2656:                 rename($source,$destination);
                   2657:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2658:                                  $home);
1.481     raeburn  2659:             }
                   2660:         } elsif ($action eq 'uploaddoc') {
                   2661:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2662:             print $fh $env{'form.'.$source};
1.481     raeburn  2663:             close($fh);
1.637     raeburn  2664:             if ($parser eq 'parse') {
1.1024    raeburn  2665:                 my $mm = new File::MMagic;
1.1095    raeburn  2666:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2667:                 if ($type eq 'text/html') {
1.1024    raeburn  2668:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2669:                     unless ($parse_result eq 'ok') {
                   2670:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2671:                     }
1.637     raeburn  2672:                 }
1.1095    raeburn  2673:                 if (ref($mimetype)) {
                   2674:                     $$mimetype = $type;
                   2675:                 } 
1.637     raeburn  2676:             }
1.477     raeburn  2677:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2678:                                  $home);
1.481     raeburn  2679:             if ($fetchresult eq 'ok') {
                   2680:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2681:             } else {
                   2682:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2683:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2684:                 return '/adm/notfound.html';
                   2685:             }
1.477     raeburn  2686:         }
                   2687:     }
1.485     raeburn  2688:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2689:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2690:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2691:     }
                   2692:     return $fetchresult;
                   2693: }
                   2694: 
1.637     raeburn  2695: sub build_filepath {
                   2696:     my ($fpath) = @_;
                   2697:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2698:     unless ($fpath eq '') {
                   2699:         my @parts=split('/',$fpath);
                   2700:         foreach my $part (@parts) {
                   2701:             $filepath.= '/'.$part;
                   2702:             if ((-e $filepath)!=1) {
                   2703:                 mkdir($filepath,0777);
                   2704:             }
                   2705:         }
                   2706:     }
                   2707:     return $filepath;
                   2708: }
                   2709: 
                   2710: sub store_edited_file {
1.638     albertel 2711:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2712:     my $file = $primary_url;
                   2713:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2714:     my $fpath = '';
                   2715:     my $fname = $file;
                   2716:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2717:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2718:     my $filepath = &build_filepath($fpath);
                   2719:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2720:     print $fh $content;
                   2721:     close($fh);
1.638     albertel 2722:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2723:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2724: 			  $home);
1.637     raeburn  2725:     if ($$fetchresult eq 'ok') {
                   2726:         return '/uploaded/'.$fpath.'/'.$fname;
                   2727:     } else {
1.638     albertel 2728:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2729: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2730:         return '/adm/notfound.html';
                   2731:     }
                   2732: }
                   2733: 
1.531     albertel 2734: sub clean_filename {
1.831     albertel 2735:     my ($fname,$args)=@_;
1.315     www      2736: # Replace Windows backslashes by forward slashes
1.257     www      2737:     $fname=~s/\\/\//g;
1.831     albertel 2738:     if (!$args->{'keep_path'}) {
                   2739:         # Get rid of everything but the actual filename
                   2740: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2741:     }
1.315     www      2742: # Replace spaces by underscores
                   2743:     $fname=~s/\s+/\_/g;
                   2744: # Replace all other weird characters by nothing
1.831     albertel 2745:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2746: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2747: # numbers
                   2748:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2749:     return $fname;
                   2750: }
1.1051    raeburn  2751: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2752: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2753: # image with the same aspect ratio as the original, but with dimensions which do 
                   2754: # not exceed $resizewidth and $resizeheight.
                   2755:  
1.984     neumanie 2756: sub resizeImage {
1.1051    raeburn  2757:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2758:     my $ima = Image::Magick->new;
                   2759:     my $resized;
                   2760:     if (-e $img_path) {
                   2761:         $ima->Read($img_path);
                   2762:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2763:             my $width = $ima->Get('width');
                   2764:             my $height = $ima->Get('height');
                   2765:             if ($width > $resizewidth) {
                   2766: 	        my $factor = $width/$resizewidth;
                   2767:                 my $newheight = $height/$factor;
                   2768:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2769:                 $resized = 1;
                   2770:             }
                   2771:         }
                   2772:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2773:             my $width = $ima->Get('width');
                   2774:             my $height = $ima->Get('height');
                   2775:             if ($height > $resizeheight) {
                   2776:                 my $factor = $height/$resizeheight;
                   2777:                 my $newwidth = $width/$factor;
                   2778:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2779:                 $resized = 1;
                   2780:             }
                   2781:         }
                   2782:         if ($resized) {
                   2783:             $ima->Write($img_path);
                   2784:         }
                   2785:     }
                   2786:     return;
1.977     amueller 2787: }
                   2788: 
1.608     albertel 2789: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2790: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2791: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2792: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2793: #                                    canceloverwrite, or ''. 
                   2794: #                   if 'coursedoc': upload to the current course
                   2795: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2796: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2797: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2798: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2799: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2800: #        $allfiles - reference to hash for embedded objects
                   2801: #        $codebase - reference to hash for codebase of java objects
                   2802: #        $desuname - username for permanent storage of uploaded file
                   2803: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2804: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2805: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2806: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2807: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2808: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2809: #                    from File::MMagic.
1.858     raeburn  2810: # 
1.686     albertel 2811: # output: url of file in userspace, or error: <message> 
                   2812: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2813: 
1.531     albertel 2814: sub userfileupload {
1.1090    raeburn  2815:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2816:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2817:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2818:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2819:     $fname=&clean_filename($fname);
1.1090    raeburn  2820:     # See if there is anything left
1.257     www      2821:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2822:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2823:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2824:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2825:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2826:         my $now = time;
1.1090    raeburn  2827:         my $filepath;
1.1095    raeburn  2828:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2829:              $filepath = 'tmp/helprequests/'.$now;
                   2830:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2831:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2832:                          '_'.$env{'user.domain'}.'/pending';
                   2833:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2834:             my ($docuname,$docudom);
                   2835:             if ($destudom) {
                   2836:                 $docudom = $destudom;
                   2837:             } else {
                   2838:                 $docudom = $env{'user.domain'};
                   2839:             }
                   2840:             if ($destuname) {
                   2841:                 $docuname = $destuname;
                   2842:             } else {
                   2843:                 $docuname = $env{'user.name'};
                   2844:             }
                   2845:             if (exists($env{'form.group'})) {
                   2846:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2847:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2848:             }
                   2849:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2850:             if ($context eq 'canceloverwrite') {
                   2851:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2852:                 if (-e  $tempfile) {
                   2853:                     my @info = stat($tempfile);
                   2854:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2855:                         unlink($tempfile);
                   2856:                     }
                   2857:                 }
                   2858:                 return;
1.523     raeburn  2859:             }
                   2860:         }
1.1090    raeburn  2861:         # Create the directory if not present
1.741     raeburn  2862:         my @parts=split(/\//,$filepath);
                   2863:         my $fullpath = $perlvar{'lonDaemons'};
                   2864:         for (my $i=0;$i<@parts;$i++) {
                   2865:             $fullpath .= '/'.$parts[$i];
                   2866:             if ((-e $fullpath)!=1) {
                   2867:                 mkdir($fullpath,0777);
                   2868:             }
                   2869:         }
                   2870:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2871:         print $fh $env{'form.'.$formname};
                   2872:         close($fh);
1.1090    raeburn  2873:         if ($context eq 'existingfile') {
                   2874:             my @info = stat($fullpath.'/'.$fname);
                   2875:             return ($fullpath.'/'.$fname,$info[9]);
                   2876:         } else {
                   2877:             return $fullpath.'/'.$fname;
                   2878:         }
1.523     raeburn  2879:     }
1.995     raeburn  2880:     if ($subdir eq 'scantron') {
                   2881:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2882:     } else {
1.995     raeburn  2883:         $fname="$subdir/$fname";
                   2884:     }
1.1090    raeburn  2885:     if ($context eq 'coursedoc') {
1.638     albertel 2886: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2887: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2888:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2889:             return &finishuserfileupload($docuname,$docudom,
                   2890: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2891: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2892:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2893:         } else {
1.620     albertel 2894:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2895:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2896: 				       $fname,$formname,$parser,
1.1095    raeburn  2897: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2898:         }
1.719     banghart 2899:     } elsif (defined($destuname)) {
                   2900:         my $docuname=$destuname;
                   2901:         my $docudom=$destudom;
1.860     raeburn  2902: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2903: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2904:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2905:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2906:     } else {
1.638     albertel 2907:         my $docuname=$env{'user.name'};
                   2908:         my $docudom=$env{'user.domain'};
1.714     raeburn  2909:         if (exists($env{'form.group'})) {
                   2910:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2911:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2912:         }
1.860     raeburn  2913: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2914: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2915:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2916:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2917:     }
1.271     www      2918: }
                   2919: 
                   2920: sub finishuserfileupload {
1.860     raeburn  2921:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2922:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2923:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2924:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2925:   
1.860     raeburn  2926:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2927:     $file=$fname;
                   2928:     if ($fname=~m|/|) {
                   2929:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2930: 	$path.=$fnamepath.'/';
                   2931:     }
1.259     www      2932:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2933:     my $count;
                   2934:     for ($count=4;$count<=$#parts;$count++) {
                   2935:         $filepath.="/$parts[$count]";
                   2936:         if ((-e $filepath)!=1) {
                   2937: 	    mkdir($filepath,0777);
                   2938:         }
                   2939:     }
1.984     neumanie 2940: 
1.258     www      2941: # Save the file
                   2942:     {
1.701     albertel 2943: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2944: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2945: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2946: 	    return '/adm/notfound.html';
                   2947: 	}
1.1090    raeburn  2948:         if ($context eq 'overwrite') {
1.1117    foxr     2949:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2950:             my $target = $filepath.'/'.$file;
                   2951:             if (-e $source) {
                   2952:                 my @info = stat($source);
                   2953:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2954:                     unless (&File::Copy::move($source,$target)) {
                   2955:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2956:                         return "Moving from $source failed";
                   2957:                     }
                   2958:                 } else {
                   2959:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2960:                 }
                   2961:             } else {
                   2962:                 return "Temporary file: $source missing";
                   2963:             }
                   2964:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2965: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2966: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2967: 	    return '/adm/notfound.html';
                   2968: 	}
1.570     albertel 2969: 	close(FH);
1.1051    raeburn  2970:         if ($resizewidth && $resizeheight) {
                   2971:             my $mm = new File::MMagic;
                   2972:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2973:             if ($mime_type =~ m{^image/}) {
                   2974: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2975:             }  
1.977     amueller 2976: 	}
1.258     www      2977:     }
1.1152    raeburn  2978:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   2979:         if (ref($mimetype)) {
                   2980:             if ($$mimetype eq '') {
                   2981:                 my $mm = new File::MMagic;
                   2982:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2983:                 $$mimetype = $type;
                   2984:             }
                   2985:         }
                   2986:     }
1.637     raeburn  2987:     if ($parser eq 'parse') {
1.1152    raeburn  2988:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  2989:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2990:                                                        $allfiles,$codebase);
                   2991:             unless ($parse_result eq 'ok') {
                   2992:                 &logthis('Failed to parse '.$filepath.$file.
                   2993: 	   	         ' for embedded media: '.$parse_result); 
                   2994:             }
1.637     raeburn  2995:         }
                   2996:     }
1.860     raeburn  2997:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2998:         my $input = $filepath.'/'.$file;
                   2999:         my $output = $filepath.'/'.'tn-'.$file;
                   3000:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3001:         system("convert -sample $thumbsize $input $output");
                   3002:         if (-e $filepath.'/'.'tn-'.$file) {
                   3003:             $fetchthumb  = 1; 
                   3004:         }
                   3005:     }
1.858     raeburn  3006:  
1.259     www      3007: # Notify homeserver to grep it
                   3008: #
1.984     neumanie 3009:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3010:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3011:     if ($fetchresult eq 'ok') {
1.860     raeburn  3012:         if ($fetchthumb) {
                   3013:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3014:             if ($thumbresult ne 'ok') {
                   3015:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3016:                          $docuhome.': '.$thumbresult);
                   3017:             }
                   3018:         }
1.259     www      3019: #
1.258     www      3020: # Return the URL to it
1.494     albertel 3021:         return '/uploaded/'.$path.$file;
1.263     www      3022:     } else {
1.494     albertel 3023:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3024: 		 ': '.$fetchresult);
1.263     www      3025:         return '/adm/notfound.html';
1.858     raeburn  3026:     }
1.493     albertel 3027: }
                   3028: 
1.637     raeburn  3029: sub extract_embedded_items {
1.961     raeburn  3030:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3031:     my @state = ();
1.1164    raeburn  3032:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3033:     my %javafiles = (
                   3034:                       codebase => '',
                   3035:                       code => '',
                   3036:                       archive => ''
                   3037:                     );
                   3038:     my %mediafiles = (
                   3039:                       src => '',
                   3040:                       movie => '',
                   3041:                      );
1.648     raeburn  3042:     my $p;
                   3043:     if ($content) {
                   3044:         $p = HTML::LCParser->new($content);
                   3045:     } else {
1.961     raeburn  3046:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3047:     }
1.641     albertel 3048:     while (my $t=$p->get_token()) {
1.640     albertel 3049: 	if ($t->[0] eq 'S') {
                   3050: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3051: 	    push(@state, $tagname);
1.648     raeburn  3052:             if (lc($tagname) eq 'allow') {
                   3053:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3054:             }
1.640     albertel 3055: 	    if (lc($tagname) eq 'img') {
                   3056: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3057: 	    }
1.886     albertel 3058: 	    if (lc($tagname) eq 'a') {
                   3059: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3060: 	    }
1.645     raeburn  3061:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3062:                 my $src;
1.645     raeburn  3063:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3064:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3065:                 } else {
1.1164    raeburn  3066:                     if ($attr->{'src'} ne '') {
                   3067:                         $src = $attr->{'src'};
                   3068:                         &add_filetype($allfiles,$src,'src');
                   3069:                     }
                   3070:                 }
                   3071:                 my $text = $p->get_trimmed_text();
                   3072:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3073:                     my @swfargs = split(/,/,$1);
                   3074:                     foreach my $item (@swfargs) {
                   3075:                         $item =~ s/["']//g;
                   3076:                         $item =~ s/^\s+//;
                   3077:                         $item =~ s/\s+$//;
                   3078:                     }
                   3079:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3080:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3081:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3082:                         } else {
                   3083:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3084:                         }
                   3085:                     }
1.645     raeburn  3086:                 }
                   3087:             }
                   3088:             if (lc($tagname) eq 'link') {
                   3089:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3090:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3091:                 }
                   3092:             }
1.640     albertel 3093: 	    if (lc($tagname) eq 'object' ||
                   3094: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3095: 		foreach my $item (keys(%javafiles)) {
                   3096: 		    $javafiles{$item} = '';
                   3097: 		}
1.1164    raeburn  3098:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3099:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3100:                 }
1.640     albertel 3101: 	    }
                   3102: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3103: 		my $name = lc($attr->{'name'});
                   3104: 		foreach my $item (keys(%javafiles)) {
                   3105: 		    if ($name eq $item) {
                   3106: 			$javafiles{$item} = $attr->{'value'};
                   3107: 			last;
                   3108: 		    }
                   3109: 		}
1.1164    raeburn  3110:                 my $pathfrom;
1.640     albertel 3111: 		foreach my $item (keys(%mediafiles)) {
                   3112: 		    if ($name eq $item) {
1.1164    raeburn  3113:                         $pathfrom = $attr->{'value'};
                   3114:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3115: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3116: 			last;
                   3117: 		    }
                   3118: 		}
1.1164    raeburn  3119:                 if ($name eq 'flashvars') {
                   3120:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3121:                 }
                   3122:                 if ($pathfrom ne '') {
                   3123:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3124:                                          $pathfrom);
                   3125:                 }
1.640     albertel 3126: 	    }
                   3127: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3128: 		foreach my $item (keys(%javafiles)) {
                   3129: 		    if ($attr->{$item}) {
                   3130: 			$javafiles{$item} = $attr->{$item};
                   3131: 			last;
                   3132: 		    }
                   3133: 		}
                   3134: 		foreach my $item (keys(%mediafiles)) {
                   3135: 		    if ($attr->{$item}) {
                   3136: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3137: 			last;
                   3138: 		    }
                   3139: 		}
1.1164    raeburn  3140:                 if (lc($tagname) eq 'embed') {
                   3141:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3142:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3143:                                              $attr->{'src'});
                   3144:                     }
                   3145:                 }
1.640     albertel 3146: 	    }
1.1164    raeburn  3147:             if ($t->[4] =~ m{/>$}) {
                   3148:                 pop(@state);  
                   3149:             }
1.640     albertel 3150: 	} elsif ($t->[0] eq 'E') {
                   3151: 	    my ($tagname) = ($t->[1]);
                   3152: 	    if ($javafiles{'codebase'} ne '') {
                   3153: 		$javafiles{'codebase'} .= '/';
                   3154: 	    }  
                   3155: 	    if (lc($tagname) eq 'applet' ||
                   3156: 		lc($tagname) eq 'object' ||
                   3157: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3158: 		) {
                   3159: 		foreach my $item (keys(%javafiles)) {
                   3160: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3161: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3162: 			&add_filetype($allfiles,$file,$item);
                   3163: 		    }
                   3164: 		}
                   3165: 	    } 
                   3166: 	    pop @state;
                   3167: 	}
                   3168:     }
1.1164    raeburn  3169:     foreach my $id (sort(keys(%flashvars))) {
                   3170:         if ($shockwave{$id} ne '') {
                   3171:             my @pairs = split(/\&/,$flashvars{$id});
                   3172:             foreach my $pair (@pairs) {
                   3173:                 my ($key,$value) = split(/\=/,$pair);
                   3174:                 if ($key eq 'thumb') {
                   3175:                     &add_filetype($allfiles,$value,$key);
                   3176:                 } elsif ($key eq 'content') {
                   3177:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3178:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3179:                     if ($ext ne '') {
                   3180:                         &add_filetype($allfiles,$path.$value,$ext);
                   3181:                     }
                   3182:                 }
                   3183:             }
                   3184:         }
                   3185:     }
1.637     raeburn  3186:     return 'ok';
                   3187: }
                   3188: 
1.639     albertel 3189: sub add_filetype {
                   3190:     my ($allfiles,$file,$type)=@_;
                   3191:     if (exists($allfiles->{$file})) {
                   3192: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3193: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3194: 	}
                   3195:     } else {
                   3196: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3197:     }
                   3198: }
                   3199: 
1.1164    raeburn  3200: sub embedded_dependency {
                   3201:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3202:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3203:         if (($identifier ne '') &&
                   3204:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3205:             ($pathfrom ne '')) {
                   3206:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3207:             foreach my $dep (@{$related->{$identifier}}) {
                   3208:                 &add_filetype($allfiles,$path.$dep,'object');
                   3209:             }
                   3210:         }
                   3211:     }
                   3212:     return;
                   3213: }
                   3214: 
1.493     albertel 3215: sub removeuploadedurl {
1.984     neumanie 3216:     my ($url)=@_;	
                   3217:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3218:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3219: }
                   3220: 
                   3221: sub removeuserfile {
                   3222:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3223:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3224:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3225:     if ($result eq 'ok') {	
1.798     raeburn  3226:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3227:             my $metafile = $fname.'.meta';
                   3228:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3229: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3230:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3231:             my $sqlresult = 
1.823     albertel 3232:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3233:                                         'portfolio_metadata',$group,
                   3234:                                         'delete');
1.798     raeburn  3235:         }
                   3236:     }
                   3237:     return $result;
1.257     www      3238: }
1.15      www      3239: 
1.530     albertel 3240: sub mkdiruserfile {
                   3241:     my ($docuname,$docudom,$dir)=@_;
                   3242:     my $home=&homeserver($docuname,$docudom);
                   3243:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3244: }
                   3245: 
1.531     albertel 3246: sub renameuserfile {
                   3247:     my ($docuname,$docudom,$old,$new)=@_;
                   3248:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3249:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3250:                         &escape("$old").':'.&escape("$new"),$home);
                   3251:     if ($result eq 'ok') {
                   3252:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3253:             my $oldmeta = $old.'.meta';
                   3254:             my $newmeta = $new.'.meta';
                   3255:             my $metaresult = 
                   3256:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3257: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3258:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3259:             my $sqlresult = 
1.823     albertel 3260:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3261:                                         'portfolio_metadata',$group,
                   3262:                                         'delete');
1.798     raeburn  3263:         }
                   3264:     }
                   3265:     return $result;
1.531     albertel 3266: }
                   3267: 
1.14      www      3268: # ------------------------------------------------------------------------- Log
                   3269: 
                   3270: sub log {
                   3271:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3272:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3273: }
                   3274: 
                   3275: # ------------------------------------------------------------------ Course Log
1.352     www      3276: #
                   3277: # This routine flushes several buffers of non-mission-critical nature
                   3278: #
1.157     www      3279: 
                   3280: sub flushcourselogs {
1.352     www      3281:     &logthis('Flushing log buffers');
                   3282: #
                   3283: # course logs
                   3284: # This is a log of all transactions in a course, which can be used
                   3285: # for data mining purposes
                   3286: #
                   3287: # It also collects the courseid database, which lists last transaction
                   3288: # times and course titles for all courseids
                   3289: #
                   3290:     my %courseidbuffer=();
1.921     raeburn  3291:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3292:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3293: 		          &escape($courselogs{$crsid}),
                   3294: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3295: 	    delete $courselogs{$crsid};
                   3296:         } else {
                   3297:             &logthis('Failed to flush log buffer for '.$crsid);
                   3298:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3299:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3300:                         " exceeded maximum size, deleting.</font>");
                   3301:                delete $courselogs{$crsid};
                   3302:             }
1.352     www      3303:         }
1.920     raeburn  3304:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3305:             'description' => $coursedescrbuf{$crsid},
                   3306:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3307:             'type'        => $coursetypebuf{$crsid},
                   3308:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3309:         };
1.191     harris41 3310:     }
1.352     www      3311: #
                   3312: # Write course id database (reverse lookup) to homeserver of courses 
                   3313: # Is used in pickcourse
                   3314: #
1.840     albertel 3315:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3316:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3317:                                     $courseidbuffer{$crs_home},
                   3318:                                     $crs_home,'timeonly');
1.352     www      3319:     }
                   3320: #
                   3321: # File accesses
                   3322: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3323: #
1.449     matthew  3324:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3325:         if ($entry =~ /___count$/) {
                   3326:             my ($dom,$name);
1.807     albertel 3327:             ($dom,$name,undef)=
1.811     albertel 3328: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3329:             if (! defined($dom) || $dom eq '' || 
                   3330:                 ! defined($name) || $name eq '') {
1.620     albertel 3331:                 my $cid = $env{'request.course.id'};
                   3332:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3333:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3334:             }
1.450     matthew  3335:             my $value = $accesshash{$entry};
                   3336:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3337:             my %temphash=($url => $value);
1.449     matthew  3338:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3339:             if ($result eq 'ok') {
                   3340:                 delete $accesshash{$entry};
                   3341:             }
                   3342:         } else {
1.811     albertel 3343:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3344:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3345:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3346:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3347:                 delete $accesshash{$entry};
                   3348:             }
1.185     www      3349:         }
1.191     harris41 3350:     }
1.352     www      3351: #
                   3352: # Roles
                   3353: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3354: #
1.800     albertel 3355:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3356:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3357: 	    split(/\:/,$entry);
                   3358:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3359:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3360:                 $rudom,$runame) eq 'ok') {
                   3361: 	    delete $userrolehash{$entry};
                   3362:         }
                   3363:     }
1.662     raeburn  3364: #
                   3365: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3366: #
                   3367:     my %domrolebuffer = ();
1.1000    raeburn  3368:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3369:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3370:         if ($domrolebuffer{$rudom}) {
                   3371:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3372:                       '='.&escape($domainrolehash{$entry});
                   3373:         } else {
                   3374:             $domrolebuffer{$rudom}.=&escape($entry).
                   3375:                       '='.&escape($domainrolehash{$entry});
                   3376:         }
                   3377:         delete $domainrolehash{$entry};
                   3378:     }
                   3379:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3380: 	my %servers = &get_servers($dom,'library');
                   3381: 	foreach my $tryserver (keys(%servers)) {
                   3382: 	    unless (&reply('domroleput:'.$dom.':'.
                   3383: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3384: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3385: 	    }
1.662     raeburn  3386:         }
                   3387:     }
1.186     www      3388:     $dumpcount++;
1.157     www      3389: }
                   3390: 
                   3391: sub courselog {
                   3392:     my $what=shift;
1.158     www      3393:     $what=time.':'.$what;
1.620     albertel 3394:     unless ($env{'request.course.id'}) { return ''; }
                   3395:     $coursedombuf{$env{'request.course.id'}}=
                   3396:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3397:     $coursenumbuf{$env{'request.course.id'}}=
                   3398:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3399:     $coursehombuf{$env{'request.course.id'}}=
                   3400:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3401:     $coursedescrbuf{$env{'request.course.id'}}=
                   3402:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3403:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3404:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3405:     $courseownerbuf{$env{'request.course.id'}}=
                   3406:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3407:     $coursetypebuf{$env{'request.course.id'}}=
                   3408:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3409:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3410: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3411:     } else {
1.620     albertel 3412: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3413:     }
1.620     albertel 3414:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3415: 	&flushcourselogs();
                   3416:     }
1.158     www      3417: }
                   3418: 
                   3419: sub courseacclog {
                   3420:     my $fnsymb=shift;
1.620     albertel 3421:     unless ($env{'request.course.id'}) { return ''; }
                   3422:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3423:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3424:         $what.=':POST';
1.583     matthew  3425:         # FIXME: Probably ought to escape things....
1.800     albertel 3426: 	foreach my $key (keys(%env)) {
                   3427:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3428:                 my $formitem = $1;
                   3429:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3430:                     $what.=':'.$formitem.'='.$env{$key};
                   3431:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3432:                     $what.=':'.$formitem.'='.$env{$key};
                   3433:                 }
1.158     www      3434:             }
1.191     harris41 3435:         }
1.583     matthew  3436:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3437:         # FIXME: We should not be depending on a form parameter that someone
                   3438:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3439:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3440:             $what.= ':POST';
                   3441:             # FIXME: Probably ought to escape things....
                   3442:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3443:                                  'crsdiscuss') {
1.620     albertel 3444:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3445:             }
                   3446:         }
1.158     www      3447:     }
                   3448:     &courselog($what);
1.149     www      3449: }
                   3450: 
1.185     www      3451: sub countacc {
                   3452:     my $url=&declutter(shift);
1.458     matthew  3453:     return if (! defined($url) || $url eq '');
1.620     albertel 3454:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3455: #
                   3456: # Mark that this url was used in this course
                   3457: #
1.620     albertel 3458:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3459: #
                   3460: # Increase the access count for this resource in this child process
                   3461: #
1.281     www      3462:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3463:     $accesshash{$key}++;
1.185     www      3464: }
1.349     www      3465: 
1.361     www      3466: sub linklog {
                   3467:     my ($from,$to)=@_;
                   3468:     $from=&declutter($from);
                   3469:     $to=&declutter($to);
                   3470:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3471:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3472: }
1.1160    www      3473: 
                   3474: sub statslog {
                   3475:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3476:     if ($users<2) { return; }
                   3477:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3478:             'course'       => $env{'request.course.id'},
                   3479:             'sections'     => '"all"',
                   3480:             'num_students' => $users,
                   3481:             'part'         => $part,
                   3482:             'symb'         => $symb,
                   3483:             'mean_tries'   => $av_attempts,
                   3484:             'deg_of_diff'  => $degdiff});
                   3485:     foreach my $key (keys(%dynstore)) {
                   3486:         $accesshash{$key}=$dynstore{$key};
                   3487:     }
                   3488: }
1.361     www      3489:   
1.349     www      3490: sub userrolelog {
                   3491:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3492:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3493:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3494:        $userrolehash
                   3495:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3496:                     =$tend.':'.$tstart;
1.662     raeburn  3497:     }
1.1169    droeschl 3498:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3499:        $userrolehash
                   3500:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3501:                     =$tend.':'.$tstart;
                   3502:     }
1.1169    droeschl 3503:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3504:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3505:        $domainrolehash
                   3506:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3507:                     = $tend.':'.$tstart;
                   3508:     }
1.351     www      3509: }
                   3510: 
1.957     raeburn  3511: sub courserolelog {
                   3512:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3513:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3514:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3515:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3516:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3517:         ($trole eq 'co')) {
1.957     raeburn  3518:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3519:             my $cdom = $1;
                   3520:             my $cnum = $2;
                   3521:             my $sec = $3;
                   3522:             my $namespace = 'rolelog';
                   3523:             my %storehash = (
                   3524:                                role    => $trole,
                   3525:                                start   => $tstart,
                   3526:                                end     => $tend,
                   3527:                                selfenroll => $selfenroll,
                   3528:                                context    => $context,
                   3529:                             );
                   3530:             if ($trole eq 'gr') {
                   3531:                 $namespace = 'groupslog';
                   3532:                 $storehash{'group'} = $sec;
                   3533:             } else {
                   3534:                 $storehash{'section'} = $sec;
                   3535:             }
                   3536:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3537:             if (($trole ne 'st') || ($sec ne '')) {
                   3538:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3539:             }
1.957     raeburn  3540:         }
                   3541:     }
                   3542:     return;
                   3543: }
                   3544: 
1.351     www      3545: sub get_course_adv_roles {
1.948     raeburn  3546:     my ($cid,$codes) = @_;
1.620     albertel 3547:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3548:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3549:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3550:     my %nothide=();
1.800     albertel 3551:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3552:         if ($user !~ /:/) {
                   3553: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3554:         } else {
                   3555:             $nothide{$user}=1;
                   3556:         }
1.470     www      3557:     }
1.351     www      3558:     my %returnhash=();
                   3559:     my %dumphash=
                   3560:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3561:     my $now=time;
1.997     raeburn  3562:     my %privileged;
1.1000    raeburn  3563:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3564: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3565:         if (($tstart) && ($tstart<0)) { next; }
                   3566:         if (($tend) && ($tend<$now)) { next; }
                   3567:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3568:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3569: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3570:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3571:             my %dompersonnel =
1.998     raeburn  3572:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3573:             $privileged{$domain} = {};
                   3574:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3575:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3576:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3577:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3578:                         $privileged{$udom}{$uname} = 1;
                   3579:                     }
                   3580:                 }
                   3581:             }
                   3582:         }
                   3583:         if ((exists($privileged{$domain}{$username})) && 
                   3584:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3585: 	if ($role eq 'cr') { next; }
1.948     raeburn  3586:         if ($codes) {
                   3587:             if ($section) { $role .= ':'.$section; }
                   3588:             if ($returnhash{$role}) {
                   3589:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3590:             } else {
                   3591:                 $returnhash{$role}=$username.':'.$domain;
                   3592:             }
1.351     www      3593:         } else {
1.988     raeburn  3594:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3595:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3596:             if ($returnhash{$key}) {
                   3597: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3598:             } else {
                   3599:                 $returnhash{$key}=$username.':'.$domain;
                   3600:             }
1.351     www      3601:         }
1.948     raeburn  3602:     }
1.400     www      3603:     return %returnhash;
                   3604: }
                   3605: 
                   3606: sub get_my_roles {
1.937     raeburn  3607:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3608:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3609:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3610:     my (%dumphash,%nothide);
1.1086    raeburn  3611:     if ($context eq 'userroles') {
1.1166    raeburn  3612:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3613:     } else {
                   3614:         %dumphash=
1.400     www      3615:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3616:         if ($hidepriv) {
                   3617:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3618:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3619:                 if ($user !~ /:/) {
                   3620:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3621:                 } else {
                   3622:                     $nothide{$user} = 1;
                   3623:                 }
                   3624:             }
                   3625:         }
1.858     raeburn  3626:     }
1.400     www      3627:     my %returnhash=();
                   3628:     my $now=time;
1.999     raeburn  3629:     my %privileged;
1.800     albertel 3630:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3631:         my ($role,$tend,$tstart);
                   3632:         if ($context eq 'userroles') {
1.1149    raeburn  3633:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3634: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3635:         } else {
                   3636:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3637:         }
1.400     www      3638:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3639:         my $status = 'active';
1.939     raeburn  3640:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3641:             $status = 'previous';
                   3642:         } 
                   3643:         if (($tstart) && ($now<$tstart)) {
                   3644:             $status = 'future';
                   3645:         }
                   3646:         if (ref($types) eq 'ARRAY') {
                   3647:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3648:                 next;
                   3649:             } 
                   3650:         } else {
                   3651:             if ($status ne 'active') {
                   3652:                 next;
                   3653:             }
                   3654:         }
1.867     raeburn  3655:         my ($rolecode,$username,$domain,$section,$area);
                   3656:         if ($context eq 'userroles') {
                   3657:             ($area,$rolecode) = split(/_/,$entry);
                   3658:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3659:         } else {
                   3660:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3661:         }
1.832     raeburn  3662:         if (ref($roledoms) eq 'ARRAY') {
                   3663:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3664:                 next;
                   3665:             }
                   3666:         }
                   3667:         if (ref($roles) eq 'ARRAY') {
                   3668:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3669:                 if ($role =~ /^cr\//) {
                   3670:                     if (!grep(/^cr$/,@{$roles})) {
                   3671:                         next;
                   3672:                     }
1.1104    raeburn  3673:                 } elsif ($role =~ /^gr\//) {
                   3674:                     if (!grep(/^gr$/,@{$roles})) {
                   3675:                         next;
                   3676:                     }
1.922     raeburn  3677:                 } else {
                   3678:                     next;
                   3679:                 }
1.832     raeburn  3680:             }
1.867     raeburn  3681:         }
1.937     raeburn  3682:         if ($hidepriv) {
1.999     raeburn  3683:             if ($context eq 'userroles') {
                   3684:                 if ((&privileged($username,$domain)) &&
                   3685:                     (!$nothide{$username.':'.$domain})) {
                   3686:                     next;
                   3687:                 }
                   3688:             } else {
                   3689:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3690:                     my %dompersonnel =
                   3691:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3692:                     $privileged{$domain} = {};
                   3693:                     if (keys(%dompersonnel)) {
                   3694:                         foreach my $server (keys(%dompersonnel)) {
                   3695:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3696:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3697:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3698:                                     $privileged{$udom}{$uname} = $trole;
                   3699:                                 }
                   3700:                             }
                   3701:                         }
                   3702:                     }
                   3703:                 }
                   3704:                 if (exists($privileged{$domain}{$username})) {
                   3705:                     if (!$nothide{$username.':'.$domain}) {
                   3706:                         next;
                   3707:                     }
                   3708:                 }
1.937     raeburn  3709:             }
                   3710:         }
1.933     raeburn  3711:         if ($withsec) {
                   3712:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3713:                 $tstart.':'.$tend;
                   3714:         } else {
                   3715:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3716:         }
1.832     raeburn  3717:     }
1.373     www      3718:     return %returnhash;
1.399     www      3719: }
                   3720: 
                   3721: # ----------------------------------------------------- Frontpage Announcements
                   3722: #
                   3723: #
                   3724: 
                   3725: sub postannounce {
                   3726:     my ($server,$text)=@_;
1.844     albertel 3727:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3728:     unless ($text=~/\w/) { $text=''; }
                   3729:     return &reply('setannounce:'.&escape($text),$server);
                   3730: }
                   3731: 
                   3732: sub getannounce {
1.448     albertel 3733: 
                   3734:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3735: 	my $announcement='';
1.800     albertel 3736: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3737: 	close($fh);
1.399     www      3738: 	if ($announcement=~/\w/) { 
                   3739: 	    return 
                   3740:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3741:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3742: 	} else {
                   3743: 	    return '';
                   3744: 	}
                   3745:     } else {
                   3746: 	return '';
                   3747:     }
1.351     www      3748: }
1.353     www      3749: 
                   3750: # ---------------------------------------------------------- Course ID routines
                   3751: # Deal with domain's nohist_courseid.db files
                   3752: #
                   3753: 
                   3754: sub courseidput {
1.921     raeburn  3755:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3756:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3757:     my $outcome;
                   3758:     if ($caller eq 'timeonly') {
                   3759:         my $cids = '';
                   3760:         foreach my $item (keys(%$storehash)) {
                   3761:             $cids.=&escape($item).'&';
                   3762:         }
                   3763:         $cids=~s/\&$//;
                   3764:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3765:                           $coursehome);       
                   3766:     } else {
                   3767:         my $items = '';
                   3768:         foreach my $item (keys(%$storehash)) {
                   3769:             $items.= &escape($item).'='.
                   3770:                      &freeze_escape($$storehash{$item}).'&';
                   3771:         }
                   3772:         $items=~s/\&$//;
                   3773:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3774:                           $coursehome);
1.918     raeburn  3775:     }
                   3776:     if ($outcome eq 'unknown_cmd') {
                   3777:         my $what;
                   3778:         foreach my $cid (keys(%$storehash)) {
                   3779:             $what .= &escape($cid).'=';
1.921     raeburn  3780:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3781:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3782:             }
                   3783:             $what =~ s/\:$/&/;
                   3784:         }
                   3785:         $what =~ s/\&$//;  
                   3786:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3787:     } else {
                   3788:         return $outcome;
                   3789:     }
1.353     www      3790: }
                   3791: 
                   3792: sub courseiddump {
1.921     raeburn  3793:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3794:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3795:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3796:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3797:     my $as_hash = 1;
                   3798:     my %returnhash;
                   3799:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3800:     my %libserv = &all_library();
                   3801:     foreach my $tryserver (keys(%libserv)) {
                   3802:         if ( (  $hostidflag == 1 
                   3803: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3804: 	     || (!defined($hostidflag)) ) {
                   3805: 
1.918     raeburn  3806: 	    if (($domfilter eq '') ||
                   3807: 		(&host_domain($tryserver) eq $domfilter)) {
                   3808:                 my $rep = 
                   3809:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3810:                          $sincefilter.':'.&escape($descfilter).':'.
                   3811:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3812:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3813:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3814:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3815:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3816:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3817:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3818:                          &escape($creationcontext).':'.$domcloner,
                   3819:                          $tryserver);
1.918     raeburn  3820:                 my @pairs=split(/\&/,$rep);
                   3821:                 foreach my $item (@pairs) {
                   3822:                     my ($key,$value)=split(/\=/,$item,2);
                   3823:                     $key = &unescape($key);
                   3824:                     next if ($key =~ /^error: 2 /);
                   3825:                     my $result = &thaw_unescape($value);
                   3826:                     if (ref($result) eq 'HASH') {
                   3827:                         $returnhash{$key}=$result;
                   3828:                     } else {
1.921     raeburn  3829:                         my @responses = split(/:/,$value);
                   3830:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3831:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3832:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3833:                         }
1.1008    raeburn  3834:                     }
1.353     www      3835:                 }
                   3836:             }
                   3837:         }
                   3838:     }
                   3839:     return %returnhash;
                   3840: }
                   3841: 
1.1055    raeburn  3842: sub courselastaccess {
                   3843:     my ($cdom,$cnum,$hostidref) = @_;
                   3844:     my %returnhash;
                   3845:     if ($cdom && $cnum) {
                   3846:         my $chome = &homeserver($cnum,$cdom);
                   3847:         if ($chome ne 'no_host') {
                   3848:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3849:             &extract_lastaccess(\%returnhash,$rep);
                   3850:         }
                   3851:     } else {
                   3852:         if (!$cdom) { $cdom=''; }
                   3853:         my %libserv = &all_library();
                   3854:         foreach my $tryserver (keys(%libserv)) {
                   3855:             if (ref($hostidref) eq 'ARRAY') {
                   3856:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3857:             } 
                   3858:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3859:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3860:                 &extract_lastaccess(\%returnhash,$rep);
                   3861:             }
                   3862:         }
                   3863:     }
                   3864:     return %returnhash;
                   3865: }
                   3866: 
                   3867: sub extract_lastaccess {
                   3868:     my ($returnhash,$rep) = @_;
                   3869:     if (ref($returnhash) eq 'HASH') {
                   3870:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3871:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3872:                  $rep eq '') {
                   3873:             my @pairs=split(/\&/,$rep);
                   3874:             foreach my $item (@pairs) {
                   3875:                 my ($key,$value)=split(/\=/,$item,2);
                   3876:                 $key = &unescape($key);
                   3877:                 next if ($key =~ /^error: 2 /);
                   3878:                 $returnhash->{$key} = &thaw_unescape($value);
                   3879:             }
                   3880:         }
                   3881:     }
                   3882:     return;
                   3883: }
                   3884: 
1.658     raeburn  3885: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3886: 
                   3887: sub dcmailput {
1.685     raeburn  3888:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3889:     my $status = &Apache::lonnet::critical(
1.740     www      3890:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3891:        &escape($message),$server);
1.662     raeburn  3892:     return $status;
                   3893: }
                   3894: 
1.658     raeburn  3895: sub dcmaildump {
                   3896:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3897:     my %returnhash=();
1.846     albertel 3898: 
                   3899:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3900:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3901:                                                          &escape($enddate).':';
                   3902: 	my @esc_senders=map { &escape($_)} @$senders;
                   3903: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3904: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3905:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3906:             if (($key) && ($value)) {
                   3907:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3908:             }
                   3909:         }
                   3910:     }
                   3911:     return %returnhash;
                   3912: }
1.662     raeburn  3913: # ---------------------------------------------------------- Domain roles
                   3914: 
                   3915: sub get_domain_roles {
                   3916:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3917:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3918:         $startdate = '.';
                   3919:     }
1.1018    raeburn  3920:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3921:         $enddate = '.';
                   3922:     }
1.922     raeburn  3923:     my $rolelist;
                   3924:     if (ref($roles) eq 'ARRAY') {
                   3925:         $rolelist = join(':',@{$roles});
                   3926:     }
1.662     raeburn  3927:     my %personnel = ();
1.841     albertel 3928: 
                   3929:     my %servers = &get_servers($dom,'library');
                   3930:     foreach my $tryserver (keys(%servers)) {
                   3931: 	%{$personnel{$tryserver}}=();
                   3932: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3933: 					    &escape($startdate).':'.
                   3934: 					    &escape($enddate).':'.
                   3935: 					    &escape($rolelist), $tryserver))) {
                   3936: 	    my ($key,$value) = split(/\=/,$line,2);
                   3937: 	    if (($key) && ($value)) {
                   3938: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3939: 	    }
                   3940: 	}
1.662     raeburn  3941:     }
                   3942:     return %personnel;
                   3943: }
1.658     raeburn  3944: 
1.1057    www      3945: # ----------------------------------------------------------- Interval timing 
1.149     www      3946: 
1.1153    www      3947: {
                   3948: # Caches needed for speedup of navmaps
                   3949: # We don't want to cache this for very long at all (5 seconds at most)
                   3950: # 
                   3951: # The user for whom we cache
                   3952: my $cachedkey='';
                   3953: # The cached times for this user
                   3954: my %cachedtimes=();
                   3955: # When this was last done
                   3956: my $cachedtime=();
                   3957: 
                   3958: sub load_all_first_access {
1.1154    raeburn  3959:     my ($uname,$udom)=@_;
1.1156    www      3960:     if (($cachedkey eq $uname.':'.$udom) &&
1.1154    raeburn  3961:         (abs($cachedtime-time)<5)) {
                   3962:         return;
                   3963:     }
                   3964:     $cachedtime=time;
                   3965:     $cachedkey=$uname.':'.$udom;
                   3966:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      3967: }
                   3968: 
1.504     albertel 3969: sub get_first_access {
1.1162    raeburn  3970:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 3971:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3972:     if ($argsymb) { $symb=$argsymb; }
                   3973:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  3974:     if ($argmap) { $map = $argmap; }
1.926     albertel 3975:     if ($type eq 'course') {
                   3976: 	$res='course';
                   3977:     } elsif ($type eq 'map') {
1.588     albertel 3978: 	$res=&symbread($map);
                   3979:     } else {
                   3980: 	$res=$symb;
                   3981:     }
1.1153    www      3982:     &load_all_first_access($uname,$udom);
                   3983:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 3984: }
                   3985: 
                   3986: sub set_first_access {
1.1162    raeburn  3987:     my ($type,$interval)=@_;
1.790     albertel 3988:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3989:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3990:     if ($type eq 'course') {
                   3991: 	$res='course';
                   3992:     } elsif ($type eq 'map') {
1.588     albertel 3993: 	$res=&symbread($map);
                   3994:     } else {
                   3995: 	$res=$symb;
                   3996:     }
1.1153    www      3997:     $cachedkey='';
1.1162    raeburn  3998:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 3999:     if (!$firstaccess) {
1.1162    raeburn  4000:         my $start = time;
                   4001: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4002:                           $udom,$uname);
                   4003:         if ($putres eq 'ok') {
                   4004:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4005:                  $udom,$uname); 
                   4006:             &appenv(
                   4007:                      {
                   4008:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4009:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4010:                      }
                   4011:                   );
                   4012:         }
                   4013:         return $putres;
1.505     albertel 4014:     }
                   4015:     return 'already_set';
1.504     albertel 4016: }
1.1153    www      4017: }
1.110     www      4018: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4019: 
                   4020: sub expirespread {
                   4021:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4022:     my $cid=$env{'request.course.id'}; 
1.110     www      4023:     if ($cid) {
                   4024:        my $now=time;
                   4025:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4026:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4027:                             $env{'course.'.$cid.'.num'}.
1.110     www      4028: 	        	    ':nohist_expirationdates:'.
                   4029:                             &escape($key).'='.$now,
1.620     albertel 4030:                             $env{'course.'.$cid.'.home'})
1.110     www      4031:     }
                   4032:     return 'ok';
1.14      www      4033: }
                   4034: 
1.109     www      4035: # ----------------------------------------------------- Devalidate Spreadsheets
                   4036: 
                   4037: sub devalidate {
1.325     www      4038:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4039:     my $cid=$env{'request.course.id'}; 
1.109     www      4040:     if ($cid) {
1.391     matthew  4041:         # delete the stored spreadsheets for
                   4042:         # - the student level sheet of this user in course's homespace
                   4043:         # - the assessment level sheet for this resource 
                   4044:         #   for this user in user's homespace
1.553     albertel 4045: 	# - current conditional state info
1.325     www      4046: 	my $key=$uname.':'.$udom.':';
1.109     www      4047:         my $status=
1.299     matthew  4048: 	    &del('nohist_calculatedsheets',
1.391     matthew  4049: 		 [$key.'studentcalc:'],
1.620     albertel 4050: 		 $env{'course.'.$cid.'.domain'},
                   4051: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4052: 		.' '.
                   4053: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4054: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4055:         unless ($status eq 'ok ok') {
                   4056:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4057:                     $uname.' at '.$udom.' for '.
1.109     www      4058: 		    $symb.': '.$status);
1.133     albertel 4059:         }
1.553     albertel 4060: 	&delenv('user.state.'.$cid);
1.109     www      4061:     }
                   4062: }
                   4063: 
1.265     albertel 4064: sub get_scalar {
                   4065:     my ($string,$end) = @_;
                   4066:     my $value;
                   4067:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4068: 	$value = $1;
                   4069:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4070: 	$value = $1;
                   4071:     }
                   4072:     return &unescape($value);
                   4073: }
                   4074: 
                   4075: sub array2str {
                   4076:   my (@array) = @_;
                   4077:   my $result=&arrayref2str(\@array);
                   4078:   $result=~s/^__ARRAY_REF__//;
                   4079:   $result=~s/__END_ARRAY_REF__$//;
                   4080:   return $result;
                   4081: }
                   4082: 
1.204     albertel 4083: sub arrayref2str {
                   4084:   my ($arrayref) = @_;
1.265     albertel 4085:   my $result='__ARRAY_REF__';
1.204     albertel 4086:   foreach my $elem (@$arrayref) {
1.265     albertel 4087:     if(ref($elem) eq 'ARRAY') {
                   4088:       $result.=&arrayref2str($elem).'&';
                   4089:     } elsif(ref($elem) eq 'HASH') {
                   4090:       $result.=&hashref2str($elem).'&';
                   4091:     } elsif(ref($elem)) {
                   4092:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4093:     } else {
                   4094:       $result.=&escape($elem).'&';
                   4095:     }
                   4096:   }
                   4097:   $result=~s/\&$//;
1.265     albertel 4098:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4099:   return $result;
                   4100: }
                   4101: 
1.168     albertel 4102: sub hash2str {
1.204     albertel 4103:   my (%hash) = @_;
                   4104:   my $result=&hashref2str(\%hash);
1.265     albertel 4105:   $result=~s/^__HASH_REF__//;
                   4106:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4107:   return $result;
                   4108: }
                   4109: 
                   4110: sub hashref2str {
                   4111:   my ($hashref)=@_;
1.265     albertel 4112:   my $result='__HASH_REF__';
1.800     albertel 4113:   foreach my $key (sort(keys(%$hashref))) {
                   4114:     if (ref($key) eq 'ARRAY') {
                   4115:       $result.=&arrayref2str($key).'=';
                   4116:     } elsif (ref($key) eq 'HASH') {
                   4117:       $result.=&hashref2str($key).'=';
                   4118:     } elsif (ref($key)) {
1.265     albertel 4119:       $result.='=';
1.800     albertel 4120:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4121:     } else {
1.1132    raeburn  4122: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4123:     }
                   4124: 
1.800     albertel 4125:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4126:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4127:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4128:       $result.=&hashref2str($hashref->{$key}).'&';
                   4129:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4130:        $result.='&';
1.800     albertel 4131:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4132:     } else {
1.800     albertel 4133:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4134:     }
                   4135:   }
1.168     albertel 4136:   $result=~s/\&$//;
1.265     albertel 4137:   $result .= '__END_HASH_REF__';
1.168     albertel 4138:   return $result;
                   4139: }
                   4140: 
                   4141: sub str2hash {
1.265     albertel 4142:     my ($string)=@_;
                   4143:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4144:     return %$hash;
                   4145: }
                   4146: 
                   4147: sub str2hashref {
1.168     albertel 4148:   my ($string) = @_;
1.265     albertel 4149: 
                   4150:   my %hash;
                   4151: 
                   4152:   if($string !~ /^__HASH_REF__/) {
                   4153:       if (! ($string eq '' || !defined($string))) {
                   4154: 	  $hash{'error'}='Not hash reference';
                   4155:       }
                   4156:       return (\%hash, $string);
                   4157:   }
                   4158: 
                   4159:   $string =~ s/^__HASH_REF__//;
                   4160: 
                   4161:   while($string !~ /^__END_HASH_REF__/) {
                   4162:       #key
                   4163:       my $key='';
                   4164:       if($string =~ /^__HASH_REF__/) {
                   4165:           ($key, $string)=&str2hashref($string);
                   4166:           if(defined($key->{'error'})) {
                   4167:               $hash{'error'}='Bad data';
                   4168:               return (\%hash, $string);
                   4169:           }
                   4170:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4171:           ($key, $string)=&str2arrayref($string);
                   4172:           if($key->[0] eq 'Array reference error') {
                   4173:               $hash{'error'}='Bad data';
                   4174:               return (\%hash, $string);
                   4175:           }
                   4176:       } else {
                   4177:           $string =~ s/^(.*?)=//;
1.267     albertel 4178: 	  $key=&unescape($1);
1.265     albertel 4179:       }
                   4180:       $string =~ s/^=//;
                   4181: 
                   4182:       #value
                   4183:       my $value='';
                   4184:       if($string =~ /^__HASH_REF__/) {
                   4185:           ($value, $string)=&str2hashref($string);
                   4186:           if(defined($value->{'error'})) {
                   4187:               $hash{'error'}='Bad data';
                   4188:               return (\%hash, $string);
                   4189:           }
                   4190:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4191:           ($value, $string)=&str2arrayref($string);
                   4192:           if($value->[0] eq 'Array reference error') {
                   4193:               $hash{'error'}='Bad data';
                   4194:               return (\%hash, $string);
                   4195:           }
                   4196:       } else {
                   4197: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4198:       }
                   4199:       $string =~ s/^&//;
                   4200: 
                   4201:       $hash{$key}=$value;
1.204     albertel 4202:   }
1.265     albertel 4203: 
                   4204:   $string =~ s/^__END_HASH_REF__//;
                   4205: 
                   4206:   return (\%hash, $string);
1.204     albertel 4207: }
                   4208: 
                   4209: sub str2array {
1.265     albertel 4210:     my ($string)=@_;
                   4211:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4212:     return @$array;
                   4213: }
                   4214: 
                   4215: sub str2arrayref {
1.204     albertel 4216:   my ($string) = @_;
1.265     albertel 4217:   my @array;
                   4218: 
                   4219:   if($string !~ /^__ARRAY_REF__/) {
                   4220:       if (! ($string eq '' || !defined($string))) {
                   4221: 	  $array[0]='Array reference error';
                   4222:       }
                   4223:       return (\@array, $string);
                   4224:   }
                   4225: 
                   4226:   $string =~ s/^__ARRAY_REF__//;
                   4227: 
                   4228:   while($string !~ /^__END_ARRAY_REF__/) {
                   4229:       my $value='';
                   4230:       if($string =~ /^__HASH_REF__/) {
                   4231:           ($value, $string)=&str2hashref($string);
                   4232:           if(defined($value->{'error'})) {
                   4233:               $array[0] ='Array reference error';
                   4234:               return (\@array, $string);
                   4235:           }
                   4236:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4237:           ($value, $string)=&str2arrayref($string);
                   4238:           if($value->[0] eq 'Array reference error') {
                   4239:               $array[0] ='Array reference error';
                   4240:               return (\@array, $string);
                   4241:           }
                   4242:       } else {
                   4243: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4244:       }
                   4245:       $string =~ s/^&//;
                   4246: 
                   4247:       push(@array, $value);
1.191     harris41 4248:   }
1.265     albertel 4249: 
                   4250:   $string =~ s/^__END_ARRAY_REF__//;
                   4251: 
                   4252:   return (\@array, $string);
1.168     albertel 4253: }
                   4254: 
1.167     albertel 4255: # -------------------------------------------------------------------Temp Store
                   4256: 
1.168     albertel 4257: sub tmpreset {
                   4258:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4259:   if (!$symb) {
                   4260:     $symb=&symbread();
1.620     albertel 4261:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4262:   }
                   4263:   $symb=escape($symb);
                   4264: 
1.620     albertel 4265:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4266:   $namespace=~s/\//\_/g;
                   4267:   $namespace=~s/\W//g;
                   4268: 
1.620     albertel 4269:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4270:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4271:   if ($domain eq 'public' && $stuname eq 'public') {
                   4272:       $stuname=$ENV{'REMOTE_ADDR'};
                   4273:   }
1.1117    foxr     4274:   my $path=LONCAPA::tempdir();
1.168     albertel 4275:   my %hash;
                   4276:   if (tie(%hash,'GDBM_File',
                   4277: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4278: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4279:     foreach my $key (keys(%hash)) {
1.180     albertel 4280:       if ($key=~ /:$symb/) {
1.168     albertel 4281: 	delete($hash{$key});
                   4282:       }
                   4283:     }
                   4284:   }
                   4285: }
                   4286: 
1.167     albertel 4287: sub tmpstore {
1.168     albertel 4288:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4289: 
                   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: 
                   4296:   if (!$namespace) {
                   4297:     # I don't think we would ever want to store this for a course.
                   4298:     # it seems this will only be used if we don't have a course.
1.620     albertel 4299:     #$namespace=$env{'request.course.id'};
1.168     albertel 4300:     #if (!$namespace) {
1.620     albertel 4301:       $namespace=$env{'request.state'};
1.168     albertel 4302:     #}
                   4303:   }
                   4304:   $namespace=~s/\//\_/g;
                   4305:   $namespace=~s/\W//g;
1.620     albertel 4306:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4307:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4308:   if ($domain eq 'public' && $stuname eq 'public') {
                   4309:       $stuname=$ENV{'REMOTE_ADDR'};
                   4310:   }
1.168     albertel 4311:   my $now=time;
                   4312:   my %hash;
1.1117    foxr     4313:   my $path=LONCAPA::tempdir();
1.168     albertel 4314:   if (tie(%hash,'GDBM_File',
                   4315: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4316: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4317:     $hash{"version:$symb"}++;
                   4318:     my $version=$hash{"version:$symb"};
                   4319:     my $allkeys=''; 
                   4320:     foreach my $key (keys(%$storehash)) {
                   4321:       $allkeys.=$key.':';
1.591     albertel 4322:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4323:     }
                   4324:     $hash{"$version:$symb:timestamp"}=$now;
                   4325:     $allkeys.='timestamp';
                   4326:     $hash{"$version:keys:$symb"}=$allkeys;
                   4327:     if (untie(%hash)) {
                   4328:       return 'ok';
                   4329:     } else {
                   4330:       return "error:$!";
                   4331:     }
                   4332:   } else {
                   4333:     return "error:$!";
                   4334:   }
                   4335: }
1.167     albertel 4336: 
1.168     albertel 4337: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4338: 
1.168     albertel 4339: sub tmprestore {
                   4340:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4341: 
1.168     albertel 4342:   if (!$symb) {
                   4343:     $symb=&symbread();
1.620     albertel 4344:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4345:   }
                   4346:   $symb=escape($symb);
                   4347: 
1.620     albertel 4348:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4349: 
1.620     albertel 4350:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4351:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4352:   if ($domain eq 'public' && $stuname eq 'public') {
                   4353:       $stuname=$ENV{'REMOTE_ADDR'};
                   4354:   }
1.168     albertel 4355:   my %returnhash;
                   4356:   $namespace=~s/\//\_/g;
                   4357:   $namespace=~s/\W//g;
                   4358:   my %hash;
1.1117    foxr     4359:   my $path=LONCAPA::tempdir();
1.168     albertel 4360:   if (tie(%hash,'GDBM_File',
                   4361: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4362: 	  &GDBM_READER(),0640)) {
1.168     albertel 4363:     my $version=$hash{"version:$symb"};
                   4364:     $returnhash{'version'}=$version;
                   4365:     my $scope;
                   4366:     for ($scope=1;$scope<=$version;$scope++) {
                   4367:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4368:       my @keys=split(/:/,$vkeys);
                   4369:       my $key;
                   4370:       $returnhash{"$scope:keys"}=$vkeys;
                   4371:       foreach $key (@keys) {
1.591     albertel 4372: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4373: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4374:       }
                   4375:     }
1.168     albertel 4376:     if (!(untie(%hash))) {
                   4377:       return "error:$!";
                   4378:     }
                   4379:   } else {
                   4380:     return "error:$!";
                   4381:   }
                   4382:   return %returnhash;
1.167     albertel 4383: }
                   4384: 
1.9       www      4385: # ----------------------------------------------------------------------- Store
                   4386: 
                   4387: sub store {
1.124     www      4388:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4389:     my $home='';
                   4390: 
1.168     albertel 4391:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4392: 
1.213     www      4393:     $symb=&symbclean($symb);
1.122     albertel 4394:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4395: 
1.620     albertel 4396:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4397:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4398: 
                   4399:     &devalidate($symb,$stuname,$domain);
1.109     www      4400: 
                   4401:     $symb=escape($symb);
1.187     www      4402:     if (!$namespace) { 
1.620     albertel 4403:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4404:           return ''; 
                   4405:        } 
                   4406:     }
1.620     albertel 4407:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4408: 
                   4409:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4410:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4411: 
1.12      www      4412:     my $namevalue='';
1.800     albertel 4413:     foreach my $key (keys(%$storehash)) {
                   4414:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4415:     }
1.12      www      4416:     $namevalue=~s/\&$//;
1.187     www      4417:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4418:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4419: }
                   4420: 
1.47      www      4421: # -------------------------------------------------------------- Critical Store
                   4422: 
                   4423: sub cstore {
1.124     www      4424:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4425:     my $home='';
                   4426: 
1.168     albertel 4427:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4428: 
1.213     www      4429:     $symb=&symbclean($symb);
1.122     albertel 4430:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4431: 
1.620     albertel 4432:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4433:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4434: 
                   4435:     &devalidate($symb,$stuname,$domain);
1.109     www      4436: 
                   4437:     $symb=escape($symb);
1.187     www      4438:     if (!$namespace) { 
1.620     albertel 4439:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4440:           return ''; 
                   4441:        } 
                   4442:     }
1.620     albertel 4443:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4444: 
                   4445:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4446:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4447: 
1.47      www      4448:     my $namevalue='';
1.800     albertel 4449:     foreach my $key (keys(%$storehash)) {
                   4450:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4451:     }
1.47      www      4452:     $namevalue=~s/\&$//;
1.187     www      4453:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4454:     return critical
                   4455:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4456: }
                   4457: 
1.9       www      4458: # --------------------------------------------------------------------- Restore
                   4459: 
                   4460: sub restore {
1.124     www      4461:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4462:     my $home='';
                   4463: 
1.168     albertel 4464:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4465: 
1.122     albertel 4466:     if (!$symb) {
                   4467:       unless ($symb=escape(&symbread())) { return ''; }
                   4468:     } else {
1.213     www      4469:       $symb=&escape(&symbclean($symb));
1.122     albertel 4470:     }
1.188     www      4471:     if (!$namespace) { 
1.620     albertel 4472:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4473:           return ''; 
                   4474:        } 
                   4475:     }
1.620     albertel 4476:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4477:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4478:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4479:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4480: 
1.12      www      4481:     my %returnhash=();
1.800     albertel 4482:     foreach my $line (split(/\&/,$answer)) {
                   4483: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4484:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4485:     }
1.75      www      4486:     my $version;
                   4487:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4488:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4489:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4490:        }
1.75      www      4491:     }
1.13      www      4492:     return %returnhash;
1.34      www      4493: }
                   4494: 
                   4495: # ---------------------------------------------------------- Course Description
1.1118    foxr     4496: #
                   4497: #  
1.34      www      4498: 
                   4499: sub coursedescription {
1.731     albertel 4500:     my ($courseid,$args)=@_;
1.34      www      4501:     $courseid=~s/^\///;
1.49      www      4502:     $courseid=~s/\_/\//g;
1.34      www      4503:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4504:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4505:     my $normalid=$cdomain.'_'.$cnum;
                   4506:     # need to always cache even if we get errors otherwise we keep 
                   4507:     # trying and trying and trying to get the course description.
                   4508:     my %envhash=();
                   4509:     my %returnhash=();
1.731     albertel 4510:     
                   4511:     my $expiretime=600;
                   4512:     if ($env{'request.course.id'} eq $normalid) {
                   4513: 	$expiretime=120;
                   4514:     }
                   4515: 
                   4516:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4517:     if (!$args->{'freshen_cache'}
                   4518: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4519: 	foreach my $key (keys(%env)) {
                   4520: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4521: 	    my ($setting) = $1;
                   4522: 	    $returnhash{$setting} = $env{$key};
                   4523: 	}
                   4524: 	return %returnhash;
                   4525:     }
                   4526: 
1.1118    foxr     4527:     # get the data again
                   4528: 
1.731     albertel 4529:     if (!$args->{'one_time'}) {
                   4530: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4531:     }
1.811     albertel 4532: 
1.34      www      4533:     if ($chome ne 'no_host') {
1.302     albertel 4534:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4535:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4536: 	   my $username = $env{'user.name'}; # Defult username
                   4537: 	   if(defined $args->{'user'}) {
                   4538: 	       $username = $args->{'user'};
                   4539: 	   }
1.129     albertel 4540:            $returnhash{'home'}= $chome;
                   4541: 	   $returnhash{'domain'} = $cdomain;
                   4542: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4543:            if (!defined($returnhash{'type'})) {
                   4544:                $returnhash{'type'} = 'Course';
                   4545:            }
1.130     albertel 4546:            while (my ($name,$value) = each %returnhash) {
1.53      www      4547:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4548:            }
1.270     www      4549:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4550:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4551: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4552:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4553:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4554:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4555:        }
                   4556:     }
1.731     albertel 4557:     if (!$args->{'one_time'}) {
1.949     raeburn  4558: 	&appenv(\%envhash);
1.731     albertel 4559:     }
1.302     albertel 4560:     return %returnhash;
1.461     www      4561: }
                   4562: 
1.1080    raeburn  4563: sub update_released_required {
                   4564:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4565:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4566:         $cid = $env{'request.course.id'};
                   4567:         $cdom = $env{'course.'.$cid.'.domain'};
                   4568:         $cnum = $env{'course.'.$cid.'.num'};
                   4569:         $chome = $env{'course.'.$cid.'.home'};
                   4570:     }
                   4571:     if ($needsrelease) {
                   4572:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4573:         my $needsupdate;
                   4574:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4575:             $needsupdate = 1;
                   4576:         } else {
                   4577:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4578:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4579:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4580:                 $needsupdate = 1;
                   4581:             }
                   4582:         }
                   4583:         if ($needsupdate) {
                   4584:             my %needshash = (
                   4585:                              'internal.releaserequired' => $needsrelease,
                   4586:                             );
                   4587:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4588:             if ($putresult eq 'ok') {
                   4589:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4590:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4591:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4592:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4593:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4594:                 }
                   4595:             }
                   4596:         }
                   4597:     }
                   4598:     return;
                   4599: }
                   4600: 
1.461     www      4601: # -------------------------------------------------See if a user is privileged
                   4602: 
                   4603: sub privileged {
                   4604:     my ($username,$domain)=@_;
1.1170    droeschl 4605: 
                   4606:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4607:     my $now = time;
                   4608: 
                   4609:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4610:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4611:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4612:                 return 1 unless ($tend && $tend < $now) 
                   4613:                     or ($tstart && $tstart > $now);
                   4614:             }
1.461     www      4615: 	}
1.1170    droeschl 4616: 
1.461     www      4617:     return 0;
1.9       www      4618: }
1.1       albertel 4619: 
1.103     harris41 4620: # -------------------------------------------------------- Get user privileges
1.11      www      4621: 
                   4622: sub rolesinit {
1.1169    droeschl 4623:     my ($domain, $username) = @_;
                   4624:     my %userroles = ('user.login.time' => time);
                   4625:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4626: 
                   4627:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4628:     # also, blocking can be triggered by an activating timer
                   4629:     # it's saved in the user's %env.
                   4630:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4631:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4632:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4633:         %timerintchk, %timerintenv);
                   4634: 
1.1162    raeburn  4635:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4636:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4637:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4638:     }
1.1169    droeschl 4639: 
1.1162    raeburn  4640:     foreach my $key (keys(%timerinterval)) {
                   4641:         my ($cid,$rest) = split(/\0/,$key);
                   4642:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4643:     }
1.1169    droeschl 4644: 
1.11      www      4645:     my %allroles=();
1.1162    raeburn  4646:     my %allgroups=();
1.11      www      4647: 
1.1169    droeschl 4648:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4649:         my $role = $rolesdump{$area};
                   4650:         $area =~ s/\_\w\w$//;
                   4651: 
                   4652:         my ($trole, $tend, $tstart, $group_privs);
                   4653: 
                   4654:         if ($role =~ /^cr/) {
                   4655:         # Custom role, defined by a user 
                   4656:         # e.g., user.role.cr/msu/smith/mynewrole
                   4657:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4658:                 $trole = $1;
                   4659:                 ($tend, $tstart) = split('_', $2);
                   4660:             } else {
                   4661:                 $trole = $role;
                   4662:             }
                   4663:         } elsif ($role =~ m|^gr/|) {
                   4664:         # Role of member in a group, defined within a course/community
                   4665:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4666:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4667:             next if $tstart eq '-1';
                   4668:             ($trole, $group_privs) = split(/\//, $trole);
                   4669:             $group_privs = &unescape($group_privs);
                   4670:         } else {
                   4671:         # Just a normal role, defined in roles.tab
                   4672:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4673:         }
                   4674: 
                   4675:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4676:                  $username);
                   4677:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4678: 
                   4679:         # role expired or not available yet?
                   4680:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4681:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4682: 
                   4683:         next if $area eq '' or $trole eq '';
                   4684: 
                   4685:         my $spec = "$trole.$area";
                   4686:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4687: 
                   4688:         if ($trole =~ /^cr\//) {
                   4689:         # Custom role, defined by a user
                   4690:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4691:         } elsif ($trole eq 'gr') {
                   4692:         # Role of a member in a group, defined within a course/community
                   4693:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4694:             next;
                   4695:         } else {
                   4696:         # Normal role, defined in roles.tab
                   4697:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4698:         }
                   4699: 
                   4700:         my $cid = $tdomain.'_'.$trest;
                   4701:         unless ($firstaccchk{$cid}) {
                   4702:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4703:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4704:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4705:                         $coursetimerstarts{$cid}{$item}; 
                   4706:                 }
                   4707:             }
                   4708:             $firstaccchk{$cid} = 1;
                   4709:         }
                   4710:         unless ($timerintchk{$cid}) {
                   4711:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4712:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4713:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4714:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4715:                 }
1.12      www      4716:             }
1.1169    droeschl 4717:             $timerintchk{$cid} = 1;
1.191     harris41 4718:         }
1.11      www      4719:     }
1.1169    droeschl 4720: 
                   4721:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4722:         \%allroles, \%allgroups);
                   4723:     $env{'user.adv'} = $userroles{'user.adv'};
                   4724: 
1.1162    raeburn  4725:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4726: }
                   4727: 
1.567     raeburn  4728: sub set_arearole {
                   4729:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4730: # log the associated role with the area
                   4731:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4732:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4733: }
                   4734: 
                   4735: sub custom_roleprivs {
                   4736:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4737:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4738:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4739:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4740:         my ($rdummy,$roledef)=
                   4741:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4742:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4743:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4744:             if (defined($syspriv)) {
1.1043    raeburn  4745:                 if ($trest =~ /^$match_community$/) {
                   4746:                     $syspriv =~ s/bre\&S//; 
                   4747:                 }
1.567     raeburn  4748:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4749:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4750:             }
                   4751:             if ($tdomain ne '') {
                   4752:                 if (defined($dompriv)) {
                   4753:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4754:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4755:                 }
                   4756:                 if (($trest ne '') && (defined($coursepriv))) {
                   4757:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4758:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4759:                 }
                   4760:             }
                   4761:         }
                   4762:     }
                   4763: }
                   4764: 
1.678     raeburn  4765: sub group_roleprivs {
                   4766:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4767:     my $access = 1;
                   4768:     my $now = time;
                   4769:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4770:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4771:     if ($access) {
1.811     albertel 4772:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4773:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4774:     }
                   4775: }
1.567     raeburn  4776: 
                   4777: sub standard_roleprivs {
                   4778:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4779:     if (defined($pr{$trole.':s'})) {
                   4780:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4781:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4782:     }
                   4783:     if ($tdomain ne '') {
                   4784:         if (defined($pr{$trole.':d'})) {
                   4785:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4786:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4787:         }
                   4788:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4789:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4790:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4791:         }
                   4792:     }
                   4793: }
                   4794: 
                   4795: sub set_userprivs {
1.1064    raeburn  4796:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4797:     my $author=0;
                   4798:     my $adv=0;
1.678     raeburn  4799:     my %grouproles = ();
                   4800:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4801:         my @groupkeys; 
1.1000    raeburn  4802:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4803:             push(@groupkeys,$role);
                   4804:         }
                   4805:         if (ref($groups_roles) eq 'HASH') {
                   4806:             foreach my $key (keys(%{$groups_roles})) {
                   4807:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4808:                     push(@groupkeys,$key);
                   4809:                 }
                   4810:             }
                   4811:         }
                   4812:         if (@groupkeys > 0) {
                   4813:             foreach my $role (@groupkeys) {
                   4814:                 my ($trole,$area,$sec,$extendedarea);
                   4815:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4816:                     $trole = $1;
                   4817:                     $area = $2;
                   4818:                     $sec = $3;
                   4819:                     $extendedarea = $area.$sec;
                   4820:                     if (exists($$allgroups{$area})) {
                   4821:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4822:                             my $spec = $trole.'.'.$extendedarea;
                   4823:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4824:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4825:                         }
1.678     raeburn  4826:                     }
                   4827:                 }
                   4828:             }
                   4829:         }
                   4830:     }
1.800     albertel 4831:     foreach my $group (keys(%grouproles)) {
                   4832:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4833:     }
1.800     albertel 4834:     foreach my $role (keys(%{$allroles})) {
                   4835:         my %thesepriv;
1.941     raeburn  4836:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4837:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4838:             if ($item ne '') {
                   4839:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4840:                 if ($restrictions eq '') {
                   4841:                     $thesepriv{$privilege}='F';
                   4842:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4843:                     $thesepriv{$privilege}.=$restrictions;
                   4844:                 }
                   4845:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4846:             }
                   4847:         }
                   4848:         my $thesestr='';
1.1104    raeburn  4849:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4850: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4851: 	}
                   4852:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4853:     }
                   4854:     return ($author,$adv);
                   4855: }
                   4856: 
1.994     raeburn  4857: sub role_status {
1.1104    raeburn  4858:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4859:     my @pwhere = ();
                   4860:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4861:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4862:         unless (!defined($$role) || $$role eq '') {
                   4863:             $$where=join('.',@pwhere);
                   4864:             $$trolecode=$$role.'.'.$$where;
                   4865:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4866:             $$tstatus='is';
1.1104    raeburn  4867:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4868:                 $$tstatus='future';
1.1034    raeburn  4869:                 if ($$tstart<$now) {
                   4870:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4871:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4872:                             my (%allroles,%allgroups,$group_privs,
                   4873:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4874:                             my %userroles = (
                   4875:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4876:                             );
1.1064    raeburn  4877:                             @rolecodes = ('cm'); 
1.1002    raeburn  4878:                             my $spec=$$role.'.'.$$where;
                   4879:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4880:                             if ($$role =~ /^cr\//) {
                   4881:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4882:                                 push(@rolecodes,'cr');
1.1002    raeburn  4883:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4884:                                 push(@rolecodes,$$role);
1.1002    raeburn  4885:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4886:                                                     $env{'user.name'});
1.1064    raeburn  4887:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4888:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4889:                                 $group_privs = &unescape($group_privs);
                   4890:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4891:                                 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  4892:                                 &get_groups_roles($tdomain,$trest,
                   4893:                                                   \%course_roles,\@rolecodes,
                   4894:                                                   \%groups_roles);
1.1002    raeburn  4895:                             } else {
1.1064    raeburn  4896:                                 push(@rolecodes,$$role);
1.1002    raeburn  4897:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4898:                             }
1.1064    raeburn  4899:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4900:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4901:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4902:                         }
                   4903:                     }
1.1034    raeburn  4904:                     $$tstatus = 'is';
1.1002    raeburn  4905:                 }
1.994     raeburn  4906:             }
                   4907:             if ($$tend) {
1.1104    raeburn  4908:                 if ($$tend<$update) {
1.994     raeburn  4909:                     $$tstatus='expired';
                   4910:                 } elsif ($$tend<$now) {
                   4911:                     $$tstatus='will_not';
                   4912:                 }
                   4913:             }
                   4914:         }
                   4915:     }
                   4916: }
                   4917: 
1.1104    raeburn  4918: sub get_groups_roles {
                   4919:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4920:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4921:                   (ref($rolecodes) eq 'ARRAY') && 
                   4922:                   (ref($groups_roles) eq 'HASH')); 
                   4923:     if (keys(%{$cdom_courseroles}) > 0) {
                   4924:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4925:         if ($cdom ne '' && $cnum ne '') {
                   4926:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4927:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4928:                     my $crsrole = $1;
                   4929:                     my $crssec = $2;
                   4930:                     if ($crsrole =~ /^cr/) {
                   4931:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4932:                             push(@{$rolecodes},'cr');
                   4933:                         }
                   4934:                     } else {
                   4935:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4936:                             push(@{$rolecodes},$crsrole);
                   4937:                         }
                   4938:                     }
                   4939:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4940:                     if ($crssec ne '') {
                   4941:                         $rolekey .= "/$crssec";
                   4942:                     }
                   4943:                     $rolekey .= './';
                   4944:                     $groups_roles->{$rolekey} = $rolecodes;
                   4945:                 }
                   4946:             }
                   4947:         }
                   4948:     }
                   4949:     return;
                   4950: }
                   4951: 
                   4952: sub delete_env_groupprivs {
                   4953:     my ($where,$courseroles,$possroles) = @_;
                   4954:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4955:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4956:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4957:         %{$courseroles->{$udom}} =
                   4958:             &get_my_roles('','','userroles',['active'],
                   4959:                           $possroles,[$udom],1);
                   4960:     }
                   4961:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4962:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4963:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4964:             my $area = '/'.$cdom.'/'.$cnum;
                   4965:             my $privkey = "user.priv.$crsrole.$area";
                   4966:             if ($crssec ne '') {
                   4967:                 $privkey .= '/'.$crssec;
                   4968:             }
                   4969:             $privkey .= ".$area/$group";
                   4970:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4971:         }
                   4972:     }
                   4973:     return;
                   4974: }
                   4975: 
1.994     raeburn  4976: sub check_adhoc_privs {
1.1104    raeburn  4977:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4978:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4979:     if ($env{$cckey}) {
                   4980:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4981:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4982:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4983:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4984:         }
                   4985:     } else {
1.1088    raeburn  4986:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4987:     }
                   4988: }
                   4989: 
                   4990: sub set_adhoc_privileges {
                   4991: # role can be cc or ca
1.1088    raeburn  4992:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4993:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4994:     my $spec = $role.'.'.$area;
                   4995:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4996:                                   $env{'user.name'});
                   4997:     my %ccrole = ();
                   4998:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4999:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5000:     &appenv(\%userroles,[$role,'cm']);
                   5001:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5002:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5003:         &appenv( {'request.role'        => $spec,
                   5004:                   'request.role.domain' => $dcdom,
                   5005:                   'request.course.sec'  => ''
                   5006:                  }
                   5007:                );
                   5008:         my $tadv=0;
                   5009:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5010:         &appenv({'request.role.adv'    => $tadv});
                   5011:     }
1.994     raeburn  5012: }
                   5013: 
1.12      www      5014: # --------------------------------------------------------------- get interface
                   5015: 
                   5016: sub get {
1.131     albertel 5017:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5018:    my $items='';
1.800     albertel 5019:    foreach my $item (@$storearr) {
                   5020:        $items.=&escape($item).'&';
1.191     harris41 5021:    }
1.12      www      5022:    $items=~s/\&$//;
1.620     albertel 5023:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5024:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5025:    my $uhome=&homeserver($uname,$udomain);
                   5026: 
1.133     albertel 5027:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5028:    my @pairs=split(/\&/,$rep);
1.273     albertel 5029:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5030:      return @pairs;
                   5031:    }
1.15      www      5032:    my %returnhash=();
1.42      www      5033:    my $i=0;
1.800     albertel 5034:    foreach my $item (@$storearr) {
                   5035:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5036:       $i++;
1.191     harris41 5037:    }
1.15      www      5038:    return %returnhash;
1.27      www      5039: }
                   5040: 
                   5041: # --------------------------------------------------------------- del interface
                   5042: 
                   5043: sub del {
1.133     albertel 5044:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5045:    my $items='';
1.800     albertel 5046:    foreach my $item (@$storearr) {
                   5047:        $items.=&escape($item).'&';
1.191     harris41 5048:    }
1.984     neumanie 5049: 
1.27      www      5050:    $items=~s/\&$//;
1.620     albertel 5051:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5052:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5053:    my $uhome=&homeserver($uname,$udomain);
                   5054:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5055: }
                   5056: 
                   5057: # -------------------------------------------------------------- dump interface
                   5058: 
                   5059: sub dump {
1.1166    raeburn  5060:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5061:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5062:     if (!$uname) { $uname=$env{'user.name'}; }
                   5063:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5064: 
1.755     albertel 5065:     if ($regexp) {
                   5066: 	$regexp=&escape($regexp);
                   5067:     } else {
                   5068: 	$regexp='.';
                   5069:     }
1.1166    raeburn  5070:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5071:     my @pairs=split(/\&/,$rep);
                   5072:     my %returnhash=();
1.1098    foxr     5073:     if (!($rep =~ /^error/ )) {
                   5074: 	foreach my $item (@pairs) {
                   5075: 	    my ($key,$value)=split(/=/,$item,2);
                   5076: 	    $key = &unescape($key);
                   5077: 	    next if ($key =~ /^error: 2 /);
                   5078: 	    $returnhash{$key}=&thaw_unescape($value);
                   5079: 	}
1.755     albertel 5080:     }
                   5081:     return %returnhash;
1.407     www      5082: }
                   5083: 
1.1098    foxr     5084: 
1.717     albertel 5085: # --------------------------------------------------------- dumpstore interface
                   5086: 
                   5087: sub dumpstore {
                   5088:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5089:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5090:    if (!$uname) { $uname=$env{'user.name'}; }
                   5091:    my $uhome=&homeserver($uname,$udomain);
                   5092:    if ($regexp) {
                   5093:        $regexp=&escape($regexp);
                   5094:    } else {
                   5095:        $regexp='.';
                   5096:    }
                   5097:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5098:    my @pairs=split(/\&/,$rep);
                   5099:    my %returnhash=();
                   5100:    foreach my $item (@pairs) {
                   5101:        my ($key,$value)=split(/=/,$item,2);
                   5102:        next if ($key =~ /^error: 2 /);
                   5103:        $returnhash{$key}=&thaw_unescape($value);
                   5104:    }
                   5105:    return %returnhash;
1.717     albertel 5106: }
                   5107: 
1.407     www      5108: # -------------------------------------------------------------- keys interface
                   5109: 
                   5110: sub getkeys {
                   5111:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5112:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5113:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5114:    my $uhome=&homeserver($uname,$udomain);
                   5115:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5116:    my @keyarray=();
1.800     albertel 5117:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5118:       next if ($key =~ /^error: 2 /);
1.800     albertel 5119:       push(@keyarray,&unescape($key));
1.407     www      5120:    }
                   5121:    return @keyarray;
1.318     matthew  5122: }
                   5123: 
1.319     matthew  5124: # --------------------------------------------------------------- currentdump
                   5125: sub currentdump {
1.328     matthew  5126:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5127:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5128:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5129:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5130:    my $uhome = &homeserver($sname,$sdom);
                   5131:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5132:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5133:    #
1.318     matthew  5134:    my %returnhash=();
1.319     matthew  5135:    #
                   5136:    if ($rep eq "unknown_cmd") { 
                   5137:        # an old lond will not know currentdump
                   5138:        # Do a dump and make it look like a currentdump
1.822     albertel 5139:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5140:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5141:        my %hash = @tmp;
                   5142:        @tmp=();
1.424     matthew  5143:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5144:    } else {
                   5145:        my @pairs=split(/\&/,$rep);
1.800     albertel 5146:        foreach my $pair (@pairs) {
                   5147:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5148:            my ($symb,$param) = split(/:/,$key);
                   5149:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5150:                                                         &thaw_unescape($value);
1.319     matthew  5151:        }
1.191     harris41 5152:    }
1.12      www      5153:    return %returnhash;
1.424     matthew  5154: }
                   5155: 
                   5156: sub convert_dump_to_currentdump{
                   5157:     my %hash = %{shift()};
                   5158:     my %returnhash;
                   5159:     # Code ripped from lond, essentially.  The only difference
                   5160:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5161:     # we might run in to problems with parameter names =~ /^v\./
                   5162:     while (my ($key,$value) = each(%hash)) {
                   5163:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5164: 	$symb  = &unescape($symb);
                   5165: 	$param = &unescape($param);
1.424     matthew  5166:         next if ($v eq 'version' || $symb eq 'keys');
                   5167:         next if (exists($returnhash{$symb}) &&
                   5168:                  exists($returnhash{$symb}->{$param}) &&
                   5169:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5170:         $returnhash{$symb}->{$param}=$value;
                   5171:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5172:     }
                   5173:     #
                   5174:     # Remove all of the keys in the hashes which keep track of
                   5175:     # the version of the parameter.
                   5176:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5177:         # use a foreach because we are going to delete from the hash.
                   5178:         foreach my $key (keys(%$param_hash)) {
                   5179:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5180:         }
                   5181:     }
                   5182:     return \%returnhash;
1.12      www      5183: }
                   5184: 
1.627     albertel 5185: # ------------------------------------------------------ critical inc interface
                   5186: 
                   5187: sub cinc {
                   5188:     return &inc(@_,'critical');
                   5189: }
                   5190: 
1.449     matthew  5191: # --------------------------------------------------------------- inc interface
                   5192: 
                   5193: sub inc {
1.627     albertel 5194:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5195:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5196:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5197:     my $uhome=&homeserver($uname,$udomain);
                   5198:     my $items='';
                   5199:     if (! ref($store)) {
                   5200:         # got a single value, so use that instead
                   5201:         $items = &escape($store).'=&';
                   5202:     } elsif (ref($store) eq 'SCALAR') {
                   5203:         $items = &escape($$store).'=&';        
                   5204:     } elsif (ref($store) eq 'ARRAY') {
                   5205:         $items = join('=&',map {&escape($_);} @{$store});
                   5206:     } elsif (ref($store) eq 'HASH') {
                   5207:         while (my($key,$value) = each(%{$store})) {
                   5208:             $items.= &escape($key).'='.&escape($value).'&';
                   5209:         }
                   5210:     }
                   5211:     $items=~s/\&$//;
1.627     albertel 5212:     if ($critical) {
                   5213: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5214:     } else {
                   5215: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5216:     }
1.449     matthew  5217: }
                   5218: 
1.12      www      5219: # --------------------------------------------------------------- put interface
                   5220: 
                   5221: sub put {
1.134     albertel 5222:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5223:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5224:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5225:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5226:    my $items='';
1.800     albertel 5227:    foreach my $item (keys(%$storehash)) {
                   5228:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5229:    }
1.12      www      5230:    $items=~s/\&$//;
1.134     albertel 5231:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5232: }
                   5233: 
1.631     albertel 5234: # ------------------------------------------------------------ newput interface
                   5235: 
                   5236: sub newput {
                   5237:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5238:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5239:    if (!$uname) { $uname=$env{'user.name'}; }
                   5240:    my $uhome=&homeserver($uname,$udomain);
                   5241:    my $items='';
                   5242:    foreach my $key (keys(%$storehash)) {
                   5243:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5244:    }
                   5245:    $items=~s/\&$//;
                   5246:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5247: }
                   5248: 
                   5249: # ---------------------------------------------------------  putstore interface
                   5250: 
1.524     raeburn  5251: sub putstore {
1.715     albertel 5252:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5253:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5254:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5255:    my $uhome=&homeserver($uname,$udomain);
                   5256:    my $items='';
1.715     albertel 5257:    foreach my $key (keys(%$storehash)) {
                   5258:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5259:    }
1.715     albertel 5260:    $items=~s/\&$//;
1.716     albertel 5261:    my $esc_symb=&escape($symb);
                   5262:    my $esc_v=&escape($version);
1.715     albertel 5263:    my $reply =
1.716     albertel 5264:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5265: 	      $uhome);
                   5266:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5267:        # gfall back to way things use to be done
1.715     albertel 5268:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5269: 			    $uname);
1.524     raeburn  5270:    }
1.715     albertel 5271:    return $reply;
                   5272: }
                   5273: 
                   5274: sub old_putstore {
1.716     albertel 5275:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5276:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5277:     if (!$uname) { $uname=$env{'user.name'}; }
                   5278:     my $uhome=&homeserver($uname,$udomain);
                   5279:     my %newstorehash;
1.800     albertel 5280:     foreach my $item (keys(%$storehash)) {
                   5281: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5282: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5283:     }
                   5284:     my $items='';
                   5285:     my %allitems = ();
1.800     albertel 5286:     foreach my $item (keys(%newstorehash)) {
                   5287: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5288: 	    my $key = $1.':keys:'.$2;
                   5289: 	    $allitems{$key} .= $3.':';
                   5290: 	}
1.800     albertel 5291: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5292:     }
1.800     albertel 5293:     foreach my $item (keys(%allitems)) {
                   5294: 	$allitems{$item} =~ s/\:$//;
                   5295: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5296:     }
                   5297:     $items=~s/\&$//;
                   5298:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5299: }
                   5300: 
1.47      www      5301: # ------------------------------------------------------ critical put interface
                   5302: 
                   5303: sub cput {
1.134     albertel 5304:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5305:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5306:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5307:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5308:    my $items='';
1.800     albertel 5309:    foreach my $item (keys(%$storehash)) {
                   5310:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5311:    }
1.47      www      5312:    $items=~s/\&$//;
1.134     albertel 5313:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5314: }
                   5315: 
                   5316: # -------------------------------------------------------------- eget interface
                   5317: 
                   5318: sub eget {
1.133     albertel 5319:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5320:    my $items='';
1.800     albertel 5321:    foreach my $item (@$storearr) {
                   5322:        $items.=&escape($item).'&';
1.191     harris41 5323:    }
1.12      www      5324:    $items=~s/\&$//;
1.620     albertel 5325:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5326:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5327:    my $uhome=&homeserver($uname,$udomain);
                   5328:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5329:    my @pairs=split(/\&/,$rep);
                   5330:    my %returnhash=();
1.42      www      5331:    my $i=0;
1.800     albertel 5332:    foreach my $item (@$storearr) {
                   5333:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5334:       $i++;
1.191     harris41 5335:    }
1.12      www      5336:    return %returnhash;
                   5337: }
                   5338: 
1.667     albertel 5339: # ------------------------------------------------------------ tmpput interface
                   5340: sub tmpput {
1.802     raeburn  5341:     my ($storehash,$server,$context)=@_;
1.667     albertel 5342:     my $items='';
1.800     albertel 5343:     foreach my $item (keys(%$storehash)) {
                   5344: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5345:     }
                   5346:     $items=~s/\&$//;
1.802     raeburn  5347:     if (defined($context)) {
                   5348:         $items .= ':'.&escape($context);
                   5349:     }
1.667     albertel 5350:     return &reply("tmpput:$items",$server);
                   5351: }
                   5352: 
                   5353: # ------------------------------------------------------------ tmpget interface
                   5354: sub tmpget {
1.688     albertel 5355:     my ($token,$server)=@_;
                   5356:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5357:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5358:     my %returnhash;
                   5359:     foreach my $item (split(/\&/,$rep)) {
                   5360: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5361:         next if ($key =~ /^error: 2 /);
1.667     albertel 5362: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5363:     }
                   5364:     return %returnhash;
                   5365: }
                   5366: 
1.1113    raeburn  5367: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5368: sub tmpdel {
                   5369:     my ($token,$server)=@_;
                   5370:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5371:     return &reply("tmpdel:$token",$server);
                   5372: }
                   5373: 
1.765     albertel 5374: # -------------------------------------------------- portfolio access checking
                   5375: 
                   5376: sub portfolio_access {
1.766     albertel 5377:     my ($requrl) = @_;
1.765     albertel 5378:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5379:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5380:     if ($result) {
                   5381:         my %setters;
                   5382:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5383:             my ($startblock,$endblock) =
                   5384:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5385:             if ($startblock && $endblock) {
                   5386:                 return 'B';
                   5387:             }
                   5388:         } else {
                   5389:             my ($startblock,$endblock) =
                   5390:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5391:             if ($startblock && $endblock) {
                   5392:                 return 'B';
                   5393:             }
                   5394:         }
                   5395:     }
1.765     albertel 5396:     if ($result eq 'ok') {
1.766     albertel 5397:        return 'F';
1.765     albertel 5398:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5399:        return 'A';
1.765     albertel 5400:     }
1.766     albertel 5401:     return '';
1.765     albertel 5402: }
                   5403: 
                   5404: sub get_portfolio_access {
1.767     albertel 5405:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5406: 
                   5407:     if (!ref($access_hash)) {
                   5408: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5409: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5410: 						   $file_name);
                   5411: 	$access_hash = $access_controls{$file_name};
                   5412:     }
                   5413: 
1.765     albertel 5414:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5415:     my $now = time;
                   5416:     if (ref($access_hash) eq 'HASH') {
                   5417:         foreach my $key (keys(%{$access_hash})) {
                   5418:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5419:             if ($start > $now) {
                   5420:                 next;
                   5421:             }
                   5422:             if ($end && $end<$now) {
                   5423:                 next;
                   5424:             }
                   5425:             if ($scope eq 'public') {
                   5426:                 $public = $key;
                   5427:                 last;
                   5428:             } elsif ($scope eq 'guest') {
                   5429:                 $guest = $key;
                   5430:             } elsif ($scope eq 'domains') {
                   5431:                 push(@domains,$key);
                   5432:             } elsif ($scope eq 'users') {
                   5433:                 push(@users,$key);
                   5434:             } elsif ($scope eq 'course') {
                   5435:                 push(@courses,$key);
                   5436:             } elsif ($scope eq 'group') {
                   5437:                 push(@groups,$key);
                   5438:             }
                   5439:         }
                   5440:         if ($public) {
                   5441:             return 'ok';
                   5442:         }
                   5443:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5444:             if ($guest) {
                   5445:                 return $guest;
                   5446:             }
                   5447:         } else {
                   5448:             if (@domains > 0) {
                   5449:                 foreach my $domkey (@domains) {
                   5450:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5451:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5452:                             return 'ok';
                   5453:                         }
                   5454:                     }
                   5455:                 }
                   5456:             }
                   5457:             if (@users > 0) {
                   5458:                 foreach my $userkey (@users) {
1.865     raeburn  5459:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5460:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5461:                             if (ref($item) eq 'HASH') {
                   5462:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5463:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5464:                                     return 'ok';
                   5465:                                 }
                   5466:                             }
                   5467:                         }
                   5468:                     } 
1.765     albertel 5469:                 }
                   5470:             }
                   5471:             my %roleshash;
                   5472:             my @courses_and_groups = @courses;
                   5473:             push(@courses_and_groups,@groups); 
                   5474:             if (@courses_and_groups > 0) {
                   5475:                 my (%allgroups,%allroles); 
                   5476:                 my ($start,$end,$role,$sec,$group);
                   5477:                 foreach my $envkey (%env) {
1.1060    raeburn  5478:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5479:                         my $cid = $2.'_'.$3; 
                   5480:                         if ($1 eq 'gr') {
                   5481:                             $group = $4;
                   5482:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5483:                         } else {
                   5484:                             if ($4 eq '') {
                   5485:                                 $sec = 'none';
                   5486:                             } else {
                   5487:                                 $sec = $4;
                   5488:                             }
                   5489:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5490:                         }
1.811     albertel 5491:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5492:                         my $cid = $2.'_'.$3;
                   5493:                         if ($4 eq '') {
                   5494:                             $sec = 'none';
                   5495:                         } else {
                   5496:                             $sec = $4;
                   5497:                         }
                   5498:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5499:                     }
                   5500:                 }
                   5501:                 if (keys(%allroles) == 0) {
                   5502:                     return;
                   5503:                 }
                   5504:                 foreach my $key (@courses_and_groups) {
                   5505:                     my %content = %{$$access_hash{$key}};
                   5506:                     my $cnum = $content{'number'};
                   5507:                     my $cdom = $content{'domain'};
                   5508:                     my $cid = $cdom.'_'.$cnum;
                   5509:                     if (!exists($allroles{$cid})) {
                   5510:                         next;
                   5511:                     }    
                   5512:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5513:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5514:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5515:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5516:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5517:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5518:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5519:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5520:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5521:                                         if (grep/^all$/,@sections) {
                   5522:                                             return 'ok';
                   5523:                                         } else {
                   5524:                                             if (grep/^$sec$/,@sections) {
                   5525:                                                 return 'ok';
                   5526:                                             }
                   5527:                                         }
                   5528:                                     }
                   5529:                                 }
                   5530:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5531:                                     if (grep/^none$/,@groups) {
                   5532:                                         return 'ok';
                   5533:                                     }
                   5534:                                 } else {
                   5535:                                     if (grep/^all$/,@groups) {
                   5536:                                         return 'ok';
                   5537:                                     } 
                   5538:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5539:                                         if (grep/^$group$/,@groups) {
                   5540:                                             return 'ok';
                   5541:                                         }
                   5542:                                     }
                   5543:                                 } 
                   5544:                             }
                   5545:                         }
                   5546:                     }
                   5547:                 }
                   5548:             }
                   5549:             if ($guest) {
                   5550:                 return $guest;
                   5551:             }
                   5552:         }
                   5553:     }
                   5554:     return;
                   5555: }
                   5556: 
                   5557: sub course_group_datechecker {
                   5558:     my ($dates,$now,$status) = @_;
                   5559:     my ($start,$end) = split(/\./,$dates);
                   5560:     if (!$start && !$end) {
                   5561:         return 'ok';
                   5562:     }
                   5563:     if (grep/^active$/,@{$status}) {
                   5564:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5565:             return 'ok';
                   5566:         }
                   5567:     }
                   5568:     if (grep/^previous$/,@{$status}) {
                   5569:         if ($end > $now ) {
                   5570:             return 'ok';
                   5571:         }
                   5572:     }
                   5573:     if (grep/^future$/,@{$status}) {
                   5574:         if ($start > $now) {
                   5575:             return 'ok';
                   5576:         }
                   5577:     }
                   5578:     return; 
                   5579: }
                   5580: 
                   5581: sub parse_portfolio_url {
                   5582:     my ($url) = @_;
                   5583: 
                   5584:     my ($type,$udom,$unum,$group,$file_name);
                   5585:     
1.823     albertel 5586:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5587: 	$type = 1;
                   5588:         $udom = $1;
                   5589:         $unum = $2;
                   5590:         $file_name = $3;
1.823     albertel 5591:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5592: 	$type = 2;
                   5593:         $udom = $1;
                   5594:         $unum = $2;
                   5595:         $group = $3;
                   5596:         $file_name = $3.'/'.$4;
                   5597:     }
                   5598:     if (wantarray) {
                   5599: 	return ($type,$udom,$unum,$file_name,$group);
                   5600:     }
                   5601:     return $type;
                   5602: }
                   5603: 
                   5604: sub is_portfolio_url {
                   5605:     my ($url) = @_;
                   5606:     return scalar(&parse_portfolio_url($url));
                   5607: }
                   5608: 
1.798     raeburn  5609: sub is_portfolio_file {
                   5610:     my ($file) = @_;
1.820     raeburn  5611:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5612:         return 1;
                   5613:     }
                   5614:     return;
                   5615: }
                   5616: 
1.976     raeburn  5617: sub usertools_access {
1.1084    raeburn  5618:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5619:     my ($access,%tools);
                   5620:     if ($context eq '') {
                   5621:         $context = 'tools';
                   5622:     }
                   5623:     if ($context eq 'requestcourses') {
                   5624:         %tools = (
                   5625:                       official   => 1,
                   5626:                       unofficial => 1,
1.1006    raeburn  5627:                       community  => 1,
1.985     raeburn  5628:                  );
                   5629:     } else {
                   5630:         %tools = (
                   5631:                       aboutme   => 1,
                   5632:                       blog      => 1,
                   5633:                       portfolio => 1,
                   5634:                  );
                   5635:     }
1.976     raeburn  5636:     return if (!defined($tools{$tool}));
                   5637: 
                   5638:     if ((!defined($udom)) || (!defined($uname))) {
                   5639:         $udom = $env{'user.domain'};
                   5640:         $uname = $env{'user.name'};
                   5641:     }
                   5642: 
1.978     raeburn  5643:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5644:         if ($action ne 'reload') {
1.985     raeburn  5645:             if ($context eq 'requestcourses') {
                   5646:                 return $env{'environment.canrequest.'.$tool};
                   5647:             } else {
                   5648:                 return $env{'environment.availabletools.'.$tool};
                   5649:             }
                   5650:         }
1.976     raeburn  5651:     }
                   5652: 
                   5653:     my ($toolstatus,$inststatus);
                   5654: 
1.985     raeburn  5655:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5656:          ($action ne 'reload')) {
                   5657:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5658:         $inststatus = $env{'environment.inststatus'};
                   5659:     } else {
1.1084    raeburn  5660:         if (ref($userenvref) eq 'HASH') {
                   5661:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5662:             $inststatus = $userenvref->{'inststatus'};
                   5663:         } else {
                   5664:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5665:             $toolstatus = $userenv{$context.'.'.$tool};
                   5666:             $inststatus = $userenv{'inststatus'};
                   5667:         }
1.976     raeburn  5668:     }
                   5669: 
                   5670:     if ($toolstatus ne '') {
                   5671:         if ($toolstatus) {
                   5672:             $access = 1;
                   5673:         } else {
                   5674:             $access = 0;
                   5675:         }
                   5676:         return $access;
                   5677:     }
                   5678: 
1.1084    raeburn  5679:     my ($is_adv,%domdef);
                   5680:     if (ref($is_advref) eq 'HASH') {
                   5681:         $is_adv = $is_advref->{'is_adv'};
                   5682:     } else {
                   5683:         $is_adv = &is_advanced_user($udom,$uname);
                   5684:     }
                   5685:     if (ref($domdefref) eq 'HASH') {
                   5686:         %domdef = %{$domdefref};
                   5687:     } else {
                   5688:         %domdef = &get_domain_defaults($udom);
                   5689:     }
1.976     raeburn  5690:     if (ref($domdef{$tool}) eq 'HASH') {
                   5691:         if ($is_adv) {
                   5692:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5693:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5694:                     $access = 1;
                   5695:                 } else {
                   5696:                     $access = 0;
                   5697:                 }
                   5698:                 return $access;
                   5699:             }
                   5700:         }
                   5701:         if ($inststatus ne '') {
                   5702:             my ($hasaccess,$hasnoaccess);
                   5703:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5704:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5705:                     if ($domdef{$tool}{$affiliation}) {
                   5706:                         $hasaccess = 1;
                   5707:                     } else {
                   5708:                         $hasnoaccess = 1;
                   5709:                     }
                   5710:                 }
                   5711:             }
                   5712:             if ($hasaccess || $hasnoaccess) {
                   5713:                 if ($hasaccess) {
                   5714:                     $access = 1;
                   5715:                 } elsif ($hasnoaccess) {
                   5716:                     $access = 0; 
                   5717:                 }
                   5718:                 return $access;
                   5719:             }
                   5720:         } else {
                   5721:             if ($domdef{$tool}{'default'} ne '') {
                   5722:                 if ($domdef{$tool}{'default'}) {
                   5723:                     $access = 1;
                   5724:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5725:                     $access = 0;
                   5726:                 }
                   5727:                 return $access;
                   5728:             }
                   5729:         }
                   5730:     } else {
1.985     raeburn  5731:         if ($context eq 'tools') {
                   5732:             $access = 1;
                   5733:         } else {
                   5734:             $access = 0;
                   5735:         }
1.976     raeburn  5736:         return $access;
                   5737:     }
                   5738: }
                   5739: 
1.1050    raeburn  5740: sub is_course_owner {
                   5741:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5742:     if (($udom eq '') || ($uname eq '')) {
                   5743:         $udom = $env{'user.domain'};
                   5744:         $uname = $env{'user.name'};
                   5745:     }
                   5746:     unless (($udom eq '') || ($uname eq '')) {
                   5747:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5748:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5749:                 return 1;
                   5750:             } else {
                   5751:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5752:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5753:                     return 1;
                   5754:                 }
                   5755:             }
                   5756:         }
                   5757:     }
                   5758:     return;
                   5759: }
                   5760: 
1.976     raeburn  5761: sub is_advanced_user {
                   5762:     my ($udom,$uname) = @_;
1.1085    raeburn  5763:     if ($udom ne '' && $uname ne '') {
                   5764:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5765:             if (wantarray) {
                   5766:                 return ($env{'user.adv'},$env{'user.author'});
                   5767:             } else {
                   5768:                 return $env{'user.adv'};
                   5769:             }
1.1085    raeburn  5770:         }
                   5771:     }
1.976     raeburn  5772:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5773:     my %allroles;
1.1128    raeburn  5774:     my ($is_adv,$is_author);
1.976     raeburn  5775:     foreach my $role (keys(%roleshash)) {
                   5776:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5777:         my $area = '/'.$tdomain.'/'.$trest;
                   5778:         if ($sec ne '') {
                   5779:             $area .= '/'.$sec;
                   5780:         }
                   5781:         if (($area ne '') && ($trole ne '')) {
                   5782:             my $spec=$trole.'.'.$area;
                   5783:             if ($trole =~ /^cr\//) {
                   5784:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5785:             } elsif ($trole ne 'gr') {
                   5786:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5787:             }
1.1128    raeburn  5788:             if ($trole eq 'au') {
                   5789:                 $is_author = 1;
                   5790:             }
1.976     raeburn  5791:         }
                   5792:     }
                   5793:     foreach my $role (keys(%allroles)) {
                   5794:         last if ($is_adv);
                   5795:         foreach my $item (split(/:/,$allroles{$role})) {
                   5796:             if ($item ne '') {
                   5797:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5798:                 if ($privilege eq 'adv') {
                   5799:                     $is_adv = 1;
                   5800:                     last;
                   5801:                 }
                   5802:             }
                   5803:         }
                   5804:     }
1.1128    raeburn  5805:     if (wantarray) {
                   5806:         return ($is_adv,$is_author);
                   5807:     }
1.976     raeburn  5808:     return $is_adv;
                   5809: }
1.798     raeburn  5810: 
1.1035    raeburn  5811: sub check_can_request {
1.1036    raeburn  5812:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5813:     my $canreq = 0;
                   5814:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5815:     my @options = ('approval','validate','autolimit');
                   5816:     my $optregex = join('|',@options);
                   5817:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5818:         foreach my $type (@{$types}) {
                   5819:             if (&usertools_access($env{'user.name'},
                   5820:                                   $env{'user.domain'},
                   5821:                                   $type,undef,'requestcourses')) {
                   5822:                 $canreq ++;
1.1036    raeburn  5823:                 if (ref($request_domains) eq 'HASH') {
                   5824:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5825:                 }
1.1035    raeburn  5826:                 if ($dom eq $env{'user.domain'}) {
                   5827:                     $can_request->{$type} = 1;
                   5828:                 }
                   5829:             }
                   5830:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5831:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5832:                 if (@curr > 0) {
1.1036    raeburn  5833:                     foreach my $item (@curr) {
                   5834:                         if (ref($request_domains) eq 'HASH') {
                   5835:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5836:                             if ($otherdom ne '') {
                   5837:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5838:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5839:                                         push(@{$request_domains->{$type}},$otherdom);
                   5840:                                     }
                   5841:                                 } else {
                   5842:                                     push(@{$request_domains->{$type}},$otherdom);
                   5843:                                 }
                   5844:                             }
                   5845:                         }
                   5846:                     }
                   5847:                     unless($dom eq $env{'user.domain'}) {
                   5848:                         $canreq ++;
1.1035    raeburn  5849:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5850:                             $can_request->{$type} = 1;
                   5851:                         }
                   5852:                     }
                   5853:                 }
                   5854:             }
                   5855:         }
                   5856:     }
                   5857:     return $canreq;
                   5858: }
                   5859: 
1.341     www      5860: # ---------------------------------------------- Custom access rule evaluation
                   5861: 
                   5862: sub customaccess {
                   5863:     my ($priv,$uri)=@_;
1.807     albertel 5864:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5865:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5866:     $udom = &LONCAPA::clean_domain($udom);
                   5867:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5868:     my $access=0;
1.800     albertel 5869:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5870: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5871: 	if ($type eq 'user') {
                   5872: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5873: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5874: 		if ($tdom) {
                   5875: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5876: 		}
1.896     albertel 5877: 		if ($tuname) {
                   5878: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5879: 		}
                   5880: 		$access=($effect eq 'allow');
                   5881: 		last;
                   5882: 	    }
                   5883: 	} else {
                   5884: 	    if ($role) {
                   5885: 		if ($role ne $urole) { next; }
                   5886: 	    }
                   5887: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5888: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5889: 		if ($tdom) {
                   5890: 		    if ($tdom ne $udom) { next; }
                   5891: 		}
                   5892: 		if ($tcrs) {
                   5893: 		    if ($tcrs ne $ucrs) { next; }
                   5894: 		}
                   5895: 		if ($tsec) {
                   5896: 		    if ($tsec ne $usec) { next; }
                   5897: 		}
                   5898: 		$access=($effect eq 'allow');
                   5899: 		last;
                   5900: 	    }
                   5901: 	    if ($realm eq '' && $role eq '') {
                   5902: 		$access=($effect eq 'allow');
                   5903: 	    }
1.402     bowersj2 5904: 	}
1.341     www      5905:     }
                   5906:     return $access;
                   5907: }
                   5908: 
1.103     harris41 5909: # ------------------------------------------------- Check for a user privilege
1.12      www      5910: 
                   5911: sub allowed {
1.810     raeburn  5912:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5913:     my $ver_orguri=$uri;
1.439     www      5914:     $uri=&deversion($uri);
1.152     www      5915:     my $orguri=$uri;
1.52      www      5916:     $uri=&declutter($uri);
1.809     raeburn  5917: 
1.810     raeburn  5918:     if ($priv eq 'evb') {
                   5919: # Evade communication block restrictions for specified role in a course
                   5920:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5921:             return $1;
                   5922:         } else {
                   5923:             return;
                   5924:         }
                   5925:     }
                   5926: 
1.620     albertel 5927:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5928: # Free bre access to adm and meta resources
1.775     albertel 5929:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5930: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5931: 	&& ($priv eq 'bre')) {
1.14      www      5932: 	return 'F';
1.159     www      5933:     }
                   5934: 
1.545     banghart 5935: # Free bre access to user's own portfolio contents
1.714     raeburn  5936:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5937:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5938: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5939:         my %setters;
                   5940:         my ($startblock,$endblock) = 
                   5941:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5942:         if ($startblock && $endblock) {
                   5943:             return 'B';
                   5944:         } else {
                   5945:             return 'F';
                   5946:         }
1.545     banghart 5947:     }
                   5948: 
1.762     raeburn  5949: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5950:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5951:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5952:         if (exists($env{'request.course.id'})) {
                   5953:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5954:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5955:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5956:                 my $courseprivid=$env{'request.course.id'};
                   5957:                 $courseprivid=~s/\_/\//;
                   5958:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5959:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5960:                     return $1; 
1.762     raeburn  5961:                 } else {
                   5962:                     if ($env{'request.course.sec'}) {
                   5963:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5964:                     }
                   5965:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5966:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5967:                         return $2;
                   5968:                     }
1.714     raeburn  5969:                 }
                   5970:             }
                   5971:         }
                   5972:     }
                   5973: 
1.159     www      5974: # Free bre to public access
                   5975: 
                   5976:     if ($priv eq 'bre') {
1.238     www      5977:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5978: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5979:            return 'F'; 
                   5980:         }
1.238     www      5981:         if ($copyright eq 'priv') {
                   5982:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5983: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5984: 		return '';
                   5985:             }
                   5986:         }
                   5987:         if ($copyright eq 'domain') {
                   5988:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5989: 	    unless (($env{'user.domain'} eq $1) ||
                   5990:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5991: 		return '';
                   5992:             }
1.262     matthew  5993:         }
1.620     albertel 5994:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5995:             # Library role, so allow browsing of resources in this domain.
                   5996:             return 'F';
1.238     www      5997:         }
1.341     www      5998:         if ($copyright eq 'custom') {
                   5999: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6000:         }
1.14      www      6001:     }
1.264     matthew  6002:     # Domain coordinator is trying to create a course
1.620     albertel 6003:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6004:         # uri is the requested domain in this case.
                   6005:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6006:         # a role of dc for the domain in question.
1.620     albertel 6007:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6008:     }
1.29      www      6009: 
1.52      www      6010:     my $thisallowed='';
                   6011:     my $statecond=0;
                   6012:     my $courseprivid='';
                   6013: 
1.1039    raeburn  6014:     my $ownaccess;
1.1043    raeburn  6015:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6016:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6017:         if ($uri eq '') {
                   6018:             $ownaccess = 1;
                   6019:         } else {
                   6020:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6021:                 my $udom = $env{'user.domain'};
                   6022:                 my $uname = $env{'user.name'};
                   6023:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6024:                     $ownaccess = 1;
1.1040    raeburn  6025:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6026:                     unless ($uri =~ m{\.\./}) {
                   6027:                         $ownaccess = 1;
                   6028:                     }
                   6029:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6030:                     my $now = time;
                   6031:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6032:                         my $adom = $1;
                   6033:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6034:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6035:                                 my ($start,$end) = split('.',$env{$key});
                   6036:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6037:                                     $ownaccess = 1;
                   6038:                                     last;
                   6039:                                 }
                   6040:                             }
                   6041:                         }
                   6042:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6043:                         my $adom = $1;
                   6044:                         my $aname = $2;
1.1042    raeburn  6045:                         foreach my $role ('ca','aa') { 
                   6046:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6047:                                 my ($start,$end) =
                   6048:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6049:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6050:                                     $ownaccess = 1;
                   6051:                                     last;
                   6052:                                 }
1.1039    raeburn  6053:                             }
                   6054:                         }
                   6055:                     }
                   6056:                 }
                   6057:             }
                   6058:         }
                   6059:     }
                   6060: 
1.52      www      6061: # Course
                   6062: 
1.620     albertel 6063:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6064:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6065:             $thisallowed.=$1;
                   6066:         }
1.52      www      6067:     }
1.29      www      6068: 
1.52      www      6069: # Domain
                   6070: 
1.620     albertel 6071:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6072:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6073:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6074:             $thisallowed.=$1;
                   6075:         }
1.12      www      6076:     }
1.52      www      6077: 
1.1141    raeburn  6078: # User who is not author or co-author might still be able to edit
                   6079: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6080:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6081:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6082:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6083:             $thisallowed.=$1;
                   6084:         }
                   6085:     }
                   6086: 
1.52      www      6087: # Course: uri itself is a course
1.66      www      6088:     my $courseuri=$uri;
                   6089:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6090:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6091: 
1.620     albertel 6092:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6093:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6094:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6095:             $thisallowed.=$1;
                   6096:         }
1.12      www      6097:     }
1.29      www      6098: 
1.665     albertel 6099: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6100: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6101:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6102: 	$thisallowed='';
1.671     raeburn  6103:         my ($match)=&is_on_map($uri);
                   6104:         if ($match) {
                   6105:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6106:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6107:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6108:                 if (@blockers > 0) {
                   6109:                     $thisallowed = 'B';
                   6110:                 } else {
                   6111:                     $thisallowed.=$1;
                   6112:                 }
1.671     raeburn  6113:             }
                   6114:         } else {
1.705     albertel 6115:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6116:             if ($refuri) {
                   6117:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6118:                     $thisallowed='F';
1.671     raeburn  6119:                 } else {
                   6120:                     $refuri=&declutter($refuri);
                   6121:                     my ($match) = &is_on_map($refuri);
                   6122:                     if ($match) {
1.1162    raeburn  6123:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6124:                         if (@blockers > 0) {
                   6125:                             $thisallowed = 'B';
                   6126:                         } else {
                   6127:                             $thisallowed='F';
                   6128:                         }
1.671     raeburn  6129:                     }
1.669     raeburn  6130:                 }
1.671     raeburn  6131:             }
                   6132:         }
1.314     www      6133:     }
1.492     albertel 6134: 
1.766     albertel 6135:     if ($priv eq 'bre'
                   6136: 	&& $thisallowed ne 'F' 
                   6137: 	&& $thisallowed ne '2'
                   6138: 	&& &is_portfolio_url($uri)) {
                   6139: 	$thisallowed = &portfolio_access($uri);
                   6140:     }
                   6141:     
1.52      www      6142: # Full access at system, domain or course-wide level? Exit.
1.29      www      6143:     if ($thisallowed=~/F/) {
                   6144: 	return 'F';
                   6145:     }
                   6146: 
1.52      www      6147: # If this is generating or modifying users, exit with special codes
1.29      www      6148: 
1.643     www      6149:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6150: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6151: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6152: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6153: 	    unless ($auname) { return $thisallowed; }
                   6154: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6155: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6156: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6157: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6158: 	}
1.52      www      6159: 	return $thisallowed;
                   6160:     }
                   6161: #
1.103     harris41 6162: # Gathered so far: system, domain and course wide privileges
1.52      www      6163: #
                   6164: # Course: See if uri or referer is an individual resource that is part of 
                   6165: # the course
                   6166: 
1.620     albertel 6167:     if ($env{'request.course.id'}) {
1.232     www      6168: 
1.620     albertel 6169:        $courseprivid=$env{'request.course.id'};
                   6170:        if ($env{'request.course.sec'}) {
                   6171:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6172:        }
                   6173:        $courseprivid=~s/\_/\//;
                   6174:        my $checkreferer=1;
1.232     www      6175:        my ($match,$cond)=&is_on_map($uri);
                   6176:        if ($match) {
                   6177:            $statecond=$cond;
1.620     albertel 6178:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6179:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6180:                my $value = $1;
                   6181:                if ($priv eq 'bre') {
                   6182:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6183:                    if (@blockers > 0) {
                   6184:                        $thisallowed = 'B';
                   6185:                    } else {
                   6186:                        $thisallowed.=$value;
                   6187:                    }
                   6188:                } else {
                   6189:                    $thisallowed.=$value;
                   6190:                }
1.52      www      6191:                $checkreferer=0;
                   6192:            }
1.29      www      6193:        }
1.83      www      6194:        
1.148     www      6195:        if ($checkreferer) {
1.620     albertel 6196: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6197:             unless ($refuri) {
1.800     albertel 6198:                 foreach my $key (keys(%env)) {
                   6199: 		    if ($key=~/^httpref\..*\*/) {
                   6200: 			my $pattern=$key;
1.156     www      6201:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6202:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6203:                         $pattern=~s/\//\\\//g;
1.152     www      6204:                         if ($orguri=~/$pattern/) {
1.800     albertel 6205: 			    $refuri=$env{$key};
1.148     www      6206:                         }
                   6207:                     }
1.191     harris41 6208:                 }
1.148     www      6209:             }
1.232     www      6210: 
1.148     www      6211:          if ($refuri) { 
1.152     www      6212: 	  $refuri=&declutter($refuri);
1.232     www      6213:           my ($match,$cond)=&is_on_map($refuri);
                   6214:             if ($match) {
                   6215:               my $refstatecond=$cond;
1.620     albertel 6216:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6217:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6218:                   my $value = $1;
                   6219:                   if ($priv eq 'bre') {
                   6220:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6221:                       if (@blockers > 0) {
                   6222:                           $thisallowed = 'B';
                   6223:                       } else {
                   6224:                           $thisallowed.=$value;
                   6225:                       }
                   6226:                   } else {
                   6227:                       $thisallowed.=$value;
                   6228:                   }
1.53      www      6229:                   $uri=$refuri;
                   6230:                   $statecond=$refstatecond;
1.52      www      6231:               }
                   6232:           }
1.148     www      6233:         }
1.29      www      6234:        }
1.52      www      6235:    }
1.29      www      6236: 
1.52      www      6237: #
1.103     harris41 6238: # Gathered now: all privileges that could apply, and condition number
1.52      www      6239: # 
                   6240: #
                   6241: # Full or no access?
                   6242: #
1.29      www      6243: 
1.52      www      6244:     if ($thisallowed=~/F/) {
                   6245: 	return 'F';
                   6246:     }
1.29      www      6247: 
1.52      www      6248:     unless ($thisallowed) {
                   6249:         return '';
                   6250:     }
1.29      www      6251: 
1.52      www      6252: # Restrictions exist, deal with them
                   6253: #
                   6254: #   C:according to course preferences
                   6255: #   R:according to resource settings
                   6256: #   L:unless locked
                   6257: #   X:according to user session state
                   6258: #
                   6259: 
                   6260: # Possibly locked functionality, check all courses
1.54      www      6261: # Locks might take effect only after 10 minutes cache expiration for other
                   6262: # courses, and 2 minutes for current course
1.52      www      6263: 
                   6264:     my $envkey;
                   6265:     if ($thisallowed=~/L/) {
1.1000    raeburn  6266:         foreach $envkey (keys(%env)) {
1.54      www      6267:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6268:                my $courseid=$2;
                   6269:                my $roleid=$1.'.'.$2;
1.92      www      6270:                $courseid=~s/^\///;
1.54      www      6271:                my $expiretime=600;
1.620     albertel 6272:                if ($env{'request.role'} eq $roleid) {
1.54      www      6273: 		  $expiretime=120;
                   6274:                }
                   6275: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6276:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6277:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6278: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6279:                }
1.620     albertel 6280:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6281:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6282: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6283:                        &log($env{'user.domain'},$env{'user.name'},
                   6284:                             $env{'user.home'},
1.57      www      6285:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6286:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6287:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6288: 		       return '';
                   6289:                    }
                   6290:                }
1.620     albertel 6291:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6292:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6293: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6294:                        &log($env{'user.domain'},$env{'user.name'},
                   6295:                             $env{'user.home'},
1.57      www      6296:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6297:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6298:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6299: 		       return '';
                   6300:                    }
                   6301:                }
                   6302: 	   }
1.29      www      6303:        }
1.52      www      6304:     }
                   6305:    
                   6306: #
                   6307: # Rest of the restrictions depend on selected course
                   6308: #
                   6309: 
1.620     albertel 6310:     unless ($env{'request.course.id'}) {
1.766     albertel 6311: 	if ($thisallowed eq 'A') {
                   6312: 	    return 'A';
1.814     raeburn  6313:         } elsif ($thisallowed eq 'B') {
                   6314:             return 'B';
1.766     albertel 6315: 	} else {
                   6316: 	    return '1';
                   6317: 	}
1.52      www      6318:     }
1.29      www      6319: 
1.52      www      6320: #
                   6321: # Now user is definitely in a course
                   6322: #
1.53      www      6323: 
                   6324: 
                   6325: # Course preferences
                   6326: 
                   6327:    if ($thisallowed=~/C/) {
1.620     albertel 6328:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6329:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6330:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6331: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6332: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6333: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6334: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6335: 			$env{'request.course.id'});
                   6336: 	   }
1.237     www      6337:            return '';
                   6338:        }
                   6339: 
1.620     albertel 6340:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6341: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6342: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6343: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6344: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6345: 			$env{'request.course.id'});
                   6346: 	   }
1.54      www      6347:            return '';
                   6348:        }
1.53      www      6349:    }
                   6350: 
                   6351: # Resource preferences
                   6352: 
                   6353:    if ($thisallowed=~/R/) {
1.620     albertel 6354:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6355:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6356: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6357: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6358: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6359: 	   }
                   6360: 	   return '';
1.54      www      6361:        }
1.53      www      6362:    }
1.30      www      6363: 
1.246     www      6364: # Restricted by state or randomout?
1.30      www      6365: 
1.52      www      6366:    if ($thisallowed=~/X/) {
1.620     albertel 6367:       if ($env{'acc.randomout'}) {
1.579     albertel 6368: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6369:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6370:             return ''; 
                   6371:          }
1.247     www      6372:       }
                   6373:       if (&condval($statecond)) {
1.52      www      6374: 	 return '2';
                   6375:       } else {
                   6376:          return '';
                   6377:       }
                   6378:    }
1.30      www      6379: 
1.766     albertel 6380:     if ($thisallowed eq 'A') {
                   6381: 	return 'A';
1.814     raeburn  6382:     } elsif ($thisallowed eq 'B') {
                   6383:         return 'B';
1.766     albertel 6384:     }
1.52      www      6385:    return 'F';
1.232     www      6386: }
1.1162    raeburn  6387: 
                   6388: sub get_comm_blocks {
                   6389:     my ($cdom,$cnum) = @_;
                   6390:     if ($cdom eq '' || $cnum eq '') {
                   6391:         return unless ($env{'request.course.id'});
                   6392:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6393:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6394:     }
                   6395:     my %commblocks;
                   6396:     my $hashid=$cdom.'_'.$cnum;
                   6397:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6398:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6399:         %commblocks = %{$blocksref};
                   6400:     } else {
                   6401:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6402:         my $cachetime = 600;
                   6403:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6404:     }
                   6405:     return %commblocks;
                   6406: }
                   6407: 
                   6408: sub has_comm_blocking {
                   6409:     my ($priv,$symb,$uri,$blocks) = @_;
                   6410:     return unless ($env{'request.course.id'});
                   6411:     return unless ($priv eq 'bre');
                   6412:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6413:     my %commblocks;
                   6414:     if (ref($blocks) eq 'HASH') {
                   6415:         %commblocks = %{$blocks};
                   6416:     } else {
                   6417:         %commblocks = &get_comm_blocks();
                   6418:     }
                   6419:     return unless (keys(%commblocks) > 0);
                   6420:     if (!$symb) { $symb=&symbread($uri,1); }
                   6421:     my ($map,$resid,undef)=&decode_symb($symb);
                   6422:     my %tocheck = (
                   6423:                     maps      => $map,
                   6424:                     resources => $symb,
                   6425:                   );
                   6426:     my @blockers;
                   6427:     my $now = time;
1.1163    raeburn  6428:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6429:     foreach my $block (keys(%commblocks)) {
                   6430:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6431:             my ($start,$end) = ($1,$2);
                   6432:             if ($start <= $now && $end >= $now) {
                   6433:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6434:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6435:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6436:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6437:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6438:                                     push(@blockers,$block);
                   6439:                                 }
                   6440:                             }
                   6441:                         }
                   6442:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6443:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6444:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6445:                                     push(@blockers,$block);
                   6446:                                 }
                   6447:                             }
                   6448:                         }
                   6449:                     }
                   6450:                 }
                   6451:             }
                   6452:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6453:             my $item = $1;
1.1163    raeburn  6454:             my @to_test;
1.1162    raeburn  6455:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6456:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6457:                     my $check_interval;
                   6458:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6459:                         my @interval;
                   6460:                         my $type = 'map';
                   6461:                         if ($item eq 'course') {
                   6462:                             $type = 'course';
                   6463:                             @interval=&EXT("resource.0.interval");
                   6464:                         } else {
                   6465:                             if ($item =~ /___\d+___/) {
                   6466:                                 $type = 'resource';
                   6467:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6468:                                 if (ref($navmap)) {                        
                   6469:                                     my $res = $navmap->getBySymb($item); 
                   6470:                                     push(@to_test,$res);
                   6471:                                 }
1.1162    raeburn  6472:                             } else {
                   6473:                                 my $mapsymb = &symbread($item,1);
                   6474:                                 if ($mapsymb) {
                   6475:                                     if (ref($navmap)) {
                   6476:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6477:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6478:                                         foreach my $res (@to_test) {
1.1162    raeburn  6479:                                             my $symb = $res->symb();
                   6480:                                             next if ($symb eq $mapsymb);
                   6481:                                             if ($symb ne '') {
                   6482:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6483:                                                 last;
                   6484:                                             }
                   6485:                                         }
                   6486:                                     }
                   6487:                                 }
                   6488:                             }
                   6489:                         }
                   6490:                         if ($interval[0] =~ /\d+/) {
                   6491:                             my $first_access;
                   6492:                             if ($type eq 'resource') {
                   6493:                                 $first_access=&get_first_access($interval[1],$item);
                   6494:                             } elsif ($type eq 'map') {
                   6495:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6496:                             } else {
                   6497:                                 $first_access=&get_first_access($interval[1]);
                   6498:                             }
                   6499:                             if ($first_access) {
                   6500:                                 my $timesup = $first_access+$interval[0];
                   6501:                                 if ($timesup > $now) {
1.1163    raeburn  6502:                                     foreach my $res (@to_test) {
                   6503:                                         if ($res->is_problem()) {
                   6504:                                             if ($res->completable()) {
                   6505:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6506:                                                     push(@blockers,$block);
                   6507:                                                 }
                   6508:                                                 last;
                   6509:                                             }
                   6510:                                         }
1.1162    raeburn  6511:                                     }
                   6512:                                 }
                   6513:                             }
                   6514:                         }
                   6515:                     }
                   6516:                 }
                   6517:             }
                   6518:         }
                   6519:     }
                   6520:     return @blockers;
                   6521: }
                   6522: 
                   6523: sub check_docs_block {
                   6524:     my ($docsblock,$tocheck) =@_;
                   6525:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6526:         return;
                   6527:     }
                   6528:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6529:         if ($tocheck->{'maps'}) {
                   6530:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6531:                 return 1;
                   6532:             }
                   6533:         }
                   6534:     }
                   6535:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6536:         if ($tocheck->{'resources'}) {
                   6537:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6538:                 return 1;
                   6539:             }
                   6540:         }
                   6541:     }
                   6542:     return;
                   6543: }
                   6544: 
1.1133    foxr     6545: #
                   6546: #   Removes the versino from a URI and
                   6547: #   splits it in to its filename and path to the filename.
                   6548: #   Seems like File::Basename could have done this more clearly.
                   6549: #   Parameters:
                   6550: #      $uri   - input URI
                   6551: #   Returns:
                   6552: #     Two element list consisting of 
                   6553: #     $pathname  - the URI up to and excluding the trailing /
                   6554: #     $filename  - The part of the URI following the last /
                   6555: #  NOTE:
                   6556: #    Another realization of this is simply:
                   6557: #    use File::Basename;
                   6558: #    ...
                   6559: #    $uri = shift;
                   6560: #    $filename = basename($uri);
                   6561: #    $path     = dirname($uri);
                   6562: #    return ($filename, $path);
                   6563: #
                   6564: #     The implementation below is probably faster however.
                   6565: #
1.710     albertel 6566: sub split_uri_for_cond {
                   6567:     my $uri=&deversion(&declutter(shift));
                   6568:     my @uriparts=split(/\//,$uri);
                   6569:     my $filename=pop(@uriparts);
                   6570:     my $pathname=join('/',@uriparts);
                   6571:     return ($pathname,$filename);
                   6572: }
1.232     www      6573: # --------------------------------------------------- Is a resource on the map?
                   6574: 
                   6575: sub is_on_map {
1.710     albertel 6576:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6577:     #Trying to find the conditional for the file
1.620     albertel 6578:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6579: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6580:     if ($match) {
1.289     bowersj2 6581: 	return (1,$1);
                   6582:     } else {
1.434     www      6583: 	return (0,0);
1.289     bowersj2 6584:     }
1.12      www      6585: }
                   6586: 
1.427     www      6587: # --------------------------------------------------------- Get symb from alias
                   6588: 
                   6589: sub get_symb_from_alias {
                   6590:     my $symb=shift;
                   6591:     my ($map,$resid,$url)=&decode_symb($symb);
                   6592: # Already is a symb
                   6593:     if ($url) { return $symb; }
                   6594: # Must be an alias
                   6595:     my $aliassymb='';
                   6596:     my %bighash;
1.620     albertel 6597:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6598:                             &GDBM_READER(),0640)) {
                   6599:         my $rid=$bighash{'mapalias_'.$symb};
                   6600: 	if ($rid) {
                   6601: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6602: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6603: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6604: 	}
                   6605:         untie %bighash;
                   6606:     }
                   6607:     return $aliassymb;
                   6608: }
                   6609: 
1.12      www      6610: # ----------------------------------------------------------------- Define Role
                   6611: 
                   6612: sub definerole {
                   6613:   if (allowed('mcr','/')) {
                   6614:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6615:     foreach my $role (split(':',$sysrole)) {
                   6616: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6617:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6618:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6619: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6620:                return "refused:s:$crole&$cqual"; 
                   6621:             }
                   6622:         }
1.191     harris41 6623:     }
1.800     albertel 6624:     foreach my $role (split(':',$domrole)) {
                   6625: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6626:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6627:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6628: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6629:                return "refused:d:$crole&$cqual"; 
                   6630:             }
                   6631:         }
1.191     harris41 6632:     }
1.800     albertel 6633:     foreach my $role (split(':',$courole)) {
                   6634: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6635:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6636:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6637: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6638:                return "refused:c:$crole&$cqual"; 
                   6639:             }
                   6640:         }
1.191     harris41 6641:     }
1.620     albertel 6642:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6643:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6644: 	        "rolesdef_$rolename=".
                   6645:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6646:     return reply($command,$env{'user.home'});
1.12      www      6647:   } else {
                   6648:     return 'refused';
                   6649:   }
1.105     harris41 6650: }
                   6651: 
                   6652: # ---------------- Make a metadata query against the network of library servers
                   6653: 
                   6654: sub metadata_query {
1.244     matthew  6655:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6656:     my %rhash;
1.845     albertel 6657:     my %libserv = &all_library();
1.244     matthew  6658:     my @server_list = (defined($server_array) ? @$server_array
                   6659:                                               : keys(%libserv) );
                   6660:     for my $server (@server_list) {
1.118     harris41 6661: 	unless ($custom or $customshow) {
                   6662: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6663: 	    $rhash{$server}=$reply;
                   6664: 	}
                   6665: 	else {
                   6666: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6667: 			     &escape($custom).':'.&escape($customshow),
                   6668: 			     $server);
                   6669: 	    $rhash{$server}=$reply;
                   6670: 	}
1.112     harris41 6671:     }
1.118     harris41 6672:     return \%rhash;
1.240     www      6673: }
                   6674: 
                   6675: # ----------------------------------------- Send log queries and wait for reply
                   6676: 
                   6677: sub log_query {
                   6678:     my ($uname,$udom,$query,%filters)=@_;
                   6679:     my $uhome=&homeserver($uname,$udom);
                   6680:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6681:     my $uhost=&hostname($uhome);
1.800     albertel 6682:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6683:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6684:                        $uhome);
1.479     albertel 6685:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6686:     return get_query_reply($queryid);
                   6687: }
                   6688: 
1.818     raeburn  6689: # -------------------------- Update MySQL table for portfolio file
                   6690: 
                   6691: sub update_portfolio_table {
1.821     raeburn  6692:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6693:     if ($group ne '') {
                   6694:         $file_name =~s /^\Q$group\E//;
                   6695:     }
1.818     raeburn  6696:     my $homeserver = &homeserver($uname,$udom);
                   6697:     my $queryid=
1.821     raeburn  6698:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6699:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6700:     my $reply = &get_query_reply($queryid);
                   6701:     return $reply;
                   6702: }
                   6703: 
1.899     raeburn  6704: # -------------------------- Update MySQL allusers table
                   6705: 
                   6706: sub update_allusers_table {
                   6707:     my ($uname,$udom,$names) = @_;
                   6708:     my $homeserver = &homeserver($uname,$udom);
                   6709:     my $queryid=
                   6710:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6711:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6712:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6713:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6714:                'generation='.&escape($names->{'generation'}).'%%'.
                   6715:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6716:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6717:     return;
1.899     raeburn  6718: }
                   6719: 
1.508     raeburn  6720: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6721: 
                   6722: sub fetch_enrollment_query {
1.511     raeburn  6723:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6724:     my $homeserver;
1.547     raeburn  6725:     my $maxtries = 1;
1.508     raeburn  6726:     if ($context eq 'automated') {
                   6727:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6728:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6729:     } else {
                   6730:         $homeserver = &homeserver($cnum,$dom);
                   6731:     }
1.838     albertel 6732:     my $host=&hostname($homeserver);
1.506     raeburn  6733:     my $cmd = '';
1.1000    raeburn  6734:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6735:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6736:     }
                   6737:     $cmd =~ s/%%$//;
                   6738:     $cmd = &escape($cmd);
                   6739:     my $query = 'fetchenrollment';
1.620     albertel 6740:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6741:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6742:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6743:         return 'error: '.$queryid;
                   6744:     }
1.506     raeburn  6745:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6746:     my $tries = 1;
                   6747:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6748:         $reply = &get_query_reply($queryid);
                   6749:         $tries ++;
                   6750:     }
1.526     raeburn  6751:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6752:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6753:     } else {
1.901     albertel 6754:         my @responses = split(/:/,$reply);
1.515     raeburn  6755:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6756:             foreach my $line (@responses) {
                   6757:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6758:                 $$replyref{$key} = $value;
                   6759:             }
                   6760:         } else {
1.1117    foxr     6761:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6762:             foreach my $line (@responses) {
                   6763:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6764:                 $$replyref{$key} = $value;
                   6765:                 if ($value > 0) {
1.800     albertel 6766:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6767:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6768:                         my $destname = $pathname.'/'.$filename;
                   6769:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6770:                         if ($xml_classlist =~ /^error/) {
                   6771:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6772:                         } else {
1.506     raeburn  6773:                             if ( open(FILE,">$destname") ) {
                   6774:                                 print FILE &unescape($xml_classlist);
                   6775:                                 close(FILE);
1.526     raeburn  6776:                             } else {
                   6777:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6778:                             }
                   6779:                         }
                   6780:                     }
                   6781:                 }
                   6782:             }
                   6783:         }
                   6784:         return 'ok';
                   6785:     }
                   6786:     return 'error';
                   6787: }
                   6788: 
1.242     www      6789: sub get_query_reply {
                   6790:     my $queryid=shift;
1.1117    foxr     6791:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6792:     my $reply='';
                   6793:     for (1..100) {
                   6794: 	sleep 2;
                   6795:         if (-e $replyfile.'.end') {
1.448     albertel 6796: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6797: 		$reply = join('',<$fh>);
                   6798: 		close($fh);
1.240     www      6799: 	   } else { return 'error: reply_file_error'; }
1.242     www      6800:            return &unescape($reply);
                   6801: 	}
1.240     www      6802:     }
1.242     www      6803:     return 'timeout:'.$queryid;
1.240     www      6804: }
                   6805: 
                   6806: sub courselog_query {
1.241     www      6807: #
                   6808: # possible filters:
                   6809: # url: url or symb
                   6810: # username
                   6811: # domain
                   6812: # action: view, submit, grade
                   6813: # start: timestamp
                   6814: # end: timestamp
                   6815: #
1.240     www      6816:     my (%filters)=@_;
1.620     albertel 6817:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6818:     if ($filters{'url'}) {
                   6819: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6820:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6821:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6822:     }
1.620     albertel 6823:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6824:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6825:     return &log_query($cname,$cdom,'courselog',%filters);
                   6826: }
                   6827: 
                   6828: sub userlog_query {
1.858     raeburn  6829: #
                   6830: # possible filters:
                   6831: # action: log check role
                   6832: # start: timestamp
                   6833: # end: timestamp
                   6834: #
1.240     www      6835:     my ($uname,$udom,%filters)=@_;
                   6836:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6837: }
                   6838: 
1.506     raeburn  6839: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6840: 
                   6841: sub auto_run {
1.508     raeburn  6842:     my ($cnum,$cdom) = @_;
1.876     raeburn  6843:     my $response = 0;
                   6844:     my $settings;
                   6845:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6846:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6847:         $settings = $domconfig{'autoenroll'};
                   6848:         if ($settings->{'run'} eq '1') {
                   6849:             $response = 1;
                   6850:         }
                   6851:     } else {
1.934     raeburn  6852:         my $homeserver;
                   6853:         if (&is_course($cdom,$cnum)) {
                   6854:             $homeserver = &homeserver($cnum,$cdom);
                   6855:         } else {
                   6856:             $homeserver = &domain($cdom,'primary');
                   6857:         }
                   6858:         if ($homeserver ne 'no_host') {
                   6859:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6860:         }
1.876     raeburn  6861:     }
1.506     raeburn  6862:     return $response;
                   6863: }
1.776     albertel 6864: 
1.506     raeburn  6865: sub auto_get_sections {
1.508     raeburn  6866:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6867:     my $homeserver;
                   6868:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6869:         $homeserver = &homeserver($cnum,$cdom);
                   6870:     }
                   6871:     if (!defined($homeserver)) { 
                   6872:         if ($cdom =~ /^$match_domain$/) {
                   6873:             $homeserver = &domain($cdom,'primary');
                   6874:         }
                   6875:     }
                   6876:     my @secs;
                   6877:     if (defined($homeserver)) {
                   6878:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6879:         unless ($response eq 'refused') {
                   6880:             @secs = split(/:/,$response);
                   6881:         }
1.506     raeburn  6882:     }
                   6883:     return @secs;
                   6884: }
1.776     albertel 6885: 
1.506     raeburn  6886: sub auto_new_course {
1.1099    raeburn  6887:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6888:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6889:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6890:     return $response;
                   6891: }
1.776     albertel 6892: 
1.506     raeburn  6893: sub auto_validate_courseID {
1.508     raeburn  6894:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6895:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6896:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6897:     return $response;
                   6898: }
1.776     albertel 6899: 
1.1007    raeburn  6900: sub auto_validate_instcode {
1.1020    raeburn  6901:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6902:     my ($homeserver,$response);
                   6903:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6904:         $homeserver = &homeserver($cnum,$cdom);
                   6905:     }
                   6906:     if (!defined($homeserver)) {
                   6907:         if ($cdom =~ /^$match_domain$/) {
                   6908:             $homeserver = &domain($cdom,'primary');
                   6909:         }
                   6910:     }
1.1065    raeburn  6911:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6912:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6913:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6914:     return ($outcome,$description);
1.1007    raeburn  6915: }
                   6916: 
1.506     raeburn  6917: sub auto_create_password {
1.873     raeburn  6918:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6919:     my ($homeserver,$response);
1.506     raeburn  6920:     my $create_passwd = 0;
                   6921:     my $authchk = '';
1.873     raeburn  6922:     if ($udom =~ /^$match_domain$/) {
                   6923:         $homeserver = &domain($udom,'primary');
                   6924:     }
                   6925:     if ($homeserver eq '') {
                   6926:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6927:             $homeserver = &homeserver($cnum,$cdom);
                   6928:         }
                   6929:     }
                   6930:     if ($homeserver eq '') {
                   6931:         $authchk = 'nodomain';
1.506     raeburn  6932:     } else {
1.873     raeburn  6933:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6934:         if ($response eq 'refused') {
                   6935:             $authchk = 'refused';
                   6936:         } else {
1.901     albertel 6937:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6938:         }
1.506     raeburn  6939:     }
                   6940:     return ($authparam,$create_passwd,$authchk);
                   6941: }
                   6942: 
1.706     raeburn  6943: sub auto_photo_permission {
                   6944:     my ($cnum,$cdom,$students) = @_;
                   6945:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6946:     my ($outcome,$perm_reqd,$conditions) = 
                   6947: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6948:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6949: 	return (undef,undef);
                   6950:     }
1.706     raeburn  6951:     return ($outcome,$perm_reqd,$conditions);
                   6952: }
                   6953: 
                   6954: sub auto_checkphotos {
                   6955:     my ($uname,$udom,$pid) = @_;
                   6956:     my $homeserver = &homeserver($uname,$udom);
                   6957:     my ($result,$resulttype);
                   6958:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6959: 				   &escape($uname).':'.&escape($pid),
                   6960: 				   $homeserver));
1.709     albertel 6961:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6962: 	return (undef,undef);
                   6963:     }
1.706     raeburn  6964:     if ($outcome) {
                   6965:         ($result,$resulttype) = split(/:/,$outcome);
                   6966:     } 
                   6967:     return ($result,$resulttype);
                   6968: }
                   6969: 
                   6970: sub auto_photochoice {
                   6971:     my ($cnum,$cdom) = @_;
                   6972:     my $homeserver = &homeserver($cnum,$cdom);
                   6973:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6974: 						       &escape($cdom),
                   6975: 						       $homeserver)));
1.709     albertel 6976:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6977: 	return (undef,undef);
                   6978:     }
1.706     raeburn  6979:     return ($update,$comment);
                   6980: }
                   6981: 
                   6982: sub auto_photoupdate {
                   6983:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6984:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6985:     my $host=&hostname($homeserver);
1.706     raeburn  6986:     my $cmd = '';
                   6987:     my $maxtries = 1;
1.800     albertel 6988:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6989:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6990:     }
                   6991:     $cmd =~ s/%%$//;
                   6992:     $cmd = &escape($cmd);
                   6993:     my $query = 'institutionalphotos';
                   6994:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6995:     unless ($queryid=~/^\Q$host\E\_/) {
                   6996:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6997:         return 'error: '.$queryid;
                   6998:     }
                   6999:     my $reply = &get_query_reply($queryid);
                   7000:     my $tries = 1;
                   7001:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7002:         $reply = &get_query_reply($queryid);
                   7003:         $tries ++;
                   7004:     }
                   7005:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7006:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7007:     } else {
                   7008:         my @responses = split(/:/,$reply);
                   7009:         my $outcome = shift(@responses); 
                   7010:         foreach my $item (@responses) {
                   7011:             my ($key,$value) = split(/=/,$item);
                   7012:             $$photo{$key} = $value;
                   7013:         }
                   7014:         return $outcome;
                   7015:     }
                   7016:     return 'error';
                   7017: }
                   7018: 
1.521     raeburn  7019: sub auto_instcode_format {
1.793     albertel 7020:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7021: 	$cat_order) = @_;
1.521     raeburn  7022:     my $courses = '';
1.772     raeburn  7023:     my @homeservers;
1.521     raeburn  7024:     if ($caller eq 'global') {
1.841     albertel 7025: 	my %servers = &get_servers($codedom,'library');
                   7026: 	foreach my $tryserver (keys(%servers)) {
                   7027: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7028: 		push(@homeservers,$tryserver);
                   7029: 	    }
1.584     raeburn  7030:         }
1.1022    raeburn  7031:     } elsif ($caller eq 'requests') {
                   7032:         if ($codedom =~ /^$match_domain$/) {
                   7033:             my $chome = &domain($codedom,'primary');
                   7034:             unless ($chome eq 'no_host') {
                   7035:                 push(@homeservers,$chome);
                   7036:             }
                   7037:         }
1.521     raeburn  7038:     } else {
1.772     raeburn  7039:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7040:     }
1.793     albertel 7041:     foreach my $code (keys(%{$instcodes})) {
                   7042:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7043:     }
                   7044:     chop($courses);
1.772     raeburn  7045:     my $ok_response = 0;
                   7046:     my $response;
                   7047:     while (@homeservers > 0 && $ok_response == 0) {
                   7048:         my $server = shift(@homeservers); 
                   7049:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7050:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7051:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7052: 		split(/:/,$response);
1.772     raeburn  7053:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7054:             push(@{$codetitles},&str2array($codetitles_str));
                   7055:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7056:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7057:             $ok_response = 1;
                   7058:         }
                   7059:     }
                   7060:     if ($ok_response) {
1.521     raeburn  7061:         return 'ok';
1.772     raeburn  7062:     } else {
                   7063:         return $response;
1.521     raeburn  7064:     }
                   7065: }
                   7066: 
1.792     raeburn  7067: sub auto_instcode_defaults {
                   7068:     my ($domain,$returnhash,$code_order) = @_;
                   7069:     my @homeservers;
1.841     albertel 7070: 
                   7071:     my %servers = &get_servers($domain,'library');
                   7072:     foreach my $tryserver (keys(%servers)) {
                   7073: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7074: 	    push(@homeservers,$tryserver);
                   7075: 	}
1.792     raeburn  7076:     }
1.841     albertel 7077: 
1.792     raeburn  7078:     my $response;
1.841     albertel 7079:     foreach my $server (@homeservers) {
1.792     raeburn  7080:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7081:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7082: 	
                   7083: 	foreach my $pair (split(/\&/,$response)) {
                   7084: 	    my ($name,$value)=split(/\=/,$pair);
                   7085: 	    if ($name eq 'code_order') {
                   7086: 		@{$code_order} = split(/\&/,&unescape($value));
                   7087: 	    } else {
                   7088: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7089: 	    }
                   7090: 	}
                   7091: 	return 'ok';
1.792     raeburn  7092:     }
1.841     albertel 7093: 
                   7094:     return $response;
1.1003    raeburn  7095: }
                   7096: 
                   7097: sub auto_possible_instcodes {
1.1007    raeburn  7098:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7099:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7100:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7101:         return;
                   7102:     }
1.1003    raeburn  7103:     my (@homeservers,$uhome);
                   7104:     if (defined(&domain($domain,'primary'))) {
                   7105:         $uhome=&domain($domain,'primary');
                   7106:         push(@homeservers,&domain($domain,'primary'));
                   7107:     } else {
                   7108:         my %servers = &get_servers($domain,'library');
                   7109:         foreach my $tryserver (keys(%servers)) {
                   7110:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7111:                 push(@homeservers,$tryserver);
                   7112:             }
                   7113:         }
                   7114:     }
                   7115:     my $response;
                   7116:     foreach my $server (@homeservers) {
                   7117:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7118:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7119:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7120:             split(':',$response);
                   7121:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7122:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7123:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7124:             my ($name,$value)=split('=',$item);
                   7125:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7126:         }
                   7127:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7128:             my ($name,$value)=split('=',$item);
                   7129:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7130:         }
                   7131:         return 'ok';
                   7132:     }
                   7133:     return $response;
                   7134: }
1.792     raeburn  7135: 
1.1010    raeburn  7136: sub auto_courserequest_checks {
                   7137:     my ($dom) = @_;
1.1020    raeburn  7138:     my ($homeserver,%validations);
                   7139:     if ($dom =~ /^$match_domain$/) {
                   7140:         $homeserver = &domain($dom,'primary');
                   7141:     }
                   7142:     unless ($homeserver eq 'no_host') {
                   7143:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7144:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7145:             my @items = split(/&/,$response);
                   7146:             foreach my $item (@items) {
                   7147:                 my ($key,$value) = split('=',$item);
                   7148:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7149:             }
                   7150:         }
                   7151:     }
1.1010    raeburn  7152:     return %validations; 
                   7153: }
                   7154: 
1.1020    raeburn  7155: sub auto_courserequest_validation {
                   7156:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7157:     my ($homeserver,$response);
                   7158:     if ($dom =~ /^$match_domain$/) {
                   7159:         $homeserver = &domain($dom,'primary');
                   7160:     }
                   7161:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7162:           
1.1020    raeburn  7163:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7164:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7165:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7166:                                     $homeserver));
                   7167:     }
                   7168:     return $response;
                   7169: }
                   7170: 
1.777     albertel 7171: sub auto_validate_class_sec {
1.918     raeburn  7172:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7173:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7174:     my $ownerlist;
                   7175:     if (ref($owners) eq 'ARRAY') {
                   7176:         $ownerlist = join(',',@{$owners});
                   7177:     } else {
                   7178:         $ownerlist = $owners;
                   7179:     }
1.773     raeburn  7180:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7181:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7182:     return $response;
                   7183: }
                   7184: 
1.679     raeburn  7185: # ------------------------------------------------------- Course Group routines
                   7186: 
                   7187: sub get_coursegroups {
1.809     raeburn  7188:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7189:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7190: }
                   7191: 
1.679     raeburn  7192: sub modify_coursegroup {
                   7193:     my ($cdom,$cnum,$groupsettings) = @_;
                   7194:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7195: }
                   7196: 
1.809     raeburn  7197: sub toggle_coursegroup_status {
                   7198:     my ($cdom,$cnum,$group,$action) = @_;
                   7199:     my ($from_namespace,$to_namespace);
                   7200:     if ($action eq 'delete') {
                   7201:         $from_namespace = 'coursegroups';
                   7202:         $to_namespace = 'deleted_groups';
                   7203:     } else {
                   7204:         $from_namespace = 'deleted_groups';
                   7205:         $to_namespace = 'coursegroups';
                   7206:     }
                   7207:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7208:     if (my $tmp = &error(%curr_group)) {
                   7209:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7210:         return ('read error',$tmp);
                   7211:     } else {
                   7212:         my %savedsettings = %curr_group; 
1.809     raeburn  7213:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7214:         my $deloutcome;
                   7215:         if ($result eq 'ok') {
1.809     raeburn  7216:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7217:         } else {
                   7218:             return ('write error',$result);
                   7219:         }
                   7220:         if ($deloutcome eq 'ok') {
                   7221:             return 'ok';
                   7222:         } else {
                   7223:             return ('delete error',$deloutcome);
                   7224:         }
                   7225:     }
                   7226: }
                   7227: 
1.679     raeburn  7228: sub modify_group_roles {
1.957     raeburn  7229:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7230:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7231:     my $role = 'gr/'.&escape($userprivs);
                   7232:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7233:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7234:     if ($result eq 'ok') {
                   7235:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7236:     }
1.679     raeburn  7237:     return $result;
                   7238: }
                   7239: 
                   7240: sub modify_coursegroup_membership {
                   7241:     my ($cdom,$cnum,$membership) = @_;
                   7242:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7243:     return $result;
                   7244: }
                   7245: 
1.682     raeburn  7246: sub get_active_groups {
                   7247:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7248:     my $now = time;
                   7249:     my %groups = ();
                   7250:     foreach my $key (keys(%env)) {
1.811     albertel 7251:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7252:             my ($start,$end) = split(/\./,$env{$key});
                   7253:             if (($end!=0) && ($end<$now)) { next; }
                   7254:             if (($start!=0) && ($start>$now)) { next; }
                   7255:             if ($1 eq $cdom && $2 eq $cnum) {
                   7256:                 $groups{$3} = $env{$key} ;
                   7257:             }
                   7258:         }
                   7259:     }
                   7260:     return %groups;
                   7261: }
                   7262: 
1.683     raeburn  7263: sub get_group_membership {
                   7264:     my ($cdom,$cnum,$group) = @_;
                   7265:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7266: }
                   7267: 
                   7268: sub get_users_groups {
                   7269:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7270:     my @usersgroups;
1.683     raeburn  7271:     my $cachetime=1800;
                   7272: 
                   7273:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7274:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7275:     if (defined($cached)) {
1.734     albertel 7276:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7277:     } else {  
                   7278:         $grouplist = '';
1.816     raeburn  7279:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7280:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7281:         my $access_end = $env{'course.'.$courseid.
                   7282:                               '.default_enrollment_end_date'};
                   7283:         my $now = time;
                   7284:         foreach my $key (keys(%roleshash)) {
                   7285:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7286:                 my $group = $1;
                   7287:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7288:                     my $start = $2;
                   7289:                     my $end = $1;
                   7290:                     if ($start == -1) { next; } # deleted from group
                   7291:                     if (($start!=0) && ($start>$now)) { next; }
                   7292:                     if (($end!=0) && ($end<$now)) {
                   7293:                         if ($access_end && $access_end < $now) {
                   7294:                             if ($access_end - $end < 86400) {
                   7295:                                 push(@usersgroups,$group);
1.733     raeburn  7296:                             }
                   7297:                         }
1.817     raeburn  7298:                         next;
1.733     raeburn  7299:                     }
1.817     raeburn  7300:                     push(@usersgroups,$group);
1.683     raeburn  7301:                 }
                   7302:             }
                   7303:         }
1.817     raeburn  7304:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7305:         $grouplist = join(':',@usersgroups);
                   7306:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7307:     }
1.733     raeburn  7308:     return @usersgroups;
1.683     raeburn  7309: }
                   7310: 
                   7311: sub devalidate_getgroups_cache {
                   7312:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7313:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7314: 
1.683     raeburn  7315:     my $hashid="$udom:$uname:$courseid";
                   7316:     &devalidate_cache_new('getgroups',$hashid);
                   7317: }
                   7318: 
1.12      www      7319: # ------------------------------------------------------------------ Plain Text
                   7320: 
                   7321: sub plaintext {
1.988     raeburn  7322:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7323:     if ($short =~ m{^cr/}) {
1.758     albertel 7324: 	return (split('/',$short))[-1];
                   7325:     }
1.742     raeburn  7326:     if (!defined($cid)) {
                   7327:         $cid = $env{'request.course.id'};
                   7328:     }
                   7329:     my %rolenames = (
1.1008    raeburn  7330:                       Course    => 'std',
                   7331:                       Community => 'alt1',
1.742     raeburn  7332:                     );
1.1037    raeburn  7333:     if ($cid ne '') {
                   7334:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7335:             unless ($forcedefault) {
                   7336:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7337:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7338:                 return &Apache::lonlocal::mt($roletext);
                   7339:             }
                   7340:         }
                   7341:     }
                   7342:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7343:         (defined($rolenames{$type})) && 
                   7344:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7345:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7346:     } elsif ($cid ne '') {
                   7347:         my $crstype = $env{'course.'.$cid.'.type'};
                   7348:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7349:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7350:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7351:         }
1.742     raeburn  7352:     }
1.1037    raeburn  7353:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7354: }
                   7355: 
                   7356: # ----------------------------------------------------------------- Assign Role
                   7357: 
                   7358: sub assignrole {
1.957     raeburn  7359:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7360:         $context)=@_;
1.21      www      7361:     my $mrole;
                   7362:     if ($role =~ /^cr\//) {
1.393     www      7363:         my $cwosec=$url;
1.811     albertel 7364:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7365: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7366:            my $refused = 1;
                   7367:            if ($context eq 'requestcourses') {
                   7368:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7369:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7370:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7371:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7372:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7373:                            if ($crsenv{'internal.courseowner'} eq
                   7374:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7375:                                $refused = '';
                   7376:                            }
                   7377:                        }
                   7378:                    }
                   7379:                }
                   7380:            }
                   7381:            if ($refused) {
                   7382:                &logthis('Refused custom assignrole: '.
                   7383:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7384:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7385:                return 'refused';
                   7386:            }
1.104     www      7387:         }
1.21      www      7388:         $mrole='cr';
1.678     raeburn  7389:     } elsif ($role =~ /^gr\//) {
                   7390:         my $cwogrp=$url;
1.811     albertel 7391:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7392:         unless (&allowed('mdg',$cwogrp)) {
                   7393:             &logthis('Refused group assignrole: '.
                   7394:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7395:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7396:             return 'refused';
                   7397:         }
                   7398:         $mrole='gr';
1.21      www      7399:     } else {
1.82      www      7400:         my $cwosec=$url;
1.811     albertel 7401:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7402:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7403:             my $refused;
                   7404:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7405:                 if (!(&allowed('c'.$role,$url))) {
                   7406:                     $refused = 1;
                   7407:                 }
                   7408:             } else {
                   7409:                 $refused = 1;
                   7410:             }
1.947     raeburn  7411:             if ($refused) {
1.1045    raeburn  7412:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7413:                 if (!$selfenroll && $context eq 'course') {
                   7414:                     my %crsenv;
                   7415:                     if ($role eq 'cc' || $role eq 'co') {
                   7416:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7417:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7418:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7419:                                 if ($crsenv{'internal.courseowner'} eq 
                   7420:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7421:                                     $refused = '';
                   7422:                                 }
                   7423:                             }
                   7424:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7425:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7426:                                 if ($crsenv{'internal.courseowner'} eq 
                   7427:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7428:                                     $refused = '';
                   7429:                                 }
                   7430:                             }
                   7431:                         }
                   7432:                     }
                   7433:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7434:                     $refused = '';
1.1017    raeburn  7435:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7436:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7437:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7438:                         my $wrongcc;
                   7439:                         if ($cnum =~ /^$match_community$/) {
                   7440:                             $wrongcc = 1 if ($role eq 'cc');
                   7441:                         } else {
                   7442:                             $wrongcc = 1 if ($role eq 'co');
                   7443:                         }
                   7444:                         unless ($wrongcc) {
                   7445:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7446:                             if ($crsenv{'internal.courseowner'} eq 
                   7447:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7448:                                 $refused = '';
                   7449:                             }
1.1017    raeburn  7450:                         }
                   7451:                     }
                   7452:                 }
                   7453:                 if ($refused) {
1.947     raeburn  7454:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7455:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7456: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7457:                     return 'refused';
                   7458:                 }
1.932     raeburn  7459:             }
1.1131    raeburn  7460:         } elsif ($role eq 'au') {
                   7461:             if ($url ne '/'.$udom.'/') {
                   7462:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7463:                          ' to assign author role for '.$uname.':'.$udom.
                   7464:                          ' in domain: '.$url.' refused (wrong domain).');
                   7465:                 return 'refused';
                   7466:             }
1.104     www      7467:         }
1.21      www      7468:         $mrole=$role;
                   7469:     }
1.620     albertel 7470:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7471:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7472:     if ($end) { $command.='_'.$end; }
1.21      www      7473:     if ($start) {
                   7474: 	if ($end) { 
1.81      www      7475:            $command.='_'.$start; 
1.21      www      7476:         } else {
1.81      www      7477:            $command.='_0_'.$start;
1.21      www      7478:         }
                   7479:     }
1.739     raeburn  7480:     my $origstart = $start;
                   7481:     my $origend = $end;
1.957     raeburn  7482:     my $delflag;
1.357     www      7483: # actually delete
                   7484:     if ($deleteflag) {
1.373     www      7485: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7486: # modify command to delete the role
1.620     albertel 7487:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7488:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7489: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7490: # set start and finish to negative values for userrolelog
                   7491:            $start=-1;
                   7492:            $end=-1;
1.957     raeburn  7493:            $delflag = 1;
1.357     www      7494:         }
                   7495:     }
                   7496: # send command
1.349     www      7497:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7498: # log new user role if status is ok
1.349     www      7499:     if ($answer eq 'ok') {
1.663     raeburn  7500: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7501: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7502:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7503:         unless ($role =~ /^gr/) {
                   7504:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7505:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7506:         }
1.1053    raeburn  7507:         if ($role eq 'cc') {
                   7508:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7509:         }
1.349     www      7510:     }
                   7511:     return $answer;
1.169     harris41 7512: }
                   7513: 
1.1053    raeburn  7514: sub autoupdate_coowners {
                   7515:     my ($url,$end,$start,$uname,$udom) = @_;
                   7516:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7517:     if (($cdom ne '') && ($cnum ne '')) {
                   7518:         my $now = time;
                   7519:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7520:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7521:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7522:             my $instcode = $coursehash{'internal.coursecode'};
                   7523:             if ($instcode ne '') {
1.1056    raeburn  7524:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7525:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7526:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7527:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7528:                         if ($result eq 'valid') {
                   7529:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7530:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7531:                                     push(@newcoowners,$coowner);
                   7532:                                 }
                   7533:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7534:                                     push(@newcoowners,$uname.':'.$udom);
                   7535:                                 }
                   7536:                                 @newcoowners = sort(@newcoowners);
                   7537:                             } else {
                   7538:                                 push(@newcoowners,$uname.':'.$udom);
                   7539:                             }
                   7540:                         } else {
                   7541:                             if ($coursehash{'internal.co-owners'}) {
                   7542:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7543:                                     unless ($coowner eq $uname.':'.$udom) {
                   7544:                                         push(@newcoowners,$coowner);
                   7545:                                     }
                   7546:                                 }
                   7547:                                 unless (@newcoowners > 0) {
                   7548:                                     $delcoowners = 1;
                   7549:                                     $coowners = '';
                   7550:                                 }
                   7551:                             }
                   7552:                         }
                   7553:                         if (@newcoowners || $delcoowners) {
                   7554:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7555:                                             $delcoowners,@newcoowners);
                   7556:                         }
                   7557:                     }
                   7558:                 }
                   7559:             }
                   7560:         }
                   7561:     }
                   7562: }
                   7563: 
                   7564: sub store_coowners {
                   7565:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7566:     my $cid = $cdom.'_'.$cnum;
                   7567:     my ($coowners,$delresult,$putresult);
                   7568:     if (@newcoowners) {
                   7569:         $coowners = join(',',@newcoowners);
                   7570:         my %coownershash = (
                   7571:                             'internal.co-owners' => $coowners,
                   7572:                            );
                   7573:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7574:         if ($putresult eq 'ok') {
                   7575:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7576:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7577:             }
                   7578:         }
                   7579:     }
                   7580:     if ($delcoowners) {
                   7581:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7582:         if ($delresult eq 'ok') {
                   7583:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7584:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7585:             }
                   7586:         }
                   7587:     }
                   7588:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7589:         my %crsinfo =
                   7590:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7591:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7592:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7593:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7594:         }
                   7595:     }
                   7596: }
                   7597: 
1.169     harris41 7598: # -------------------------------------------------- Modify user authentication
1.197     www      7599: # Overrides without validation
                   7600: 
1.169     harris41 7601: sub modifyuserauth {
                   7602:     my ($udom,$uname,$umode,$upass)=@_;
                   7603:     my $uhome=&homeserver($uname,$udom);
1.197     www      7604:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7605:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7606:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7607:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7608:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7609: 		     &escape($upass),$uhome);
1.620     albertel 7610:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7611:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7612:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7613:     &log($udom,,$uname,$uhome,
1.620     albertel 7614:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7615:                                      $env{'user.name'}.', '.$umode.
1.197     www      7616:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7617:     unless ($reply eq 'ok') {
1.197     www      7618:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7619: 	return 'error: '.$reply;
                   7620:     }   
1.170     harris41 7621:     return 'ok';
1.80      www      7622: }
                   7623: 
1.81      www      7624: # --------------------------------------------------------------- Modify a user
1.80      www      7625: 
1.81      www      7626: sub modifyuser {
1.206     matthew  7627:     my ($udom,    $uname, $uid,
                   7628:         $umode,   $upass, $first,
                   7629:         $middle,  $last,  $gene,
1.1058    raeburn  7630:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7631:     $udom= &LONCAPA::clean_domain($udom);
                   7632:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7633:     my $showcandelete = 'none';
                   7634:     if (ref($candelete) eq 'ARRAY') {
                   7635:         if (@{$candelete} > 0) {
                   7636:             $showcandelete = join(', ',@{$candelete});
                   7637:         }
                   7638:     }
1.81      www      7639:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7640:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7641: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7642:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7643:                                      ' desiredhome not specified'). 
1.620     albertel 7644:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7645:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7646:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7647:     my $newuser;
                   7648:     if ($uhome eq 'no_host') {
                   7649:         $newuser = 1;
                   7650:     }
1.80      www      7651: # ----------------------------------------------------------------- Create User
1.406     albertel 7652:     if (($uhome eq 'no_host') && 
                   7653: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7654:         my $unhome='';
1.844     albertel 7655:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7656:             $unhome = $desiredhome;
1.620     albertel 7657: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7658: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7659:         } else { # load balancing routine for determining $unhome
1.81      www      7660:             my $loadm=10000000;
1.841     albertel 7661: 	    my %servers = &get_servers($udom,'library');
                   7662: 	    foreach my $tryserver (keys(%servers)) {
                   7663: 		my $answer=reply('load',$tryserver);
                   7664: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7665: 		    $loadm=$answer;
                   7666: 		    $unhome=$tryserver;
                   7667: 		}
1.80      www      7668: 	    }
                   7669:         }
                   7670:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7671: 	    return 'error: unable to find a home server for '.$uname.
                   7672:                    ' in domain '.$udom;
1.80      www      7673:         }
                   7674:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7675:                          &escape($upass),$unhome);
                   7676: 	unless ($reply eq 'ok') {
                   7677:             return 'error: '.$reply;
                   7678:         }   
1.230     stredwic 7679:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7680:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7681: 	    return 'error: unable verify users home machine.';
1.80      www      7682:         }
1.209     matthew  7683:     }   # End of creation of new user
1.80      www      7684: # ---------------------------------------------------------------------- Add ID
                   7685:     if ($uid) {
                   7686:        $uid=~tr/A-Z/a-z/;
                   7687:        my %uidhash=&idrget($udom,$uname);
1.196     www      7688:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7689:          && (!$forceid)) {
1.80      www      7690: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7691: 	      return 'error: user id "'.$uid.'" does not match '.
                   7692:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7693:           }
                   7694:        } else {
                   7695: 	  &idput($udom,($uname => $uid));
                   7696:        }
                   7697:     }
                   7698: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7699:     my @tmp=&get('environment',
1.899     raeburn  7700: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7701:                     'permanentemail','inststatus'],
1.134     albertel 7702: 		   $udom,$uname);
1.1075    raeburn  7703:     my (%names,%oldnames);
1.313     matthew  7704:     if ($tmp[0] =~ m/^error:.*/) { 
                   7705:         %names=(); 
                   7706:     } else {
                   7707:         %names = @tmp;
1.1075    raeburn  7708:         %oldnames = %names;
1.313     matthew  7709:     }
1.388     www      7710: #
1.1058    raeburn  7711: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7712: # of users did not contain them), do not overwrite existing values
                   7713: # unless field is in $candelete array ref.  
                   7714: #
                   7715: 
                   7716:     my @fields = ('firstname','middlename','lastname','generation',
                   7717:                   'permanentemail','id');
                   7718:     my %newvalues;
                   7719:     if (ref($candelete) eq 'ARRAY') {
                   7720:         foreach my $field (@fields) {
                   7721:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7722:                 if ($field eq 'firstname') {
                   7723:                     $names{$field} = $first;
                   7724:                 } elsif ($field eq 'middlename') {
                   7725:                     $names{$field} = $middle;
                   7726:                 } elsif ($field eq 'lastname') {
                   7727:                     $names{$field} = $last;
                   7728:                 } elsif ($field eq 'generation') { 
                   7729:                     $names{$field} = $gene;
                   7730:                 } elsif ($field eq 'permanentemail') {
                   7731:                     $names{$field} = $email;
                   7732:                 } elsif ($field eq 'id') {
                   7733:                     $names{$field}  = $uid;
                   7734:                 }
                   7735:             }
                   7736:         }
                   7737:     }
1.388     www      7738:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7739:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7740:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7741:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7742:     if ($email) {
                   7743:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7744:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7745:     }
1.899     raeburn  7746:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7747:     if (defined($inststatus)) {
                   7748:         $names{'inststatus'} = '';
                   7749:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7750:         if (ref($usertypes) eq 'HASH') {
                   7751:             my @okstatuses; 
                   7752:             foreach my $item (split(/:/,$inststatus)) {
                   7753:                 if (defined($usertypes->{$item})) {
                   7754:                     push(@okstatuses,$item);  
                   7755:                 }
                   7756:             }
                   7757:             if (@okstatuses) {
                   7758:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7759:             }
                   7760:         }
                   7761:     }
1.1075    raeburn  7762:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7763:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7764:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7765:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7766:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7767:     } else {
                   7768:         $logmsg .= ' during self creation';
                   7769:     }
1.1075    raeburn  7770:     my $changed;
                   7771:     if ($newuser) {
                   7772:         $changed = 1;
                   7773:     } else {
                   7774:         foreach my $field (@fields) {
                   7775:             if ($names{$field} ne $oldnames{$field}) {
                   7776:                 $changed = 1;
                   7777:                 last;
                   7778:             }
                   7779:         }
                   7780:     }
                   7781:     unless ($changed) {
                   7782:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7783:         &logthis($logmsg);
                   7784:         return 'ok';
                   7785:     }
                   7786:     my $reply = &put('environment', \%names, $udom,$uname);
                   7787:     if ($reply ne 'ok') { 
                   7788:         return 'error: '.$reply;
                   7789:     }
1.1087    raeburn  7790:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7791:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7792:     }
1.1075    raeburn  7793:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7794:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7795:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7796:     &logthis($logmsg);
1.134     albertel 7797:     return 'ok';
1.80      www      7798: }
                   7799: 
1.81      www      7800: # -------------------------------------------------------------- Modify student
1.80      www      7801: 
1.81      www      7802: sub modifystudent {
                   7803:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7804:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7805:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7806:     if (!$cid) {
1.620     albertel 7807: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7808: 	    return 'not_in_class';
                   7809: 	}
1.80      www      7810:     }
                   7811: # --------------------------------------------------------------- Make the user
1.81      www      7812:     my $reply=&modifyuser
1.209     matthew  7813: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7814:          $desiredhome,$email,$inststatus);
1.80      www      7815:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7816:     # This will cause &modify_student_enrollment to get the uid from the
                   7817:     # students environment
                   7818:     $uid = undef if (!$forceid);
1.455     albertel 7819:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7820: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7821:     return $reply;
                   7822: }
                   7823: 
                   7824: sub modify_student_enrollment {
1.957     raeburn  7825:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7826:     my ($cdom,$cnum,$chome);
                   7827:     if (!$cid) {
1.620     albertel 7828: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7829: 	    return 'not_in_class';
                   7830: 	}
1.620     albertel 7831: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7832: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7833:     } else {
                   7834: 	($cdom,$cnum)=split(/_/,$cid);
                   7835:     }
1.620     albertel 7836:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7837:     if (!$chome) {
1.457     raeburn  7838: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7839:     }
1.455     albertel 7840:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7841:     # Make sure the user exists
1.81      www      7842:     my $uhome=&homeserver($uname,$udom);
                   7843:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7844: 	return 'error: no such user';
                   7845:     }
1.297     matthew  7846:     # Get student data if we were not given enough information
                   7847:     if (!defined($first)  || $first  eq '' || 
                   7848:         !defined($last)   || $last   eq '' || 
                   7849:         !defined($uid)    || $uid    eq '' || 
                   7850:         !defined($middle) || $middle eq '' || 
                   7851:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7852:         # They did not supply us with enough data to enroll the student, so
                   7853:         # we need to pick up more information.
1.297     matthew  7854:         my %tmp = &get('environment',
1.294     matthew  7855:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7856:                        ,$udom,$uname);
                   7857: 
1.800     albertel 7858:         #foreach my $key (keys(%tmp)) {
                   7859:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7860:         #}
1.294     matthew  7861:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7862:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7863:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7864:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7865:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7866:     }
1.556     albertel 7867:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7868:     my $user = "$uname:$udom";
                   7869:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7870:     my $reply=cput('classlist',
1.1148    raeburn  7871: 		   {$user => 
1.515     raeburn  7872: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7873: 		   $cdom,$cnum);
1.1148    raeburn  7874:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7875:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7876:     } else { 
1.81      www      7877: 	return 'error: '.$reply;
                   7878:     }
1.297     matthew  7879:     # Add student role to user
1.83      www      7880:     my $uurl='/'.$cid;
1.81      www      7881:     $uurl=~s/\_/\//g;
                   7882:     if ($usec) {
                   7883: 	$uurl.='/'.$usec;
                   7884:     }
1.1148    raeburn  7885:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7886:                              $selfenroll,$context);
                   7887:     if ($result ne 'ok') {
                   7888:         if ($old_entry{$user} ne '') {
                   7889:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7890:         } else {
                   7891:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7892:         }
                   7893:     }
                   7894:     return $result; 
1.21      www      7895: }
                   7896: 
1.556     albertel 7897: sub format_name {
                   7898:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7899:     my $name;
                   7900:     if ($first ne 'lastname') {
                   7901: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7902:     } else {
                   7903: 	if ($lastname=~/\S/) {
                   7904: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7905: 	    $name=~s/\s+,/,/;
                   7906: 	} else {
                   7907: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7908: 	}
                   7909:     }
                   7910:     $name=~s/^\s+//;
                   7911:     $name=~s/\s+$//;
                   7912:     $name=~s/\s+/ /g;
                   7913:     return $name;
                   7914: }
                   7915: 
1.84      www      7916: # ------------------------------------------------- Write to course preferences
                   7917: 
                   7918: sub writecoursepref {
                   7919:     my ($courseid,%prefs)=@_;
                   7920:     $courseid=~s/^\///;
                   7921:     $courseid=~s/\_/\//g;
                   7922:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7923:     my $chome=homeserver($cnum,$cdomain);
                   7924:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7925: 	return 'error: no such course';
                   7926:     }
                   7927:     my $cstring='';
1.800     albertel 7928:     foreach my $pref (keys(%prefs)) {
                   7929: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7930:     }
1.84      www      7931:     $cstring=~s/\&$//;
                   7932:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7933: }
                   7934: 
                   7935: # ---------------------------------------------------------- Make/modify course
                   7936: 
                   7937: sub createcourse {
1.741     raeburn  7938:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7939:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7940:     $url=&declutter($url);
                   7941:     my $cid='';
1.1028    raeburn  7942:     if ($context eq 'requestcourses') {
                   7943:         my $can_create = 0;
                   7944:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7945:         if ($udom eq $ownerdom) {
                   7946:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7947:                                   $context)) {
                   7948:                 $can_create = 1;
                   7949:             }
                   7950:         } else {
                   7951:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7952:                                            $category);
                   7953:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7954:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7955:                 if (@curr > 0) {
                   7956:                     my @options = qw(approval validate autolimit);
                   7957:                     my $optregex = join('|',@options);
                   7958:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7959:                         $can_create = 1;
                   7960:                     }
                   7961:                 }
                   7962:             }
                   7963:         }
                   7964:         if ($can_create) {
                   7965:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7966:                 unless (&allowed('ccc',$udom)) {
                   7967:                     return 'refused'; 
                   7968:                 }
1.1017    raeburn  7969:             }
                   7970:         } else {
                   7971:             return 'refused';
                   7972:         }
1.1028    raeburn  7973:     } elsif (!&allowed('ccc',$udom)) {
                   7974:         return 'refused';
1.84      www      7975:     }
1.1011    raeburn  7976: # --------------------------------------------------------------- Get Unique ID
                   7977:     my $uname;
                   7978:     if ($cnum =~ /^$match_courseid$/) {
                   7979:         my $chome=&homeserver($cnum,$udom,'true');
                   7980:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7981:             $uname = $cnum;
                   7982:         } else {
1.1038    raeburn  7983:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7984:         }
                   7985:     } else {
1.1038    raeburn  7986:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7987:     }
                   7988:     return $uname if ($uname =~ /^error/);
                   7989: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7990:     if (!defined($course_server)) {
                   7991:         if (defined(&domain($udom,'primary'))) {
                   7992:             $course_server = &domain($udom,'primary');
                   7993:         } else {
                   7994:             $course_server = $env{'user.home'}; 
                   7995:         }
                   7996:     }
                   7997:     my %host_servers =
                   7998:         &Apache::lonnet::get_servers($udom,'library');
                   7999:     unless ($host_servers{$course_server}) {
                   8000:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8001:     }
1.84      www      8002: # ------------------------------------------------------------- Make the course
                   8003:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8004:                       $course_server);
1.84      www      8005:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8006:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8007:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8008: 	return 'error: no such course';
                   8009:     }
1.271     www      8010: # ----------------------------------------------------------------- Course made
1.516     raeburn  8011: # log existence
1.1029    raeburn  8012:     my $now = time;
1.918     raeburn  8013:     my $newcourse = {
                   8014:                     $udom.'_'.$uname => {
1.921     raeburn  8015:                                      description => $description,
                   8016:                                      inst_code   => $inst_code,
                   8017:                                      owner       => $course_owner,
                   8018:                                      type        => $crstype,
1.1029    raeburn  8019:                                      creator     => $env{'user.name'}.':'.
                   8020:                                                     $env{'user.domain'},
                   8021:                                      created     => $now,
                   8022:                                      context     => $context,
1.918     raeburn  8023:                                                 },
                   8024:                     };
1.921     raeburn  8025:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8026: # set toplevel url
1.271     www      8027:     my $topurl=$url;
                   8028:     unless ($nonstandard) {
                   8029: # ------------------------------------------ For standard courses, make top url
                   8030:         my $mapurl=&clutter($url);
1.278     www      8031:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8032:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8033: <map>
                   8034: <resource id="1" type="start"></resource>
                   8035: <resource id="2" src="$mapurl"></resource>
                   8036: <resource id="3" type="finish"></resource>
                   8037: <link index="1" from="1" to="2"></link>
                   8038: <link index="2" from="2" to="3"></link>
                   8039: </map>
                   8040: ENDINITMAP
                   8041:         $topurl=&declutter(
1.638     albertel 8042:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8043:                           );
                   8044:     }
                   8045: # ----------------------------------------------------------- Write preferences
1.84      www      8046:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8047:                      ('description'              => $description,
                   8048:                       'url'                      => $topurl,
                   8049:                       'internal.creator'         => $env{'user.name'}.':'.
                   8050:                                                     $env{'user.domain'},
                   8051:                       'internal.created'         => $now,
                   8052:                       'internal.creationcontext' => $context)
                   8053:                     );
1.84      www      8054:     return '/'.$udom.'/'.$uname;
                   8055: }
                   8056: 
1.1011    raeburn  8057: # ------------------------------------------------------------------- Create ID
                   8058: sub generate_coursenum {
1.1038    raeburn  8059:     my ($udom,$crstype) = @_;
1.1011    raeburn  8060:     my $domdesc = &domain($udom);
                   8061:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8062:     my $first;
                   8063:     if ($crstype eq 'Community') {
                   8064:         $first = '0';
                   8065:     } else {
                   8066:         $first = int(1+rand(9)); 
                   8067:     } 
                   8068:     my $uname=$first.
1.1011    raeburn  8069:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8070:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8071:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8072: # ----------------------------------------------- Make sure that does not exist
                   8073:     my $uhome=&homeserver($uname,$udom,'true');
                   8074:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8075:         if ($crstype eq 'Community') {
                   8076:             $first = '0';
                   8077:         } else {
                   8078:             $first = int(1+rand(9));
                   8079:         }
                   8080:         $uname=$first.
1.1011    raeburn  8081:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8082:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8083:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8084:         $uhome=&homeserver($uname,$udom,'true');
                   8085:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8086:             return 'error: unable to generate unique course-ID';
                   8087:         }
                   8088:     }
                   8089:     return $uname;
                   8090: }
                   8091: 
1.813     albertel 8092: sub is_course {
1.1167    droeschl 8093:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8094:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8095: 
                   8096:     return unless $cdom and $cnum;
                   8097: 
                   8098:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8099:         '.');
                   8100: 
                   8101:     return unless exists($courses{$cdom.'_'.$cnum});
                   8102:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8103: }
                   8104: 
1.1015    raeburn  8105: sub store_userdata {
                   8106:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8107:     my $result;
1.1016    raeburn  8108:     if ($datakey ne '') {
1.1013    raeburn  8109:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8110:             if ($udom eq '' || $uname eq '') {
                   8111:                 $udom = $env{'user.domain'};
                   8112:                 $uname = $env{'user.name'};
                   8113:             }
                   8114:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8115:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8116:                 $result = 'error: no_host';
                   8117:             } else {
                   8118:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8119:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8120: 
                   8121:                 my $namevalue='';
                   8122:                 foreach my $key (keys(%{$storehash})) {
                   8123:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8124:                 }
                   8125:                 $namevalue=~s/\&$//;
1.1105    raeburn  8126:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8127:                                   $namevalue,$uhome);
1.1013    raeburn  8128:             }
                   8129:         } else {
                   8130:             $result = 'error: data to store was not a hash reference'; 
                   8131:         }
                   8132:     } else {
                   8133:         $result= 'error: invalid requestkey'; 
                   8134:     }
                   8135:     return $result;
                   8136: }
                   8137: 
1.21      www      8138: # ---------------------------------------------------------- Assign Custom Role
                   8139: 
                   8140: sub assigncustomrole {
1.957     raeburn  8141:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8142:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8143:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8144: }
                   8145: 
                   8146: # ----------------------------------------------------------------- Revoke Role
                   8147: 
                   8148: sub revokerole {
1.957     raeburn  8149:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8150:     my $now=time;
1.965     raeburn  8151:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8152: }
                   8153: 
                   8154: # ---------------------------------------------------------- Revoke Custom Role
                   8155: 
                   8156: sub revokecustomrole {
1.957     raeburn  8157:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8158:     my $now=time;
1.357     www      8159:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8160:            $deleteflag,$selfenroll,$context);
1.17      www      8161: }
                   8162: 
1.533     banghart 8163: # ------------------------------------------------------------ Disk usage
1.535     albertel 8164: sub diskusage {
1.955     raeburn  8165:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8166:     $directorypath =~ s/\/$//;
                   8167:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8168:                        .&escape($getpropath).':'.&escape($uname).':'
                   8169:                        .&escape($udom),homeserver($uname,$udom));
                   8170:     if ($listing eq 'unknown_cmd') {
                   8171:         if ($getpropath) {
                   8172:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8173:         }
                   8174:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8175:     }
1.514     albertel 8176:     return $listing;
1.512     banghart 8177: }
                   8178: 
1.566     banghart 8179: sub is_locked {
1.1096    raeburn  8180:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8181:     my @check;
                   8182:     my $is_locked;
1.1093    raeburn  8183:     push (@check,$file_name);
1.613     albertel 8184:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8185: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8186:     my ($tmp)=keys(%locked);
                   8187:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8188:     
1.566     banghart 8189:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8190:         $is_locked = 'false';
                   8191:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8192:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8193:                $is_locked = 'true';
1.1096    raeburn  8194:                if (ref($which) eq 'ARRAY') {
                   8195:                    push(@{$which},$entry);
                   8196:                } else {
                   8197:                    last;
                   8198:                }
1.745     raeburn  8199:            }
                   8200:        }
1.566     banghart 8201:     } else {
                   8202:         $is_locked = 'false';
                   8203:     }
1.1093    raeburn  8204:     return $is_locked;
1.566     banghart 8205: }
                   8206: 
1.759     albertel 8207: sub declutter_portfile {
                   8208:     my ($file) = @_;
1.833     albertel 8209:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8210:     return $file;
                   8211: }
                   8212: 
1.559     banghart 8213: # ------------------------------------------------------------- Mark as Read Only
                   8214: 
                   8215: sub mark_as_readonly {
                   8216:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8217:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8218:     my ($tmp)=keys(%current_permissions);
                   8219:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8220:     foreach my $file (@{$files}) {
1.759     albertel 8221: 	$file = &declutter_portfile($file);
1.561     banghart 8222:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8223:     }
1.613     albertel 8224:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8225:     return;
                   8226: }
                   8227: 
1.572     banghart 8228: # ------------------------------------------------------------Save Selected Files
                   8229: 
                   8230: sub save_selected_files {
                   8231:     my ($user, $path, @files) = @_;
                   8232:     my $filename = $user."savedfiles";
1.573     banghart 8233:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8234:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8235:     foreach my $file (@files) {
1.620     albertel 8236:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8237:     }
                   8238:     foreach my $file (@other_files) {
1.574     banghart 8239:         print (OUT $file."\n");
1.572     banghart 8240:     }
1.574     banghart 8241:     close (OUT);
1.572     banghart 8242:     return 'ok';
                   8243: }
                   8244: 
1.574     banghart 8245: sub clear_selected_files {
                   8246:     my ($user) = @_;
                   8247:     my $filename = $user."savedfiles";
1.1117    foxr     8248:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8249:     print (OUT undef);
                   8250:     close (OUT);
                   8251:     return ("ok");    
                   8252: }
                   8253: 
1.572     banghart 8254: sub files_in_path {
                   8255:     my ($user, $path) = @_;
                   8256:     my $filename = $user."savedfiles";
                   8257:     my %return_files;
1.1117    foxr     8258:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8259:     while (my $line_in = <IN>) {
1.574     banghart 8260:         chomp ($line_in);
                   8261:         my @paths_and_file = split (m!/!, $line_in);
                   8262:         my $file_part = pop (@paths_and_file);
                   8263:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8264:         $path_part.='/';
                   8265:         my $path_and_file = $path_part.$file_part;
                   8266:         if ($path_part eq $path) {
                   8267:             $return_files{$file_part}= 'selected';
                   8268:         }
                   8269:     }
1.574     banghart 8270:     close (IN);
                   8271:     return (\%return_files);
1.572     banghart 8272: }
                   8273: 
                   8274: # called in portfolio select mode, to show files selected NOT in current directory
                   8275: sub files_not_in_path {
                   8276:     my ($user, $path) = @_;
                   8277:     my $filename = $user."savedfiles";
                   8278:     my @return_files;
                   8279:     my $path_part;
1.1117    foxr     8280:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8281:     while (my $line = <IN>) {
1.572     banghart 8282:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8283:         my @paths_and_file = split(m|/|, $line);
                   8284:         my $file_part = pop(@paths_and_file);
                   8285:         chomp($file_part);
                   8286:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8287:         $path_part .= '/';
                   8288:         my $path_and_file = $path_part.$file_part;
                   8289:         if ($path_part ne $path) {
1.800     albertel 8290:             push(@return_files, ($path_and_file));
1.572     banghart 8291:         }
                   8292:     }
1.800     albertel 8293:     close(OUT);
1.574     banghart 8294:     return (@return_files);
1.572     banghart 8295: }
                   8296: 
1.745     raeburn  8297: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8298: 
1.745     raeburn  8299: sub get_portfile_permissions {
                   8300:     my ($domain,$user) = @_;
1.613     albertel 8301:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8302:     my ($tmp)=keys(%current_permissions);
                   8303:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8304:     return \%current_permissions;
                   8305: }
                   8306: 
                   8307: #---------------------------------------------Get portfolio file access controls
                   8308: 
1.749     raeburn  8309: sub get_access_controls {
1.745     raeburn  8310:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8311:     my %access;
                   8312:     my $real_file = $file;
                   8313:     $file =~ s/\.meta$//;
1.745     raeburn  8314:     if (defined($file)) {
1.749     raeburn  8315:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8316:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8317:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8318:             }
                   8319:         }
1.745     raeburn  8320:     } else {
1.749     raeburn  8321:         foreach my $key (keys(%{$current_permissions})) {
                   8322:             if ($key =~ /\0accesscontrol$/) {
                   8323:                 if (defined($group)) {
                   8324:                     if ($key !~ m-^\Q$group\E/-) {
                   8325:                         next;
                   8326:                     }
                   8327:                 }
                   8328:                 my ($fullpath) = split(/\0/,$key);
                   8329:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8330:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8331:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8332:                     }
                   8333:                 }
                   8334:             }
                   8335:         }
                   8336:     }
                   8337:     return %access;
                   8338: }
                   8339: 
                   8340: sub modify_access_controls {
                   8341:     my ($file_name,$changes,$domain,$user)=@_;
                   8342:     my ($outcome,$deloutcome);
                   8343:     my %store_permissions;
                   8344:     my %new_values;
                   8345:     my %new_control;
                   8346:     my %translation;
                   8347:     my @deletions = ();
                   8348:     my $now = time;
                   8349:     if (exists($$changes{'activate'})) {
                   8350:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8351:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8352:             my $numnew = scalar(@newitems);
                   8353:             for (my $i=0; $i<$numnew; $i++) {
                   8354:                 my $newkey = $newitems[$i];
                   8355:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8356:                 if ($newkey =~ /^\d+:/) { 
                   8357:                     $newkey =~ s/^(\d+)/$newid/;
                   8358:                     $translation{$1} = $newid;
                   8359:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8360:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8361:                     $translation{$1} = $newid;
                   8362:                 }
1.749     raeburn  8363:                 $new_values{$file_name."\0".$newkey} = 
                   8364:                                           $$changes{'activate'}{$newitems[$i]};
                   8365:                 $new_control{$newkey} = $now;
                   8366:             }
                   8367:         }
                   8368:     }
                   8369:     my %todelete;
                   8370:     my %changed_items;
                   8371:     foreach my $action ('delete','update') {
                   8372:         if (exists($$changes{$action})) {
                   8373:             if (ref($$changes{$action}) eq 'HASH') {
                   8374:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8375:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8376:                     if ($action eq 'delete') { 
                   8377:                         $todelete{$itemnum} = 1;
                   8378:                     } else {
                   8379:                         $changed_items{$itemnum} = $key;
                   8380:                     }
                   8381:                 }
1.745     raeburn  8382:             }
                   8383:         }
1.749     raeburn  8384:     }
                   8385:     # get lock on access controls for file.
                   8386:     my $lockhash = {
                   8387:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8388:                                                        ':'.$env{'user.domain'},
                   8389:                    }; 
                   8390:     my $tries = 0;
                   8391:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8392:    
                   8393:     while (($gotlock ne 'ok') && $tries <3) {
                   8394:         $tries ++;
                   8395:         sleep 1;
                   8396:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8397:     }
                   8398:     if ($gotlock eq 'ok') {
                   8399:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8400:         my ($tmp)=keys(%curr_permissions);
                   8401:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8402:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8403:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8404:             if (ref($curr_controls) eq 'HASH') {
                   8405:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8406:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8407:                     if (defined($todelete{$itemnum})) {
                   8408:                         push(@deletions,$file_name."\0".$control_item);
                   8409:                     } else {
                   8410:                         if (defined($changed_items{$itemnum})) {
                   8411:                             $new_control{$changed_items{$itemnum}} = $now;
                   8412:                             push(@deletions,$file_name."\0".$control_item);
                   8413:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8414:                         } else {
                   8415:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8416:                         }
                   8417:                     }
1.745     raeburn  8418:                 }
                   8419:             }
                   8420:         }
1.970     raeburn  8421:         my ($group);
                   8422:         if (&is_course($domain,$user)) {
                   8423:             ($group,my $file) = split(/\//,$file_name,2);
                   8424:         }
1.749     raeburn  8425:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8426:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8427:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8428:         #  remove lock
                   8429:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8430:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8431:         my $sqlresult =
1.970     raeburn  8432:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8433:                                     $group);
1.749     raeburn  8434:     } else {
                   8435:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8436:     }
1.749     raeburn  8437:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8438: }
                   8439: 
1.827     raeburn  8440: sub make_public_indefinitely {
                   8441:     my ($requrl) = @_;
                   8442:     my $now = time;
                   8443:     my $action = 'activate';
                   8444:     my $aclnum = 0;
                   8445:     if (&is_portfolio_url($requrl)) {
                   8446:         my (undef,$udom,$unum,$file_name,$group) =
                   8447:             &parse_portfolio_url($requrl);
                   8448:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8449:         my %access_controls = &get_access_controls($current_perms,
                   8450:                                                    $group,$file_name);
                   8451:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8452:             my ($num,$scope,$end,$start) = 
                   8453:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8454:             if ($scope eq 'public') {
                   8455:                 if ($start <= $now && $end == 0) {
                   8456:                     $action = 'none';
                   8457:                 } else {
                   8458:                     $action = 'update';
                   8459:                     $aclnum = $num;
                   8460:                 }
                   8461:                 last;
                   8462:             }
                   8463:         }
                   8464:         if ($action eq 'none') {
                   8465:              return 'ok';
                   8466:         } else {
                   8467:             my %changes;
                   8468:             my $newend = 0;
                   8469:             my $newstart = $now;
                   8470:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8471:             $changes{$action}{$newkey} = {
                   8472:                 type => 'public',
                   8473:                 time => {
                   8474:                     start => $newstart,
                   8475:                     end   => $newend,
                   8476:                 },
                   8477:             };
                   8478:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8479:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8480:             return $outcome;
                   8481:         }
                   8482:     } else {
                   8483:         return 'invalid';
                   8484:     }
                   8485: }
                   8486: 
1.745     raeburn  8487: #------------------------------------------------------Get Marked as Read Only
                   8488: 
                   8489: sub get_marked_as_readonly {
                   8490:     my ($domain,$user,$what,$group) = @_;
                   8491:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8492:     my @readonly_files;
1.629     banghart 8493:     my $cmp1=$what;
                   8494:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8495:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8496:         if (defined($group)) {
                   8497:             if ($file_name !~ m-^\Q$group\E/-) {
                   8498:                 next;
                   8499:             }
                   8500:         }
1.561     banghart 8501:         if (ref($value) eq "ARRAY"){
                   8502:             foreach my $stored_what (@{$value}) {
1.629     banghart 8503:                 my $cmp2=$stored_what;
1.759     albertel 8504:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8505:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8506:                 }
1.629     banghart 8507:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8508:                     push(@readonly_files, $file_name);
1.745     raeburn  8509:                     last;
1.563     banghart 8510:                 } elsif (!defined($what)) {
                   8511:                     push(@readonly_files, $file_name);
1.745     raeburn  8512:                     last;
1.561     banghart 8513:                 }
                   8514:             }
1.745     raeburn  8515:         }
1.561     banghart 8516:     }
                   8517:     return @readonly_files;
                   8518: }
1.577     banghart 8519: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8520: 
1.577     banghart 8521: sub get_marked_as_readonly_hash {
1.745     raeburn  8522:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8523:     my %readonly_files;
1.745     raeburn  8524:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8525:         if (defined($group)) {
                   8526:             if ($file_name !~ m-^\Q$group\E/-) {
                   8527:                 next;
                   8528:             }
                   8529:         }
1.577     banghart 8530:         if (ref($value) eq "ARRAY"){
                   8531:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8532:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8533:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8534:                         if ($lock_descriptor eq 'graded') {
                   8535:                             $readonly_files{$file_name} = 'graded';
                   8536:                         } elsif ($lock_descriptor eq 'handback') {
                   8537:                             $readonly_files{$file_name} = 'handback';
                   8538:                         } else {
                   8539:                             if (!exists($readonly_files{$file_name})) {
                   8540:                                 $readonly_files{$file_name} = 'locked';
                   8541:                             }
                   8542:                         }
1.745     raeburn  8543:                     }
1.750     banghart 8544:                 } 
1.577     banghart 8545:             }
                   8546:         } 
                   8547:     }
                   8548:     return %readonly_files;
                   8549: }
1.559     banghart 8550: # ------------------------------------------------------------ Unmark as Read Only
                   8551: 
                   8552: sub unmark_as_readonly {
1.629     banghart 8553:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8554:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8555:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8556:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8557:     my $symb_crs = $what;
                   8558:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8559:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8560:     my ($tmp)=keys(%current_permissions);
                   8561:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8562:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8563:     foreach my $file (@readonly_files) {
1.759     albertel 8564: 	my $clean_file = &declutter_portfile($file);
                   8565: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8566: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8567:         my @new_locks;
                   8568:         my @del_keys;
                   8569:         if (ref($current_locks) eq "ARRAY"){
                   8570:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8571:                 my $compare=$locker;
1.749     raeburn  8572:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8573:                     $compare=join('',@{$locker});
1.746     raeburn  8574:                     if ($compare ne $symb_crs) {
                   8575:                         push(@new_locks, $locker);
                   8576:                     }
1.563     banghart 8577:                 }
                   8578:             }
1.650     albertel 8579:             if (scalar(@new_locks) > 0) {
1.563     banghart 8580:                 $current_permissions{$file} = \@new_locks;
                   8581:             } else {
                   8582:                 push(@del_keys, $file);
1.613     albertel 8583:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8584:                 delete($current_permissions{$file});
1.563     banghart 8585:             }
                   8586:         }
1.561     banghart 8587:     }
1.613     albertel 8588:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8589:     return;
                   8590: }
1.512     banghart 8591: 
1.17      www      8592: # ------------------------------------------------------------ Directory lister
                   8593: 
                   8594: sub dirlist {
1.955     raeburn  8595:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8596:     $uri=~s/^\///;
                   8597:     $uri=~s/\/$//;
1.253     stredwic 8598:     my ($udom, $uname);
1.955     raeburn  8599:     if ($getuserdir) {
1.253     stredwic 8600:         $udom = $userdomain;
                   8601:         $uname = $username;
1.955     raeburn  8602:     } else {
                   8603:         (undef,$udom,$uname)=split(/\//,$uri);
                   8604:         if(defined($userdomain)) {
                   8605:             $udom = $userdomain;
                   8606:         }
                   8607:         if(defined($username)) {
                   8608:             $uname = $username;
                   8609:         }
1.253     stredwic 8610:     }
1.955     raeburn  8611:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8612: 
1.955     raeburn  8613:     $dirRoot = $perlvar{'lonDocRoot'};
                   8614:     if (defined($getpropath)) {
                   8615:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8616:         $dirRoot =~ s/\/$//;
1.955     raeburn  8617:     } elsif (defined($getuserdir)) {
                   8618:         my $subdir=$uname.'__';
                   8619:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8620:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8621:                    ."/$udom/$subdir/$uname";
                   8622:     } elsif (defined($alternateRoot)) {
                   8623:         $dirRoot = $alternateRoot;
1.751     banghart 8624:     }
1.253     stredwic 8625: 
                   8626:     if($udom) {
                   8627:         if($uname) {
1.1135    raeburn  8628:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8629:             if ($uhome eq 'no_host') {
                   8630:                 return ([],'no_host');
                   8631:             }
1.955     raeburn  8632:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8633:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8634:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8635:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8636:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8637:             } else {
                   8638:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8639:             }
1.605     matthew  8640:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8641:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8642:                 @listing_results = split(/:/,$listing);
                   8643:             } else {
                   8644:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8645:             }
1.1135    raeburn  8646:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8647:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8648:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8649:                 return ([],$listing);
                   8650:             } else {
                   8651:                 return (\@listing_results);
1.1135    raeburn  8652:             }
1.955     raeburn  8653:         } elsif(!$alternateRoot) {
1.1136    raeburn  8654:             my (%allusers,%listerror);
1.841     albertel 8655: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8656:  	    foreach my $tryserver (keys(%servers)) {
                   8657:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8658:                                   &escape($udom),$tryserver);
                   8659:                 if ($listing eq 'unknown_cmd') {
                   8660: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8661: 				      $udom, $tryserver);
                   8662:                 } else {
                   8663:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8664:                 }
1.841     albertel 8665: 		if ($listing eq 'unknown_cmd') {
                   8666: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8667: 				      $udom, $tryserver);
                   8668: 		    @listing_results = split(/:/,$listing);
                   8669: 		} else {
                   8670: 		    @listing_results =
                   8671: 			map { &unescape($_); } split(/:/,$listing);
                   8672: 		}
1.1136    raeburn  8673:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8674:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8675:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8676:                     $listerror{$tryserver} = $listing;
                   8677:                 } else {
1.841     albertel 8678: 		    foreach my $line (@listing_results) {
                   8679: 			my ($entry) = split(/&/,$line,2);
                   8680: 			$allusers{$entry} = 1;
                   8681: 		    }
                   8682: 		}
1.253     stredwic 8683:             }
1.1136    raeburn  8684:             my @alluserslist=();
1.800     albertel 8685:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8686:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8687:             }
1.1136    raeburn  8688:             return (\@alluserslist);
1.253     stredwic 8689:         } else {
1.1136    raeburn  8690:             return ([],'missing username');
1.253     stredwic 8691:         }
1.955     raeburn  8692:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8693:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8694:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8695:         return (\@all_domains);
1.955     raeburn  8696:     } else {
1.1136    raeburn  8697:         return ([],'missing domain');
1.275     stredwic 8698:     }
                   8699: }
                   8700: 
                   8701: # --------------------------------------------- GetFileTimestamp
                   8702: # This function utilizes dirlist and returns the date stamp for
                   8703: # when it was last modified.  It will also return an error of -1
                   8704: # if an error occurs
                   8705: 
                   8706: sub GetFileTimestamp {
1.955     raeburn  8707:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8708:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8709:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8710:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8711:                                     undef,$getuserdir);
                   8712:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8713:         return -1;
                   8714:     }
                   8715:     if (ref($fileref) eq 'ARRAY') {
                   8716:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8717:         # @stats contains first the filename, then the stat output
                   8718:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8719:     } else {
                   8720:         return -1;
1.253     stredwic 8721:     }
1.26      www      8722: }
                   8723: 
1.712     albertel 8724: sub stat_file {
                   8725:     my ($uri) = @_;
1.787     albertel 8726:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8727: 
1.955     raeburn  8728:     my ($udom,$uname,$file);
1.712     albertel 8729:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8730: 	($udom,$uname,$file) =
1.811     albertel 8731: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8732: 	$file = 'userfiles/'.$file;
                   8733:     }
                   8734:     if ($uri =~ m-^/res/-) {
                   8735: 	($udom,$uname) = 
1.807     albertel 8736: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8737: 	$file = $uri;
                   8738:     }
                   8739: 
                   8740:     if (!$udom || !$uname || !$file) {
                   8741: 	# unable to handle the uri
                   8742: 	return ();
                   8743:     }
1.956     raeburn  8744:     my $getpropath;
                   8745:     if ($file =~ /^userfiles\//) {
                   8746:         $getpropath = 1;
                   8747:     }
1.1136    raeburn  8748:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8749:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8750:         return ();
                   8751:     } else {
                   8752:         if (ref($listref) eq 'ARRAY') {
                   8753:             my @stats = split('&',$listref->[0]);
                   8754: 	    shift(@stats); #filename is first
                   8755: 	    return @stats;
                   8756:         }
1.712     albertel 8757:     }
                   8758:     return ();
                   8759: }
                   8760: 
1.26      www      8761: # -------------------------------------------------------- Value of a Condition
                   8762: 
1.713     albertel 8763: # gets the value of a specific preevaluated condition
                   8764: #    stored in the string  $env{user.state.<cid>}
                   8765: # or looks up a condition reference in the bighash and if if hasn't
                   8766: # already been evaluated recurses into docondval to get the value of
                   8767: # the condition, then memoizing it to 
                   8768: #   $env{user.state.<cid>.<condition>}
1.40      www      8769: sub directcondval {
                   8770:     my $number=shift;
1.620     albertel 8771:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8772: 	&Apache::lonuserstate::evalstate();
                   8773:     }
1.713     albertel 8774:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8775: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8776:     } elsif ($number =~ /^_/) {
                   8777: 	my $sub_condition;
                   8778: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8779: 		&GDBM_READER(),0640)) {
                   8780: 	    $sub_condition=$bighash{'conditions'.$number};
                   8781: 	    untie(%bighash);
                   8782: 	}
                   8783: 	my $value = &docondval($sub_condition);
1.949     raeburn  8784: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8785: 	return $value;
                   8786:     }
1.620     albertel 8787:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8788:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8789:     } else {
                   8790:        return 2;
                   8791:     }
                   8792: }
                   8793: 
1.713     albertel 8794: # get the collection of conditions for this resource
1.26      www      8795: sub condval {
                   8796:     my $condidx=shift;
1.54      www      8797:     my $allpathcond='';
1.713     albertel 8798:     foreach my $cond (split(/\|/,$condidx)) {
                   8799: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8800: 	    $allpathcond.=
                   8801: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8802: 	}
1.191     harris41 8803:     }
1.54      www      8804:     $allpathcond=~s/\|$//;
1.713     albertel 8805:     return &docondval($allpathcond);
                   8806: }
                   8807: 
                   8808: #evaluates an expression of conditions
                   8809: sub docondval {
                   8810:     my ($allpathcond) = @_;
                   8811:     my $result=0;
                   8812:     if ($env{'request.course.id'}
                   8813: 	&& defined($allpathcond)) {
                   8814: 	my $operand='|';
                   8815: 	my @stack;
                   8816: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8817: 	    if ($chunk eq '(') {
                   8818: 		push @stack,($operand,$result);
                   8819: 	    } elsif ($chunk eq ')') {
                   8820: 		my $before=pop @stack;
                   8821: 		if (pop @stack eq '&') {
                   8822: 		    $result=$result>$before?$before:$result;
                   8823: 		} else {
                   8824: 		    $result=$result>$before?$result:$before;
                   8825: 		}
                   8826: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8827: 		$operand=$chunk;
                   8828: 	    } else {
                   8829: 		my $new=directcondval($chunk);
                   8830: 		if ($operand eq '&') {
                   8831: 		    $result=$result>$new?$new:$result;
                   8832: 		} else {
                   8833: 		    $result=$result>$new?$result:$new;
                   8834: 		}
                   8835: 	    }
                   8836: 	}
1.26      www      8837:     }
                   8838:     return $result;
1.421     albertel 8839: }
                   8840: 
                   8841: # ---------------------------------------------------- Devalidate courseresdata
                   8842: 
                   8843: sub devalidatecourseresdata {
                   8844:     my ($coursenum,$coursedomain)=@_;
                   8845:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8846:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8847: }
                   8848: 
1.763     www      8849: 
1.200     www      8850: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8851: #
                   8852: #  Parameters:
                   8853: #      $coursenum    - Number of the course.
                   8854: #      $coursedomain - Domain at which the course was created.
                   8855: #  Returns:
                   8856: #     A hash of the course parameters along (I think) with timestamps
                   8857: #     and version info.
1.877     foxr     8858: 
1.624     albertel 8859: sub get_courseresdata {
                   8860:     my ($coursenum,$coursedomain)=@_;
1.200     www      8861:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8862:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8863:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8864:     my %dumpreply;
1.417     albertel 8865:     unless (defined($cached)) {
1.624     albertel 8866: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8867: 	$result=\%dumpreply;
1.251     albertel 8868: 	my ($tmp) = keys(%dumpreply);
                   8869: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8870: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8871: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8872: 	    return $tmp;
1.416     albertel 8873: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8874: 	    $result=undef;
1.599     albertel 8875: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8876: 	}
                   8877:     }
1.624     albertel 8878:     return $result;
                   8879: }
                   8880: 
1.633     albertel 8881: sub devalidateuserresdata {
                   8882:     my ($uname,$udom)=@_;
                   8883:     my $hashid="$udom:$uname";
                   8884:     &devalidate_cache_new('userres',$hashid);
                   8885: }
                   8886: 
1.624     albertel 8887: sub get_userresdata {
                   8888:     my ($uname,$udom)=@_;
                   8889:     #most student don\'t have any data set, check if there is some data
                   8890:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8891: 
                   8892:     my $hashid="$udom:$uname";
                   8893:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8894:     if (!defined($cached)) {
                   8895: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8896: 	$result=\%resourcedata;
                   8897: 	&do_cache_new('userres',$hashid,$result,600);
                   8898:     }
                   8899:     my ($tmp)=keys(%$result);
                   8900:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8901: 	return $result;
                   8902:     }
                   8903:     #error 2 occurs when the .db doesn't exist
                   8904:     if ($tmp!~/error: 2 /) {
1.672     albertel 8905: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8906: 		 " Trying to get resource data for ".
                   8907: 		 $uname." at ".$udom.": ".
                   8908: 		 $tmp."</font>");
                   8909:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8910: 	#&EXT_cache_set($udom,$uname);
                   8911: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8912: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8913:     }
                   8914:     return $tmp;
                   8915: }
1.879     foxr     8916: #----------------------------------------------- resdata - return resource data
                   8917: #  Purpose:
                   8918: #    Return resource data for either users or for a course.
                   8919: #  Parameters:
                   8920: #     $name      - Course/user name.
                   8921: #     $domain    - Name of the domain the user/course is registered on.
                   8922: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8923: #     @which     - Array of names of resources desired.
                   8924: #  Returns:
                   8925: #     The value of the first reasource in @which that is found in the
                   8926: #     resource hash.
                   8927: #  Exceptional Conditions:
                   8928: #     If the $type passed in is not valid (not the string 'course' or 
                   8929: #     'user', an undefined  reference is returned.
                   8930: #     If none of the resources are found, an undef is returned
1.624     albertel 8931: sub resdata {
                   8932:     my ($name,$domain,$type,@which)=@_;
                   8933:     my $result;
                   8934:     if ($type eq 'course') {
                   8935: 	$result=&get_courseresdata($name,$domain);
                   8936:     } elsif ($type eq 'user') {
                   8937: 	$result=&get_userresdata($name,$domain);
                   8938:     }
                   8939:     if (!ref($result)) { return $result; }    
1.251     albertel 8940:     foreach my $item (@which) {
1.927     albertel 8941: 	if (defined($result->{$item->[0]})) {
                   8942: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8943: 	}
1.250     albertel 8944:     }
1.291     albertel 8945:     return undef;
1.200     www      8946: }
                   8947: 
1.379     matthew  8948: #
                   8949: # EXT resource caching routines
                   8950: #
                   8951: 
                   8952: sub clear_EXT_cache_status {
1.383     albertel 8953:     &delenv('cache.EXT.');
1.379     matthew  8954: }
                   8955: 
                   8956: sub EXT_cache_status {
                   8957:     my ($target_domain,$target_user) = @_;
1.383     albertel 8958:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8959:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8960:         # We know already the user has no data
                   8961:         return 1;
                   8962:     } else {
                   8963:         return 0;
                   8964:     }
                   8965: }
                   8966: 
                   8967: sub EXT_cache_set {
                   8968:     my ($target_domain,$target_user) = @_;
1.383     albertel 8969:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8970:     #&appenv({$cachename => time});
1.379     matthew  8971: }
                   8972: 
1.28      www      8973: # --------------------------------------------------------- Value of a Variable
1.58      www      8974: sub EXT {
1.715     albertel 8975: 
1.395     albertel 8976:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8977:     unless ($varname) { return ''; }
1.218     albertel 8978:     #get real user name/domain, courseid and symb
                   8979:     my $courseid;
1.359     albertel 8980:     my $publicuser;
1.427     www      8981:     if ($symbparm) {
                   8982: 	$symbparm=&get_symb_from_alias($symbparm);
                   8983:     }
1.218     albertel 8984:     if (!($uname && $udom)) {
1.790     albertel 8985:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8986:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8987:     } else {
1.620     albertel 8988: 	$courseid=$env{'request.course.id'};
1.218     albertel 8989:     }
1.48      www      8990:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8991:     my $rest;
1.320     albertel 8992:     if (defined($therest[0])) {
1.48      www      8993:        $rest=join('.',@therest);
                   8994:     } else {
                   8995:        $rest='';
                   8996:     }
1.320     albertel 8997: 
1.57      www      8998:     my $qualifierrest=$qualifier;
                   8999:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9000:     my $spacequalifierrest=$space;
                   9001:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9002:     if ($realm eq 'user') {
1.48      www      9003: # --------------------------------------------------------------- user.resource
                   9004: 	if ($space eq 'resource') {
1.651     albertel 9005: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9006: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9007: 		 &&
1.744     albertel 9008: 		 ($symbparm eq &symbread()) ) {	
                   9009: 		# if we are in the middle of processing the resource the
                   9010: 		# get the value we are planning on committing
                   9011:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9012:                     return $Apache::lonhomework::results{$qualifierrest};
                   9013:                 } else {
                   9014:                     return $Apache::lonhomework::history{$qualifierrest};
                   9015:                 }
1.335     albertel 9016: 	    } else {
1.359     albertel 9017: 		my %restored;
1.620     albertel 9018: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9019: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9020: 		} else {
                   9021: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9022: 		}
1.335     albertel 9023: 		return $restored{$qualifierrest};
                   9024: 	    }
1.48      www      9025: # ----------------------------------------------------------------- user.access
                   9026:         } elsif ($space eq 'access') {
1.218     albertel 9027: 	    # FIXME - not supporting calls for a specific user
1.48      www      9028:             return &allowed($qualifier,$rest);
                   9029: # ------------------------------------------ user.preferences, user.environment
                   9030:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9031: 	    if (($uname eq $env{'user.name'}) &&
                   9032: 		($udom eq $env{'user.domain'})) {
                   9033: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9034: 	    } else {
1.359     albertel 9035: 		my %returnhash;
                   9036: 		if (!$publicuser) {
                   9037: 		    %returnhash=&userenvironment($udom,$uname,
                   9038: 						 $qualifierrest);
                   9039: 		}
1.218     albertel 9040: 		return $returnhash{$qualifierrest};
                   9041: 	    }
1.48      www      9042: # ----------------------------------------------------------------- user.course
                   9043:         } elsif ($space eq 'course') {
1.218     albertel 9044: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9045:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9046: # ------------------------------------------------------------------- user.role
                   9047:         } elsif ($space eq 'role') {
1.218     albertel 9048: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9049:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9050:             if ($qualifier eq 'value') {
                   9051: 		return $role;
                   9052:             } elsif ($qualifier eq 'extent') {
                   9053:                 return $where;
                   9054:             }
                   9055: # ----------------------------------------------------------------- user.domain
                   9056:         } elsif ($space eq 'domain') {
1.218     albertel 9057:             return $udom;
1.48      www      9058: # ------------------------------------------------------------------- user.name
                   9059:         } elsif ($space eq 'name') {
1.218     albertel 9060:             return $uname;
1.48      www      9061: # ---------------------------------------------------- Any other user namespace
1.29      www      9062:         } else {
1.359     albertel 9063: 	    my %reply;
                   9064: 	    if (!$publicuser) {
                   9065: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9066: 	    }
                   9067: 	    return $reply{$qualifierrest};
1.48      www      9068:         }
1.236     www      9069:     } elsif ($realm eq 'query') {
                   9070: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9071:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9072: 						[$spacequalifierrest]);
1.620     albertel 9073: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9074:    } elsif ($realm eq 'request') {
1.48      www      9075: # ------------------------------------------------------------- request.browser
                   9076:         if ($space eq 'browser') {
1.1145    bisitz   9077:             return $env{'browser.'.$qualifier};
1.57      www      9078: # ------------------------------------------------------------ request.filename
                   9079:         } else {
1.620     albertel 9080:             return $env{'request.'.$spacequalifierrest};
1.29      www      9081:         }
1.28      www      9082:     } elsif ($realm eq 'course') {
1.48      www      9083: # ---------------------------------------------------------- course.description
1.620     albertel 9084:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9085:     } elsif ($realm eq 'resource') {
1.165     www      9086: 
1.620     albertel 9087: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9088: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9089: 	}
1.693     albertel 9090: 
                   9091: 	if ($space eq 'title') {
                   9092: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9093: 	    return &gettitle($symbparm);
                   9094: 	}
                   9095: 	
                   9096: 	if ($space eq 'map') {
                   9097: 	    my ($map) = &decode_symb($symbparm);
                   9098: 	    return &symbread($map);
                   9099: 	}
1.905     albertel 9100: 	if ($space eq 'filename') {
                   9101: 	    if ($symbparm) {
                   9102: 		return &clutter((&decode_symb($symbparm))[2]);
                   9103: 	    }
                   9104: 	    return &hreflocation('',$env{'request.filename'});
                   9105: 	}
1.693     albertel 9106: 
                   9107: 	my ($section, $group, @groups);
1.593     albertel 9108: 	my ($courselevelm,$courselevel);
1.539     albertel 9109: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9110: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9111: 
1.218     albertel 9112: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9113: 
1.60      www      9114: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9115: 	    my $symbp=$symbparm;
1.735     albertel 9116: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9117: 
                   9118: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9119: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9120: 
1.620     albertel 9121: 	    if (($env{'user.name'} eq $uname) &&
                   9122: 		($env{'user.domain'} eq $udom)) {
                   9123: 		$section=$env{'request.course.sec'};
1.733     raeburn  9124:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9125:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9126: 	    } else {
1.539     albertel 9127: 		if (! defined($usection)) {
1.551     albertel 9128: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9129: 		} else {
                   9130: 		    $section = $usection;
                   9131: 		}
1.733     raeburn  9132:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9133: 	    }
                   9134: 
                   9135: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9136: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9137: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9138: 
1.593     albertel 9139: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9140: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9141: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9142: 
1.60      www      9143: # ----------------------------------------------------------- first, check user
1.624     albertel 9144: 
                   9145: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9146: 				       ([$courselevelr,'resource'],
                   9147: 					[$courselevelm,'map'     ],
                   9148: 					[$courselevel, 'course'  ]));
1.931     albertel 9149: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9150: 
1.594     albertel 9151: # ------------------------------------------------ second, check some of course
1.684     raeburn  9152:             my $coursereply;
1.691     raeburn  9153:             if (@groups > 0) {
                   9154:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9155:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9156:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9157:             }
1.96      www      9158: 
1.684     raeburn  9159: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9160: 				  $env{'course.'.$courseid.'.domain'},
                   9161: 				  'course',
                   9162: 				  ([$seclevelr,   'resource'],
                   9163: 				   [$seclevelm,   'map'     ],
                   9164: 				   [$seclevel,    'course'  ],
                   9165: 				   [$courselevelr,'resource']));
                   9166: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9167: 
1.60      www      9168: # ------------------------------------------------------ third, check map parms
1.218     albertel 9169: 	    my %parmhash=();
                   9170: 	    my $thisparm='';
                   9171: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9172: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9173: 		    &GDBM_READER(),0640)) {
1.218     albertel 9174: 		$thisparm=$parmhash{$symbparm};
                   9175: 		untie(%parmhash);
                   9176: 	    }
1.927     albertel 9177: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9178: 	}
1.594     albertel 9179: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9180: 
1.218     albertel 9181: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9182: 	my $filename;
                   9183: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9184: 	if ($symbparm) {
1.409     www      9185: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9186: 	} else {
1.620     albertel 9187: 	    $filename=$env{'request.filename'};
1.282     albertel 9188: 	}
                   9189: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9190: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9191: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9192: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9193: 
1.927     albertel 9194: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9195: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9196: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9197: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9198: 				     $env{'course.'.$courseid.'.domain'},
                   9199: 				     'course',
1.927     albertel 9200: 				     ([$courselevelm,'map'   ],
                   9201: 				      [$courselevel, 'course']));
                   9202: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9203: 	}
1.145     www      9204: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9205: 	unless ($space eq '0') {
1.336     albertel 9206: 	    my @parts=split(/_/,$space);
                   9207: 	    my $id=pop(@parts);
                   9208: 	    my $part=join('_',@parts);
                   9209: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9210: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9211: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9212: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9213: 	}
1.395     albertel 9214: 	if ($recurse) { return undef; }
                   9215: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9216: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9217: # ---------------------------------------------------- Any other user namespace
                   9218:     } elsif ($realm eq 'environment') {
                   9219: # ----------------------------------------------------------------- environment
1.620     albertel 9220: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9221: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9222: 	} else {
1.770     albertel 9223: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9224: 		return '';
                   9225: 	    }
1.219     albertel 9226: 	    my %returnhash=&userenvironment($udom,$uname,
                   9227: 					    $spacequalifierrest);
                   9228: 	    return $returnhash{$spacequalifierrest};
                   9229: 	}
1.28      www      9230:     } elsif ($realm eq 'system') {
1.48      www      9231: # ----------------------------------------------------------------- system.time
                   9232: 	if ($space eq 'time') {
                   9233: 	    return time;
                   9234:         }
1.696     albertel 9235:     } elsif ($realm eq 'server') {
                   9236: # ----------------------------------------------------------------- system.time
                   9237: 	if ($space eq 'name') {
                   9238: 	    return $ENV{'SERVER_NAME'};
                   9239:         }
1.28      www      9240:     }
1.48      www      9241:     return '';
1.61      www      9242: }
                   9243: 
1.927     albertel 9244: sub get_reply {
                   9245:     my ($reply_value) = @_;
1.940     raeburn  9246:     if (ref($reply_value) eq 'ARRAY') {
                   9247:         if (wantarray) {
                   9248: 	    return @$reply_value;
                   9249:         }
                   9250:         return $reply_value->[0];
                   9251:     } else {
                   9252:         return $reply_value;
1.927     albertel 9253:     }
                   9254: }
                   9255: 
1.691     raeburn  9256: sub check_group_parms {
                   9257:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9258:     my @groupitems = ();
                   9259:     my $resultitem;
1.927     albertel 9260:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9261:     foreach my $group (@{$groups}) {
                   9262:         foreach my $level (@levels) {
1.927     albertel 9263:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9264:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9265:         }
                   9266:     }
                   9267:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9268:                             $env{'course.'.$courseid.'.domain'},
                   9269:                                      'course',@groupitems);
                   9270:     return $coursereply;
                   9271: }
                   9272: 
                   9273: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9274:     my ($courseid,@groups) = @_;
                   9275:     @groups = sort(@groups);
1.691     raeburn  9276:     return @groups;
                   9277: }
                   9278: 
1.395     albertel 9279: sub packages_tab_default {
                   9280:     my ($uri,$varname)=@_;
                   9281:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9282: 
                   9283:     my (@extension,@specifics,$do_default);
                   9284:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9285: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9286: 	if ($pack_type eq 'default') {
                   9287: 	    $do_default=1;
                   9288: 	} elsif ($pack_type eq 'extension') {
                   9289: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9290: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9291: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9292: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9293: 	}
                   9294:     }
                   9295:     # first look for a package that matches the requested part id
                   9296:     foreach my $package (@specifics) {
                   9297: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9298: 	next if ($pack_part ne $part);
                   9299: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9300: 	    return $packagetab{"$pack_type&$name&default"};
                   9301: 	}
                   9302:     }
                   9303:     # look for any possible matching non extension_ package
                   9304:     foreach my $package (@specifics) {
                   9305: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9306: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9307: 	    return $packagetab{"$pack_type&$name&default"};
                   9308: 	}
1.585     albertel 9309: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9310: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9311: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9312: 	}
                   9313:     }
1.738     albertel 9314:     # look for any posible extension_ match
                   9315:     foreach my $package (@extension) {
                   9316: 	my ($package,$pack_type)=@{$package};
                   9317: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9318: 	    return $packagetab{"$pack_type&$name&default"};
                   9319: 	}
                   9320: 	if (defined($packagetab{$package."&$name&default"})) {
                   9321: 	    return $packagetab{$package."&$name&default"};
                   9322: 	}
                   9323:     }
                   9324:     # look for a global default setting
                   9325:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9326: 	return $packagetab{"default&$name&default"};
                   9327:     }
1.395     albertel 9328:     return undef;
                   9329: }
                   9330: 
1.334     albertel 9331: sub add_prefix_and_part {
                   9332:     my ($prefix,$part)=@_;
                   9333:     my $keyroot;
                   9334:     if (defined($prefix) && $prefix !~ /^__/) {
                   9335: 	# prefix that has a part already
                   9336: 	$keyroot=$prefix;
                   9337:     } elsif (defined($prefix)) {
                   9338: 	# prefix that is missing a part
                   9339: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9340:     } else {
                   9341: 	# no prefix at all
                   9342: 	if (defined($part)) { $keyroot='_'.$part; }
                   9343:     }
                   9344:     return $keyroot;
                   9345: }
                   9346: 
1.71      www      9347: # ---------------------------------------------------------------- Get metadata
                   9348: 
1.599     albertel 9349: my %metaentry;
1.1070    www      9350: my %importedpartids;
1.71      www      9351: sub metadata {
1.176     www      9352:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9353:     $uri=&declutter($uri);
1.288     albertel 9354:     # if it is a non metadata possible uri return quickly
1.529     albertel 9355:     if (($uri eq '') || 
                   9356: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9357: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9358:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9359: 	return undef;
                   9360:     }
1.1140    www      9361:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9362: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9363: 	return undef;
1.288     albertel 9364:     }
1.73      www      9365:     my $filename=$uri;
                   9366:     $uri=~s/\.meta$//;
1.172     www      9367: #
                   9368: # Is the metadata already cached?
1.177     www      9369: # Look at timestamp of caching
1.172     www      9370: # Everything is cached by the main uri, libraries are never directly cached
                   9371: #
1.428     albertel 9372:     if (!defined($liburi)) {
1.599     albertel 9373: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9374: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9375:     }
                   9376:     {
1.1069    www      9377: # Imported parts would go here
1.1070    www      9378:         my %importedids=();
                   9379:         my @origfileimportpartids=();
1.1069    www      9380:         my $importedparts=0;
1.172     www      9381: #
                   9382: # Is this a recursive call for a library?
                   9383: #
1.599     albertel 9384: #	if (! exists($metacache{$uri})) {
                   9385: #	    $metacache{$uri}={};
                   9386: #	}
1.924     albertel 9387: 	my $cachetime = 60*60;
1.171     www      9388:         if ($liburi) {
                   9389: 	    $liburi=&declutter($liburi);
                   9390:             $filename=$liburi;
1.401     bowersj2 9391:         } else {
1.599     albertel 9392: 	    &devalidate_cache_new('meta',$uri);
                   9393: 	    undef(%metaentry);
1.401     bowersj2 9394: 	}
1.140     www      9395:         my %metathesekeys=();
1.73      www      9396:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9397: 	my $metastring;
1.1140    www      9398: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9399: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9400: 	    $metastring = 
1.929     albertel 9401: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9402: 					  ('grade_target' => 'meta'));
                   9403: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9404: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9405:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9406: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9407: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9408: 	    $metastring=&getfile($file);
1.489     albertel 9409: 	}
1.208     albertel 9410:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9411:         my $token;
1.140     www      9412:         undef %metathesekeys;
1.71      www      9413:         while ($token=$parser->get_token) {
1.339     albertel 9414: 	    if ($token->[0] eq 'S') {
                   9415: 		if (defined($token->[2]->{'package'})) {
1.172     www      9416: #
                   9417: # This is a package - get package info
                   9418: #
1.339     albertel 9419: 		    my $package=$token->[2]->{'package'};
                   9420: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9421: 		    if (defined($token->[2]->{'id'})) { 
                   9422: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9423: 		    }
1.599     albertel 9424: 		    if ($metaentry{':packages'}) {
                   9425: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9426: 		    } else {
1.599     albertel 9427: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9428: 		    }
1.736     albertel 9429: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9430: 			my $part=$keyroot;
                   9431: 			$part=~s/^\_//;
1.736     albertel 9432: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9433: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9434: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9435: 			    # ignore package.tab specified default values
                   9436:                             # here &package_tab_default() will fetch those
                   9437: 			    if ($subp eq 'default') { next; }
1.736     albertel 9438: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9439: 			    my $unikey;
                   9440: 			    if ($pack =~ /_0$/) {
                   9441: 				$unikey='parameter_0_'.$name;
                   9442: 				$part=0;
                   9443: 			    } else {
                   9444: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9445: 			    }
1.339     albertel 9446: 			    if ($subp eq 'display') {
                   9447: 				$value.=' [Part: '.$part.']';
                   9448: 			    }
1.599     albertel 9449: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9450: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9451: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9452: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9453: 			    }
1.599     albertel 9454: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9455: 				$metaentry{':'.$unikey}=
                   9456: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9457: 			    }
1.339     albertel 9458: 			}
                   9459: 		    }
                   9460: 		} else {
1.172     www      9461: #
                   9462: # This is not a package - some other kind of start tag
1.339     albertel 9463: #
                   9464: 		    my $entry=$token->[1];
1.1068    www      9465: 		    my $unikey='';
1.175     www      9466: 
1.339     albertel 9467: 		    if ($entry eq 'import') {
1.175     www      9468: #
                   9469: # Importing a library here
1.339     albertel 9470: #
1.1067    www      9471:                         my $location=$parser->get_text('/import');
                   9472:                         my $dir=$filename;
                   9473:                         $dir=~s|[^/]*$||;
                   9474:                         $location=&filelocation($dir,$location);
1.1069    www      9475:                        
1.1068    www      9476:                         my $importmode=$token->[2]->{'importmode'};
                   9477:                         if ($importmode eq 'problem') {
1.1069    www      9478: # Import as problem/response
1.1068    www      9479:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9480:                         } elsif ($importmode eq 'part') {
                   9481: # Import as part(s)
1.1069    www      9482:                            $importedparts=1;
                   9483: # We need to get the original file and the imported file to get the part order correct
                   9484: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9485: # Load and inspect original file
1.1070    www      9486:                            if ($#origfileimportpartids<0) {
                   9487:                               undef(%importedpartids);
                   9488:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9489:                               my $origfile=&getfile($origfilelocation);
                   9490:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9491:                            }
                   9492: 
1.1069    www      9493: # Load and inspect imported file
                   9494:                            my $impfile=&getfile($location);
                   9495:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9496:                            if ($#impfilepartids>=0) {
                   9497: # This problem had parts
1.1070    www      9498:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9499:                            } else {
                   9500: # Importing by turning a single problem into a problem part
                   9501: # It gets the import-tags ID as part-ID
                   9502:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9503:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9504:                            }
1.1068    www      9505:                         } else {
                   9506: # Normal import
                   9507:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9508:                            if (defined($token->[2]->{'id'})) {
                   9509:                               $unikey.='_'.$token->[2]->{'id'};
                   9510:                            }
1.1067    www      9511:                         }
                   9512: 
1.339     albertel 9513: 			if ($depthcount<20) {
1.736     albertel 9514: 			    my $metadata = 
                   9515: 				&metadata($uri,'keys', $location,$unikey,
                   9516: 					  $depthcount+1);
                   9517: 			    foreach my $meta (split(',',$metadata)) {
                   9518: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9519: 				$metathesekeys{$meta}=1;
1.339     albertel 9520: 			    }
1.1068    www      9521: 			
                   9522:                         }
1.1067    www      9523: 		    } else {
                   9524: #
                   9525: # Not importing, some other kind of non-package, non-library start tag
                   9526: # 
                   9527:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9528:                         if (defined($token->[2]->{'id'})) {
                   9529:                             $unikey.='_'.$token->[2]->{'id'};
                   9530:                         }
1.339     albertel 9531: 			if (defined($token->[2]->{'name'})) { 
                   9532: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9533: 			}
                   9534: 			$metathesekeys{$unikey}=1;
1.736     albertel 9535: 			foreach my $param (@{$token->[3]}) {
                   9536: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9537: 				$token->[2]->{$param};
1.339     albertel 9538: 			}
                   9539: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9540: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9541: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9542: 		 # only ws inside the tag, and not in default, so use default
                   9543: 		 # as value
1.599     albertel 9544: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9545: 			} elsif ( $internaltext =~ /\S/ ) {
                   9546: 		  # something interesting inside the tag
                   9547: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9548: 			} else {
1.908     albertel 9549: 		  # no interesting values, don't set a default
1.339     albertel 9550: 			}
1.172     www      9551: # end of not-a-package not-a-library import
1.339     albertel 9552: 		    }
1.172     www      9553: # end of not-a-package start tag
1.339     albertel 9554: 		}
1.172     www      9555: # the next is the end of "start tag"
1.339     albertel 9556: 	    }
                   9557: 	}
1.483     albertel 9558: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9559: 	$extension = lc($extension);
                   9560: 	if ($extension eq 'htm') { $extension='html'; }
                   9561: 
1.737     albertel 9562: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9563: 	    #no specific packages #how's our extension
                   9564: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9565: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9566: 					 \%metathesekeys);
                   9567: 	}
1.883     albertel 9568: 
                   9569: 	if (!exists($metaentry{':packages'})
                   9570: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9571: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9572: 		#no specific packages well let's get default then
                   9573: 		if ($key!~/^default&/) { next; }
1.488     albertel 9574: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9575: 					     \%metathesekeys);
                   9576: 	    }
                   9577: 	}
1.338     www      9578: # are there custom rights to evaluate
1.599     albertel 9579: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9580: 
1.338     www      9581:     #
                   9582:     # Importing a rights file here
1.339     albertel 9583:     #
                   9584: 	    unless ($depthcount) {
1.599     albertel 9585: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9586: 		my $dir=$filename;
                   9587: 		$dir=~s|[^/]*$||;
                   9588: 		$location=&filelocation($dir,$location);
1.736     albertel 9589: 		my $rights_metadata =
                   9590: 		    &metadata($uri,'keys',$location,'_rights',
                   9591: 			      $depthcount+1);
                   9592: 		foreach my $rights (split(',',$rights_metadata)) {
                   9593: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9594: 		    $metathesekeys{$rights}=1;
1.339     albertel 9595: 		}
                   9596: 	    }
                   9597: 	}
1.737     albertel 9598: 	# uniqifiy package listing
                   9599: 	my %seen;
                   9600: 	my @uniq_packages =
                   9601: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9602: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9603: 
1.1070    www      9604:         if ($importedparts) {
                   9605: # We had imported parts and need to rebuild partorder
                   9606:            $metaentry{':partorder'}='';
                   9607:            $metathesekeys{'partorder'}=1;
                   9608:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9609:                if ($origfileimportpartids[$index] eq 'part') {
                   9610: # original part, part of the problem
                   9611:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9612:                } else {
                   9613: # we have imported parts at this position
                   9614:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9615:                }
                   9616:            }
                   9617:            $metaentry{':partorder'}=~s/^\,//;
                   9618:         }
                   9619: 
1.737     albertel 9620: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9621: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9622: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9623: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9624: # this is the end of "was not already recently cached
1.71      www      9625:     }
1.599     albertel 9626:     return $metaentry{':'.$what};
1.261     albertel 9627: }
                   9628: 
1.488     albertel 9629: sub metadata_create_package_def {
1.483     albertel 9630:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9631:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9632:     if ($subp eq 'default') { next; }
                   9633:     
1.599     albertel 9634:     if (defined($metaentry{':packages'})) {
                   9635: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9636:     } else {
1.599     albertel 9637: 	$metaentry{':packages'}=$package;
1.483     albertel 9638:     }
                   9639:     my $value=$packagetab{$key};
                   9640:     my $unikey;
                   9641:     $unikey='parameter_0_'.$name;
1.599     albertel 9642:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9643:     $$metathesekeys{$unikey}=1;
1.599     albertel 9644:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9645: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9646:     }
1.599     albertel 9647:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9648: 	$metaentry{':'.$unikey}=
                   9649: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9650:     }
                   9651: }
                   9652: 
1.261     albertel 9653: sub metadata_generate_part0 {
                   9654:     my ($metadata,$metacache,$uri) = @_;
                   9655:     my %allnames;
1.737     albertel 9656:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9657: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9658: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9659: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9660: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9661: 	    $allnames{$name}=$part;
                   9662: 	  }
                   9663: 	}
                   9664:     }
                   9665:     foreach my $name (keys(%allnames)) {
                   9666:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9667:       my $key=":parameter_0_$name";
1.261     albertel 9668:       $$metacache{"$key.part"}='0';
                   9669:       $$metacache{"$key.name"}=$name;
1.428     albertel 9670:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9671: 					   $allnames{$name}.'_'.$name.
                   9672: 					   '.type'};
1.428     albertel 9673:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9674: 			     '.display'};
1.644     www      9675:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9676:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9677:       $$metacache{"$key.display"}=$olddis;
                   9678:     }
1.71      www      9679: }
                   9680: 
1.764     albertel 9681: # ------------------------------------------------------ Devalidate title cache
                   9682: 
                   9683: sub devalidate_title_cache {
                   9684:     my ($url)=@_;
                   9685:     if (!$env{'request.course.id'}) { return; }
                   9686:     my $symb=&symbread($url);
                   9687:     if (!$symb) { return; }
                   9688:     my $key=$env{'request.course.id'}."\0".$symb;
                   9689:     &devalidate_cache_new('title',$key);
                   9690: }
                   9691: 
1.1014    droeschl 9692: # ------------------------------------------------- Get the title of a course
                   9693: 
                   9694: sub current_course_title {
                   9695:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9696: }
1.301     www      9697: # ------------------------------------------------- Get the title of a resource
                   9698: 
                   9699: sub gettitle {
                   9700:     my $urlsymb=shift;
                   9701:     my $symb=&symbread($urlsymb);
1.534     albertel 9702:     if ($symb) {
1.620     albertel 9703: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9704: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9705: 	if (defined($cached)) { 
                   9706: 	    return $result;
                   9707: 	}
1.534     albertel 9708: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9709: 	my $title='';
1.907     albertel 9710: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9711: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9712: 	} else {
                   9713: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9714: 		    &GDBM_READER(),0640)) {
                   9715: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9716: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9717: 		untie(%bighash);
                   9718: 	    }
1.534     albertel 9719: 	}
                   9720: 	$title=~s/\&colon\;/\:/gs;
                   9721: 	if ($title) {
1.1159    www      9722: # Remember both $symb and $title for dynamic metadata
                   9723:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9724:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9725: # Cache this title and then return it
1.599     albertel 9726: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9727: 	}
                   9728: 	$urlsymb=$url;
                   9729:     }
                   9730:     my $title=&metadata($urlsymb,'title');
                   9731:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9732:     return $title;
1.301     www      9733: }
1.613     albertel 9734: 
1.614     albertel 9735: sub get_slot {
                   9736:     my ($which,$cnum,$cdom)=@_;
                   9737:     if (!$cnum || !$cdom) {
1.790     albertel 9738: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9739: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9740: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9741:     }
1.703     albertel 9742:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9743:     my %slotinfo;
                   9744:     if (exists($remembered{$key})) {
                   9745: 	$slotinfo{$which} = $remembered{$key};
                   9746:     } else {
                   9747: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9748: 	&Apache::lonhomework::showhash(%slotinfo);
                   9749: 	my ($tmp)=keys(%slotinfo);
                   9750: 	if ($tmp=~/^error:/) { return (); }
                   9751: 	$remembered{$key} = $slotinfo{$which};
                   9752:     }
1.616     albertel 9753:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9754: 	return %{$slotinfo{$which}};
                   9755:     }
                   9756:     return $slotinfo{$which};
1.614     albertel 9757: }
1.1150    raeburn  9758: 
                   9759: sub get_reservable_slots {
                   9760:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9761:     my $now = time;
                   9762:     my $reservable_info;
                   9763:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9764:     if (exists($remembered{$key})) {
                   9765:         $reservable_info = $remembered{$key};
                   9766:     } else {
                   9767:         my %resv;
                   9768:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9769:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9770:         $reservable_info = \%resv;
                   9771:         $remembered{$key} = $reservable_info;
                   9772:     }
                   9773:     return $reservable_info;
                   9774: }
                   9775: 
                   9776: sub get_course_slots {
                   9777:     my ($cnum,$cdom) = @_;
                   9778:     my $hashid=$cnum.':'.$cdom;
                   9779:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9780:     if (defined($cached)) {
                   9781:         if (ref($result) eq 'HASH') {
                   9782:             return %{$result};
                   9783:         }
                   9784:     } else {
                   9785:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9786:         my ($tmp) = keys(%slots);
                   9787:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9788:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9789:             return %slots;
                   9790:         }
                   9791:     }
                   9792:     return;
                   9793: }
                   9794: 
                   9795: sub devalidate_slots_cache {
                   9796:     my ($cnum,$cdom)=@_;
                   9797:     my $hashid=$cnum.':'.$cdom;
                   9798:     &devalidate_cache_new('allslots',$hashid);
                   9799: }
                   9800: 
1.31      www      9801: # ------------------------------------------------- Update symbolic store links
                   9802: 
                   9803: sub symblist {
                   9804:     my ($mapname,%newhash)=@_;
1.438     www      9805:     $mapname=&deversion(&declutter($mapname));
1.31      www      9806:     my %hash;
1.620     albertel 9807:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9808:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9809:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9810: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9811: 		next if ($url eq 'last_known'
                   9812: 			 && $env{'form.no_update_last_known'});
                   9813: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9814: 						    $newhash{$url}->[1],
                   9815: 						    $newhash{$url}->[0]);
1.191     harris41 9816:             }
1.31      www      9817:             if (untie(%hash)) {
                   9818: 		return 'ok';
                   9819:             }
                   9820:         }
                   9821:     }
                   9822:     return 'error';
1.212     www      9823: }
                   9824: 
                   9825: # --------------------------------------------------------------- Verify a symb
                   9826: 
                   9827: sub symbverify {
1.510     www      9828:     my ($symb,$thisurl)=@_;
                   9829:     my $thisfn=$thisurl;
1.439     www      9830:     $thisfn=&declutter($thisfn);
1.215     www      9831: # direct jump to resource in page or to a sequence - will construct own symbs
                   9832:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9833: # check URL part
1.409     www      9834:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9835: 
1.431     www      9836:     unless ($url eq $thisfn) { return 0; }
1.213     www      9837: 
1.216     www      9838:     $symb=&symbclean($symb);
1.510     www      9839:     $thisurl=&deversion($thisurl);
1.439     www      9840:     $thisfn=&deversion($thisfn);
1.213     www      9841: 
                   9842:     my %bighash;
                   9843:     my $okay=0;
1.431     www      9844: 
1.620     albertel 9845:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9846:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9847:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9848:             $thisurl =~ s/\?.+$//;
                   9849:         }
1.510     www      9850:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9851:         unless ($ids) {
                   9852:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9853:             $ids=$bighash{$idkey};
1.216     www      9854:         }
                   9855:         if ($ids) {
                   9856: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9857: 	    foreach my $id (split(/\,/,$ids)) {
                   9858: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9859:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9860:                    $symb =~ s/\?.+$//;
                   9861:                }
1.216     www      9862:                if (
                   9863:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9864:    eq $symb) { 
1.620     albertel 9865: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9866: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9867:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9868: 		       $okay=1; 
                   9869: 		   }
                   9870: 	       }
1.216     www      9871: 	   }
                   9872:         }
1.213     www      9873: 	untie(%bighash);
                   9874:     }
                   9875:     return $okay;
1.31      www      9876: }
                   9877: 
1.210     www      9878: # --------------------------------------------------------------- Clean-up symb
                   9879: 
                   9880: sub symbclean {
                   9881:     my $symb=shift;
1.568     albertel 9882:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9883: # remove version from map
                   9884:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9885: 
1.210     www      9886: # remove version from URL
                   9887:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9888: 
1.507     www      9889: # remove wrapper
                   9890: 
1.510     www      9891:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9892:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9893:     return $symb;
1.409     www      9894: }
                   9895: 
                   9896: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9897: 
                   9898: sub encode_symb {
                   9899:     my ($map,$resid,$url)=@_;
                   9900:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9901: }
1.409     www      9902: 
                   9903: sub decode_symb {
1.568     albertel 9904:     my $symb=shift;
                   9905:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9906:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9907:     return (&fixversion($map),$resid,&fixversion($url));
                   9908: }
                   9909: 
                   9910: sub fixversion {
                   9911:     my $fn=shift;
1.609     banghart 9912:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9913:     my %bighash;
                   9914:     my $uri=&clutter($fn);
1.620     albertel 9915:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9916: # is this cached?
1.599     albertel 9917:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9918:     if (defined($cached)) { return $result; }
                   9919: # unfortunately not cached, or expired
1.620     albertel 9920:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9921: 	    &GDBM_READER(),0640)) {
                   9922:  	if ($bighash{'version_'.$uri}) {
                   9923:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9924:  	    unless (($version eq 'mostrecent') || 
                   9925: 		    ($version==&getversion($uri))) {
1.440     www      9926:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9927:  	    }
                   9928:  	}
                   9929:  	untie %bighash;
1.413     www      9930:     }
1.599     albertel 9931:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9932: }
                   9933: 
                   9934: sub deversion {
                   9935:     my $url=shift;
                   9936:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9937:     return $url;
1.210     www      9938: }
                   9939: 
1.31      www      9940: # ------------------------------------------------------ Return symb list entry
                   9941: 
                   9942: sub symbread {
1.249     www      9943:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9944:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9945:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9946: # no filename provided? try from environment
1.44      www      9947:     unless ($thisfn) {
1.620     albertel 9948:         if ($env{'request.symb'}) {
                   9949: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9950: 	}
1.620     albertel 9951: 	$thisfn=$env{'request.filename'};
1.44      www      9952:     }
1.569     albertel 9953:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9954: # is that filename actually a symb? Verify, clean, and return
                   9955:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9956: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9957: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9958: 	}
1.242     www      9959:     }
1.44      www      9960:     $thisfn=declutter($thisfn);
1.31      www      9961:     my %hash;
1.37      www      9962:     my %bighash;
                   9963:     my $syval='';
1.620     albertel 9964:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9965:         my $targetfn = $thisfn;
1.609     banghart 9966:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9967:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9968:         }
1.687     albertel 9969: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9970: 	    $targetfn=$1;
                   9971: 	}
1.620     albertel 9972:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9973:                       &GDBM_READER(),0640)) {
1.481     raeburn  9974: 	    $syval=$hash{$targetfn};
1.37      www      9975:             untie(%hash);
                   9976:         }
                   9977: # ---------------------------------------------------------- There was an entry
                   9978:         if ($syval) {
1.601     albertel 9979: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9980: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9981: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9982: 		    #return $env{$cache_str}='';
1.601     albertel 9983: 		#}    
                   9984: 		#$syval.=$1;
                   9985: 	    #}
1.37      www      9986:         } else {
                   9987: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9988:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9989:                             &GDBM_READER(),0640)) {
1.37      www      9990: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9991:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9992:               unless ($ids) { 
                   9993:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9994:               }
                   9995:               unless ($ids) {
                   9996: # alias?
                   9997: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9998:               }
1.37      www      9999:               if ($ids) {
                   10000: # ------------------------------------------------------------------- Has ID(s)
                   10001:                  my @possibilities=split(/\,/,$ids);
1.39      www      10002:                  if ($#possibilities==0) {
                   10003: # ----------------------------------------------- There is only one possibility
1.37      www      10004: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10005: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10006: 						    $resid,$thisfn);
1.249     www      10007:                  } elsif (!$donotrecurse) {
1.39      www      10008: # ------------------------------------------ There is more than one possibility
                   10009:                      my $realpossible=0;
1.800     albertel 10010:                      foreach my $id (@possibilities) {
                   10011: 			 my $file=$bighash{'src_'.$id};
1.39      www      10012:                          if (&allowed('bre',$file)) {
1.800     albertel 10013:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10014:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10015: 				$realpossible++;
1.626     albertel 10016:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10017: 						    $resid,$thisfn);
1.39      www      10018:                             }
                   10019: 			 }
1.191     harris41 10020:                      }
1.39      www      10021: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10022:                  } else {
                   10023:                      $syval='';
1.37      www      10024:                  }
                   10025: 	      }
                   10026:               untie(%bighash)
1.481     raeburn  10027:            }
1.31      www      10028:         }
1.62      www      10029:         if ($syval) {
1.620     albertel 10030: 	    return $env{$cache_str}=$syval;
1.62      www      10031:         }
1.31      www      10032:     }
1.949     raeburn  10033:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10034:     return $env{$cache_str}='';
1.31      www      10035: }
                   10036: 
                   10037: # ---------------------------------------------------------- Return random seed
                   10038: 
1.32      www      10039: sub numval {
                   10040:     my $txt=shift;
                   10041:     $txt=~tr/A-J/0-9/;
                   10042:     $txt=~tr/a-j/0-9/;
                   10043:     $txt=~tr/K-T/0-9/;
                   10044:     $txt=~tr/k-t/0-9/;
                   10045:     $txt=~tr/U-Z/0-5/;
                   10046:     $txt=~tr/u-z/0-5/;
                   10047:     $txt=~s/\D//g;
1.564     albertel 10048:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10049:     return int($txt);
1.368     albertel 10050: }
                   10051: 
1.484     albertel 10052: sub numval2 {
                   10053:     my $txt=shift;
                   10054:     $txt=~tr/A-J/0-9/;
                   10055:     $txt=~tr/a-j/0-9/;
                   10056:     $txt=~tr/K-T/0-9/;
                   10057:     $txt=~tr/k-t/0-9/;
                   10058:     $txt=~tr/U-Z/0-5/;
                   10059:     $txt=~tr/u-z/0-5/;
                   10060:     $txt=~s/\D//g;
                   10061:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10062:     my $total;
                   10063:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10064:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10065:     return int($total);
                   10066: }
                   10067: 
1.575     albertel 10068: sub numval3 {
                   10069:     use integer;
                   10070:     my $txt=shift;
                   10071:     $txt=~tr/A-J/0-9/;
                   10072:     $txt=~tr/a-j/0-9/;
                   10073:     $txt=~tr/K-T/0-9/;
                   10074:     $txt=~tr/k-t/0-9/;
                   10075:     $txt=~tr/U-Z/0-5/;
                   10076:     $txt=~tr/u-z/0-5/;
                   10077:     $txt=~s/\D//g;
                   10078:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10079:     my $total;
                   10080:     foreach my $val (@txts) { $total+=$val; }
                   10081:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10082:     return $total;
                   10083: }
                   10084: 
1.675     albertel 10085: sub digest {
                   10086:     my ($data)=@_;
                   10087:     my $digest=&Digest::MD5::md5($data);
                   10088:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10089:     my ($e,$f);
                   10090:     {
                   10091:         use integer;
                   10092:         $e=($a+$b);
                   10093:         $f=($c+$d);
                   10094:         if ($_64bit) {
                   10095:             $e=(($e<<32)>>32);
                   10096:             $f=(($f<<32)>>32);
                   10097:         }
                   10098:     }
                   10099:     if (wantarray) {
                   10100: 	return ($e,$f);
                   10101:     } else {
                   10102: 	my $g;
                   10103: 	{
                   10104: 	    use integer;
                   10105: 	    $g=($e+$f);
                   10106: 	    if ($_64bit) {
                   10107: 		$g=(($g<<32)>>32);
                   10108: 	    }
                   10109: 	}
                   10110: 	return $g;
                   10111:     }
                   10112: }
                   10113: 
1.368     albertel 10114: sub latest_rnd_algorithm_id {
1.675     albertel 10115:     return '64bit5';
1.366     albertel 10116: }
1.32      www      10117: 
1.503     albertel 10118: sub get_rand_alg {
                   10119:     my ($courseid)=@_;
1.790     albertel 10120:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10121:     if ($courseid) {
1.620     albertel 10122: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10123:     }
                   10124:     return &latest_rnd_algorithm_id();
                   10125: }
                   10126: 
1.562     albertel 10127: sub validCODE {
                   10128:     my ($CODE)=@_;
                   10129:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10130:     return 0;
                   10131: }
                   10132: 
1.491     albertel 10133: sub getCODE {
1.620     albertel 10134:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10135:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10136: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10137: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10138: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10139:     }
                   10140:     return undef;
                   10141: }
1.1133    foxr     10142: #
                   10143: #  Determines the random seed for a specific context:
                   10144: #
                   10145: # parameters:
                   10146: #   symb      - in course context the symb for the seed.
                   10147: #   course_id - The course id of the form domain_coursenum.
                   10148: #   domain    - Domain for the user.
                   10149: #   course    - Course for the user.
                   10150: #   cenv      - environment of the course.
                   10151: #
                   10152: # NOTE:
                   10153: #   All parameters are picked out of the environment if missing
                   10154: #   or not defined.
                   10155: #   If a symb cannot be determined the current time is used instead.
                   10156: #
                   10157: #  For a given well defined symb, courside, domain, username,
                   10158: #  and course environment, the seed is reproducible.
                   10159: #
1.31      www      10160: sub rndseed {
1.1133    foxr     10161:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10162:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10163:     if (!defined($symb)) {
1.366     albertel 10164: 	unless ($symb=$wsymb) { return time; }
                   10165:     }
1.1146    foxr     10166:     if (!defined $courseid) { 
                   10167: 	$courseid=$wcourseid; 
                   10168:     }
                   10169:     if (!defined $domain) { $domain=$wdomain; }
                   10170:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10171: 
                   10172:     my $which;
                   10173:     if (defined($cenv->{'rndseed'})) {
                   10174: 	$which = $cenv->{'rndseed'};
                   10175:     } else {
                   10176: 	$which =&get_rand_alg($courseid);
                   10177:     }
1.491     albertel 10178:     if (defined(&getCODE())) {
1.1133    foxr     10179: 
1.675     albertel 10180: 	if ($which eq '64bit5') {
                   10181: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10182: 	} elsif ($which eq '64bit4') {
1.575     albertel 10183: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10184: 	} else {
                   10185: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10186: 	}
1.675     albertel 10187:     } elsif ($which eq '64bit5') {
                   10188: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10189:     } elsif ($which eq '64bit4') {
                   10190: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10191:     } elsif ($which eq '64bit3') {
                   10192: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10193:     } elsif ($which eq '64bit2') {
                   10194: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10195:     } elsif ($which eq '64bit') {
                   10196: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10197:     }
                   10198:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10199: }
                   10200: 
                   10201: sub rndseed_32bit {
                   10202:     my ($symb,$courseid,$domain,$username)=@_;
                   10203:     {
                   10204: 	use integer;
                   10205: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10206: 	my $symbseed=numval($symb) << 22;
                   10207: 	my $namechck=unpack("%32C*",$username) << 17;
                   10208: 	my $nameseed=numval($username) << 12;
                   10209: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10210: 	my $courseseed=unpack("%32C*",$courseid);
                   10211: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10212: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10213: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10214: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10215: 	return $num;
                   10216:     }
                   10217: }
                   10218: 
                   10219: sub rndseed_64bit {
                   10220:     my ($symb,$courseid,$domain,$username)=@_;
                   10221:     {
                   10222: 	use integer;
                   10223: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10224: 	my $symbseed=numval($symb) << 10;
                   10225: 	my $namechck=unpack("%32S*",$username);
                   10226: 	
                   10227: 	my $nameseed=numval($username) << 21;
                   10228: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10229: 	my $courseseed=unpack("%32S*",$courseid);
                   10230: 	
                   10231: 	my $num1=$symbchck+$symbseed+$namechck;
                   10232: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10233: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10234: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10235: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10236: 	return "$num1,$num2";
1.155     albertel 10237:     }
1.366     albertel 10238: }
                   10239: 
1.443     albertel 10240: sub rndseed_64bit2 {
                   10241:     my ($symb,$courseid,$domain,$username)=@_;
                   10242:     {
                   10243: 	use integer;
                   10244: 	# strings need to be an even # of cahracters long, it it is odd the
                   10245:         # last characters gets thrown away
                   10246: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10247: 	my $symbseed=numval($symb) << 10;
                   10248: 	my $namechck=unpack("%32S*",$username.' ');
                   10249: 	
                   10250: 	my $nameseed=numval($username) << 21;
1.501     albertel 10251: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10252: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10253: 	
                   10254: 	my $num1=$symbchck+$symbseed+$namechck;
                   10255: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10256: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10257: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10258: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10259: 	return "$num1,$num2";
                   10260:     }
                   10261: }
                   10262: 
                   10263: sub rndseed_64bit3 {
                   10264:     my ($symb,$courseid,$domain,$username)=@_;
                   10265:     {
                   10266: 	use integer;
                   10267: 	# strings need to be an even # of cahracters long, it it is odd the
                   10268:         # last characters gets thrown away
                   10269: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10270: 	my $symbseed=numval2($symb) << 10;
                   10271: 	my $namechck=unpack("%32S*",$username.' ');
                   10272: 	
                   10273: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10274: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10275: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10276: 	
                   10277: 	my $num1=$symbchck+$symbseed+$namechck;
                   10278: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10279: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10280: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10281: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10282: 	
1.503     albertel 10283: 	return "$num1:$num2";
1.443     albertel 10284:     }
                   10285: }
                   10286: 
1.575     albertel 10287: sub rndseed_64bit4 {
                   10288:     my ($symb,$courseid,$domain,$username)=@_;
                   10289:     {
                   10290: 	use integer;
                   10291: 	# strings need to be an even # of cahracters long, it it is odd the
                   10292:         # last characters gets thrown away
                   10293: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10294: 	my $symbseed=numval3($symb) << 10;
                   10295: 	my $namechck=unpack("%32S*",$username.' ');
                   10296: 	
                   10297: 	my $nameseed=numval3($username) << 21;
                   10298: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10299: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10300: 	
                   10301: 	my $num1=$symbchck+$symbseed+$namechck;
                   10302: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10303: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10304: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10305: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10306: 	
1.575     albertel 10307: 	return "$num1:$num2";
                   10308:     }
                   10309: }
                   10310: 
1.675     albertel 10311: sub rndseed_64bit5 {
                   10312:     my ($symb,$courseid,$domain,$username)=@_;
                   10313:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10314:     return "$num1:$num2";
                   10315: }
                   10316: 
1.366     albertel 10317: sub rndseed_CODE_64bit {
                   10318:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10319:     {
1.366     albertel 10320: 	use integer;
1.443     albertel 10321: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10322: 	my $symbseed=numval2($symb);
1.491     albertel 10323: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10324: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10325: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10326: 	my $num1=$symbseed+$CODEchck;
                   10327: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10328: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10329: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10330: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10331: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10332: 	return "$num1:$num2";
1.366     albertel 10333:     }
                   10334: }
                   10335: 
1.575     albertel 10336: sub rndseed_CODE_64bit4 {
                   10337:     my ($symb,$courseid,$domain,$username)=@_;
                   10338:     {
                   10339: 	use integer;
                   10340: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10341: 	my $symbseed=numval3($symb);
                   10342: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10343: 	my $CODEseed=numval3(&getCODE());
                   10344: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10345: 	my $num1=$symbseed+$CODEchck;
                   10346: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10347: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10348: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10349: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10350: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10351: 	return "$num1:$num2";
                   10352:     }
                   10353: }
                   10354: 
1.675     albertel 10355: sub rndseed_CODE_64bit5 {
                   10356:     my ($symb,$courseid,$domain,$username)=@_;
                   10357:     my $code = &getCODE();
                   10358:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10359:     return "$num1:$num2";
                   10360: }
                   10361: 
1.366     albertel 10362: sub setup_random_from_rndseed {
                   10363:     my ($rndseed)=@_;
1.503     albertel 10364:     if ($rndseed =~/([,:])/) {
                   10365: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10366: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10367:     } else {
                   10368: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10369:     }
1.36      albertel 10370: }
                   10371: 
1.474     albertel 10372: sub latest_receipt_algorithm_id {
1.835     albertel 10373:     return 'receipt3';
1.474     albertel 10374: }
                   10375: 
1.480     www      10376: sub recunique {
                   10377:     my $fucourseid=shift;
                   10378:     my $unique;
1.835     albertel 10379:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10380: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10381: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10382:     } else {
                   10383: 	$unique=$perlvar{'lonReceipt'};
                   10384:     }
                   10385:     return unpack("%32C*",$unique);
                   10386: }
                   10387: 
                   10388: sub recprefix {
                   10389:     my $fucourseid=shift;
                   10390:     my $prefix;
1.835     albertel 10391:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10392: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10393: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10394:     } else {
                   10395: 	$prefix=$perlvar{'lonHostID'};
                   10396:     }
                   10397:     return unpack("%32C*",$prefix);
                   10398: }
                   10399: 
1.76      www      10400: sub ireceipt {
1.474     albertel 10401:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10402: 
                   10403:     my $return =&recprefix($fucourseid).'-';
                   10404: 
                   10405:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10406: 	$env{'request.state'} eq 'construct') {
                   10407: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10408: 	return $return;
                   10409:     }
                   10410: 
1.76      www      10411:     my $cuname=unpack("%32C*",$funame);
                   10412:     my $cudom=unpack("%32C*",$fudom);
                   10413:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10414:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10415:     my $cunique=&recunique($fucourseid);
1.474     albertel 10416:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10417:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10418: 
1.790     albertel 10419: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10420: 			       
                   10421: 	$return.= ($cunique%$cuname+
                   10422: 		   $cunique%$cudom+
                   10423: 		   $cusymb%$cuname+
                   10424: 		   $cusymb%$cudom+
                   10425: 		   $cucourseid%$cuname+
                   10426: 		   $cucourseid%$cudom+
                   10427: 		   $cpart%$cuname+
                   10428: 		   $cpart%$cudom);
                   10429:     } else {
                   10430: 	$return.= ($cunique%$cuname+
                   10431: 		   $cunique%$cudom+
                   10432: 		   $cusymb%$cuname+
                   10433: 		   $cusymb%$cudom+
                   10434: 		   $cucourseid%$cuname+
                   10435: 		   $cucourseid%$cudom);
                   10436:     }
                   10437:     return $return;
1.76      www      10438: }
                   10439: 
                   10440: sub receipt {
1.474     albertel 10441:     my ($part)=@_;
1.790     albertel 10442:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10443:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10444: }
1.260     ng       10445: 
1.790     albertel 10446: sub whichuser {
                   10447:     my ($passedsymb)=@_;
                   10448:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10449:     if (defined($env{'form.grade_symb'})) {
                   10450: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10451: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10452: 	if (!$allowed &&
                   10453: 	    exists($env{'request.course.sec'}) &&
                   10454: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10455: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10456: 			      '/'.$env{'request.course.sec'});
                   10457: 	}
                   10458: 	if ($allowed) {
                   10459: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10460: 	    $courseid=$tmp_courseid;
                   10461: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10462: 	    ($name)=&get_env_multiple('form.grade_username');
                   10463: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10464: 	}
                   10465:     }
                   10466:     if (!$passedsymb) {
                   10467: 	$symb=&symbread();
                   10468:     } else {
                   10469: 	$symb=$passedsymb;
                   10470:     }
                   10471:     $courseid=$env{'request.course.id'};
                   10472:     $domain=$env{'user.domain'};
                   10473:     $name=$env{'user.name'};
                   10474:     if ($name eq 'public' && $domain eq 'public') {
                   10475: 	if (!defined($env{'form.username'})) {
                   10476: 	    $env{'form.username'}.=time.rand(10000000);
                   10477: 	}
                   10478: 	$name.=$env{'form.username'};
                   10479:     }
                   10480:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10481: 
                   10482: }
                   10483: 
1.36      albertel 10484: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10485: # returns either the contents of the file or 
                   10486: # -1 if the file doesn't exist
1.481     raeburn  10487: #
                   10488: # if the target is a file that was uploaded via DOCS, 
                   10489: # a check will be made to see if a current copy exists on the local server,
                   10490: # if it does this will be served, otherwise a copy will be retrieved from
                   10491: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10492: # the local server.   
1.472     albertel 10493: 
1.36      albertel 10494: sub getfile {
1.538     albertel 10495:     my ($file) = @_;
1.609     banghart 10496:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10497:     &repcopy($file);
                   10498:     return &readfile($file);
                   10499: }
                   10500: 
                   10501: sub repcopy_userfile {
                   10502:     my ($file)=@_;
1.1142    raeburn  10503:     my $londocroot = $perlvar{'lonDocRoot'};
                   10504:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10505:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10506:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10507: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10508:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10509:     if (-e "$file") {
1.828     www      10510: # we already have a local copy, check it out
1.538     albertel 10511: 	my @fileinfo = stat($file);
1.828     www      10512: 	my $rtncode;
                   10513: 	my $info;
1.538     albertel 10514: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10515: 	if ($lwpresp ne 'ok') {
1.828     www      10516: # there is no such file anymore, even though we had a local copy
1.482     albertel 10517: 	    if ($rtncode eq '404') {
1.538     albertel 10518: 		unlink($file);
1.482     albertel 10519: 	    }
                   10520: 	    return -1;
                   10521: 	}
                   10522: 	if ($info < $fileinfo[9]) {
1.828     www      10523: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10524: 	    return 'ok';
1.828     www      10525: 	} else {
                   10526: # the file is outdated, get rid of it
                   10527: 	    unlink($file);
1.482     albertel 10528: 	}
1.828     www      10529:     }
                   10530: # one way or the other, at this point, we don't have the file
                   10531: # construct the correct path for the file
                   10532:     my @parts = ($cdom,$cnum); 
                   10533:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10534: 	push @parts, split(/\//,$1);
                   10535:     }
                   10536:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10537:     foreach my $part (@parts) {
                   10538: 	$path .= '/'.$part;
                   10539: 	if (!-e $path) {
                   10540: 	    mkdir($path,0770);
1.482     albertel 10541: 	}
                   10542:     }
1.828     www      10543: # now the path exists for sure
                   10544: # get a user agent
                   10545:     my $ua=new LWP::UserAgent;
                   10546:     my $transferfile=$file.'.in.transfer';
                   10547: # FIXME: this should flock
                   10548:     if (-e $transferfile) { return 'ok'; }
                   10549:     my $request;
                   10550:     $uri=~s/^\///;
1.980     raeburn  10551:     my $homeserver = &homeserver($cnum,$cdom);
                   10552:     my $protocol = $protocol{$homeserver};
                   10553:     $protocol = 'http' if ($protocol ne 'https');
                   10554:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10555:     my $response=$ua->request($request,$transferfile);
                   10556: # did it work?
                   10557:     if ($response->is_error()) {
                   10558: 	unlink($transferfile);
                   10559: 	&logthis("Userfile repcopy failed for $uri");
                   10560: 	return -1;
                   10561:     }
                   10562: # worked, rename the transfer file
                   10563:     rename($transferfile,$file);
1.607     raeburn  10564:     return 'ok';
1.481     raeburn  10565: }
                   10566: 
1.517     albertel 10567: sub tokenwrapper {
                   10568:     my $uri=shift;
1.980     raeburn  10569:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10570:     $uri=~s|^/||;
1.620     albertel 10571:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10572:     my $token=$1;
1.552     albertel 10573:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10574:     if ($udom && $uname && $file) {
                   10575: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10576:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10577:         my $homeserver = &homeserver($uname,$udom);
                   10578:         my $protocol = $protocol{$homeserver};
                   10579:         $protocol = 'http' if ($protocol ne 'https');
                   10580:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10581:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10582:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10583:     } else {
                   10584:         return '/adm/notfound.html';
                   10585:     }
                   10586: }
                   10587: 
1.828     www      10588: # call with reqtype HEAD: get last modification time
                   10589: # call with reqtype GET: get the file contents
                   10590: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10591: #
1.481     raeburn  10592: sub getuploaded {
                   10593:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10594:     $uri=~s/^\///;
1.980     raeburn  10595:     my $homeserver = &homeserver($cnum,$cdom);
                   10596:     my $protocol = $protocol{$homeserver};
                   10597:     $protocol = 'http' if ($protocol ne 'https');
                   10598:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10599:     my $ua=new LWP::UserAgent;
                   10600:     my $request=new HTTP::Request($reqtype,$uri);
                   10601:     my $response=$ua->request($request);
                   10602:     $$rtncode = $response->code;
1.482     albertel 10603:     if (! $response->is_success()) {
                   10604: 	return 'failed';
                   10605:     }      
                   10606:     if ($reqtype eq 'HEAD') {
1.486     www      10607: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10608:     } elsif ($reqtype eq 'GET') {
                   10609: 	$$info = $response->content;
1.472     albertel 10610:     }
1.482     albertel 10611:     return 'ok';
1.36      albertel 10612: }
                   10613: 
1.481     raeburn  10614: sub readfile {
                   10615:     my $file = shift;
                   10616:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10617:     my $fh;
                   10618:     open($fh,"<$file");
                   10619:     my $a='';
1.800     albertel 10620:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10621:     return $a;
                   10622: }
                   10623: 
1.36      albertel 10624: sub filelocation {
1.590     banghart 10625:     my ($dir,$file) = @_;
                   10626:     my $location;
                   10627:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10628: 
                   10629:     if ($file =~ m-^/adm/-) {
                   10630: 	$file=~s-^/adm/wrapper/-/-;
                   10631: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10632:     }
1.882     albertel 10633: 
1.1139    www      10634:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10635:         $location = $file;
1.609     banghart 10636:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10637:         my ($udom,$uname,$filename)=
1.811     albertel 10638:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10639:         my $home=&homeserver($uname,$udom);
                   10640:         my $is_me=0;
                   10641:         my @ids=&current_machine_ids();
                   10642:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10643:         if ($is_me) {
1.1117    foxr     10644:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10645:         } else {
                   10646:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10647:   	      $udom.'/'.$uname.'/'.$filename;
                   10648:         }
1.882     albertel 10649:     } elsif ($file =~ m-^/adm/-) {
                   10650: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10651:     } else {
                   10652:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10653:         $file=~s:^/(res|priv)/:/:;
                   10654:         my $space=$1;
1.590     banghart 10655:         if ( !( $file =~ m:^/:) ) {
                   10656:             $location = $dir. '/'.$file;
                   10657:         } else {
1.1142    raeburn  10658:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10659:         }
1.59      albertel 10660:     }
1.590     banghart 10661:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10662:     while ($location=~m{/\.\./}) {
                   10663: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10664: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10665: 	} else {
                   10666: 	    $location=~ s{/\.\./}{/}g;
                   10667: 	}
                   10668:     } #remove dir/..
1.590     banghart 10669:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10670:     return $location;
1.46      www      10671: }
1.36      albertel 10672: 
1.46      www      10673: sub hreflocation {
                   10674:     my ($dir,$file)=@_;
1.980     raeburn  10675:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10676: 	$file=filelocation($dir,$file);
1.700     albertel 10677:     } elsif ($file=~m-^/adm/-) {
                   10678: 	$file=~s-^/adm/wrapper/-/-;
                   10679: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10680:     }
                   10681:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10682: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10683:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10684: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10685: 	        {/uploaded/$1/$2/}x;
1.46      www      10686:     }
1.913     albertel 10687:     if ($file=~ m{^/userfiles/}) {
                   10688: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10689:     }
1.462     albertel 10690:     return $file;
1.465     albertel 10691: }
                   10692: 
1.1139    www      10693: 
                   10694: 
                   10695: 
                   10696: 
1.465     albertel 10697: sub current_machine_domains {
1.853     albertel 10698:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10699: }
                   10700: 
                   10701: sub machine_domains {
                   10702:     my ($hostname) = @_;
1.465     albertel 10703:     my @domains;
1.838     albertel 10704:     my %hostname = &all_hostnames();
1.465     albertel 10705:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10706: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10707: 	if ($hostname eq $name) {
1.844     albertel 10708: 	    push(@domains,&host_domain($id));
1.465     albertel 10709: 	}
                   10710:     }
                   10711:     return @domains;
                   10712: }
                   10713: 
                   10714: sub current_machine_ids {
1.853     albertel 10715:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10716: }
                   10717: 
                   10718: sub machine_ids {
                   10719:     my ($hostname) = @_;
                   10720:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10721:     my @ids;
1.888     albertel 10722:     my %name_to_host = &all_names();
1.889     albertel 10723:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10724: 	return @{ $name_to_host{$hostname} };
                   10725:     }
                   10726:     return;
1.31      www      10727: }
                   10728: 
1.824     raeburn  10729: sub additional_machine_domains {
                   10730:     my @domains;
                   10731:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10732:     while( my $line = <$fh>) {
                   10733:         $line =~ s/\s//g;
                   10734:         push(@domains,$line);
                   10735:     }
                   10736:     return @domains;
                   10737: }
                   10738: 
                   10739: sub default_login_domain {
                   10740:     my $domain = $perlvar{'lonDefDomain'};
                   10741:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10742:     foreach my $posdom (&current_machine_domains(),
                   10743:                         &additional_machine_domains()) {
                   10744:         if (lc($posdom) eq lc($testdomain)) {
                   10745:             $domain=$posdom;
                   10746:             last;
                   10747:         }
                   10748:     }
                   10749:     return $domain;
                   10750: }
                   10751: 
1.31      www      10752: # ------------------------------------------------------------- Declutters URLs
                   10753: 
                   10754: sub declutter {
                   10755:     my $thisfn=shift;
1.569     albertel 10756:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10757:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10758:     $thisfn=~s/^\///;
1.697     albertel 10759:     $thisfn=~s|^adm/wrapper/||;
                   10760:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10761:     $thisfn=~s/^res\///;
1.1172    bisitz   10762:     $thisfn=~s/^priv\///;
1.1032    raeburn  10763:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10764:         $thisfn=~s/\?.+$//;
                   10765:     }
1.268     www      10766:     return $thisfn;
                   10767: }
                   10768: 
                   10769: # ------------------------------------------------------------- Clutter up URLs
                   10770: 
                   10771: sub clutter {
                   10772:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10773:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10774: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10775:        $thisfn='/res'.$thisfn; 
                   10776:     }
1.1031    raeburn  10777:     if ($thisfn !~m|^/adm|) {
                   10778: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10779: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10780: 	} else {
                   10781: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10782: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10783: 	    if ($embstyle eq 'ssi'
                   10784: 		|| ($embstyle eq 'hdn')
                   10785: 		|| ($embstyle eq 'rat')
                   10786: 		|| ($embstyle eq 'prv')
                   10787: 		|| ($embstyle eq 'ign')) {
                   10788: 		#do nothing with these
                   10789: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10790: 		|| ($embstyle eq 'emb')
                   10791: 		|| ($embstyle eq 'wrp')) {
                   10792: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10793: 	    } elsif ($embstyle eq 'unk'
                   10794: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10795: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10796: 	    } else {
1.718     www      10797: #		&logthis("Got a blank emb style");
1.695     albertel 10798: 	    }
1.694     albertel 10799: 	}
                   10800:     }
1.31      www      10801:     return $thisfn;
1.12      www      10802: }
                   10803: 
1.787     albertel 10804: sub clutter_with_no_wrapper {
                   10805:     my $uri = &clutter(shift);
                   10806:     if ($uri =~ m-^/adm/-) {
                   10807: 	$uri =~ s-^/adm/wrapper/-/-;
                   10808: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10809:     }
                   10810:     return $uri;
                   10811: }
                   10812: 
1.557     albertel 10813: sub freeze_escape {
                   10814:     my ($value)=@_;
                   10815:     if (ref($value)) {
                   10816: 	$value=&nfreeze($value);
                   10817: 	return '__FROZEN__'.&escape($value);
                   10818:     }
                   10819:     return &escape($value);
                   10820: }
                   10821: 
1.11      www      10822: 
1.557     albertel 10823: sub thaw_unescape {
                   10824:     my ($value)=@_;
                   10825:     if ($value =~ /^__FROZEN__/) {
                   10826: 	substr($value,0,10,undef);
                   10827: 	$value=&unescape($value);
                   10828: 	return &thaw($value);
                   10829:     }
                   10830:     return &unescape($value);
                   10831: }
                   10832: 
1.436     albertel 10833: sub correct_line_ends {
                   10834:     my ($result)=@_;
                   10835:     $$result =~s/\r\n/\n/mg;
                   10836:     $$result =~s/\r/\n/mg;
1.415     albertel 10837: }
1.1       albertel 10838: # ================================================================ Main Program
                   10839: 
1.184     www      10840: sub goodbye {
1.204     albertel 10841:    &logthis("Starting Shut down");
1.443     albertel 10842: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10843:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10844: #converted
1.599     albertel 10845: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10846:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10847: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10848: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10849: #1.1 only
1.870     albertel 10850: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10851: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10852: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10853: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10854:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10855:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10856:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10857:    &flushcourselogs();
                   10858:    &logthis("Shutting down");
                   10859: }
                   10860: 
1.852     albertel 10861: sub get_dns {
1.869     albertel 10862:     my ($url,$func,$ignore_cache) = @_;
                   10863:     if (!$ignore_cache) {
                   10864: 	my ($content,$cached)=
                   10865: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10866: 	if ($cached) {
                   10867: 	    &$func($content);
                   10868: 	    return;
                   10869: 	}
                   10870:     }
                   10871: 
                   10872:     my %alldns;
1.852     albertel 10873:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10874:     foreach my $dns (<$config>) {
                   10875: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10876:         my $line = $1;
                   10877:         my ($host,$protocol) = split(/:/,$line);
                   10878:         if ($protocol ne 'https') {
                   10879:             $protocol = 'http';
                   10880:         }
                   10881: 	$alldns{$host} = $protocol;
1.869     albertel 10882:     }
                   10883:     while (%alldns) {
                   10884: 	my ($dns) = keys(%alldns);
1.852     albertel 10885: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10886:         $ua->timeout(30);
1.979     raeburn  10887: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10888: 	my $response=$ua->request($request);
1.979     raeburn  10889:         delete($alldns{$dns});
1.852     albertel 10890: 	next if ($response->is_error());
                   10891: 	my @content = split("\n",$response->content);
1.869     albertel 10892: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10893: 	&$func(\@content);
1.869     albertel 10894: 	return;
1.852     albertel 10895:     }
                   10896:     close($config);
1.871     albertel 10897:     my $which = (split('/',$url))[3];
                   10898:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10899:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10900:     my @content = <$config>;
                   10901:     &$func(\@content);
                   10902:     return;
1.852     albertel 10903: }
1.327     albertel 10904: # ------------------------------------------------------------ Read domain file
                   10905: {
1.852     albertel 10906:     my $loaded;
1.846     albertel 10907:     my %domain;
                   10908: 
1.852     albertel 10909:     sub parse_domain_tab {
                   10910: 	my ($lines) = @_;
                   10911: 	foreach my $line (@$lines) {
                   10912: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10913: 
1.846     albertel 10914: 	    chomp($line);
1.852     albertel 10915: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10916: 	    my %this_domain;
                   10917: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10918: 			       'lang_def', 'city', 'longi', 'lati',
                   10919: 			       'primary') {
                   10920: 		$this_domain{$field} = shift(@elements);
                   10921: 	    }
                   10922: 	    $domain{$name} = \%this_domain;
1.852     albertel 10923: 	}
                   10924:     }
1.864     albertel 10925: 
                   10926:     sub reset_domain_info {
                   10927: 	undef($loaded);
                   10928: 	undef(%domain);
                   10929:     }
                   10930: 
1.852     albertel 10931:     sub load_domain_tab {
1.869     albertel 10932: 	my ($ignore_cache) = @_;
                   10933: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10934: 	my $fh;
                   10935: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10936: 	    my @lines = <$fh>;
                   10937: 	    &parse_domain_tab(\@lines);
1.448     albertel 10938: 	}
1.852     albertel 10939: 	close($fh);
                   10940: 	$loaded = 1;
1.327     albertel 10941:     }
1.846     albertel 10942: 
                   10943:     sub domain {
1.852     albertel 10944: 	&load_domain_tab() if (!$loaded);
                   10945: 
1.846     albertel 10946: 	my ($name,$what) = @_;
                   10947: 	return if ( !exists($domain{$name}) );
                   10948: 
                   10949: 	if (!$what) {
                   10950: 	    return $domain{$name}{'description'};
                   10951: 	}
                   10952: 	return $domain{$name}{$what};
                   10953:     }
1.974     raeburn  10954: 
                   10955:     sub domain_info {
                   10956:         &load_domain_tab() if (!$loaded);
                   10957:         return %domain;
                   10958:     }
                   10959: 
1.327     albertel 10960: }
                   10961: 
                   10962: 
1.1       albertel 10963: # ------------------------------------------------------------- Read hosts file
                   10964: {
1.838     albertel 10965:     my %hostname;
1.844     albertel 10966:     my %hostdom;
1.845     albertel 10967:     my %libserv;
1.852     albertel 10968:     my $loaded;
1.888     albertel 10969:     my %name_to_host;
1.1074    raeburn  10970:     my %internetdom;
1.1107    raeburn  10971:     my %LC_dns_serv;
1.852     albertel 10972: 
                   10973:     sub parse_hosts_tab {
                   10974: 	my ($file) = @_;
                   10975: 	foreach my $configline (@$file) {
                   10976: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10977:             chomp($configline);
                   10978: 	    if ($configline =~ /^\^/) {
                   10979:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10980:                     $LC_dns_serv{$1} = 1;
                   10981:                 }
                   10982:                 next;
                   10983:             }
1.1074    raeburn  10984: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10985: 	    $name=~s/\s//g;
                   10986: 	    if ($id && $domain && $role && $name) {
                   10987: 		$hostname{$id}=$name;
1.888     albertel 10988: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10989: 		$hostdom{$id}=$domain;
                   10990: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10991:                 if (defined($protocol)) {
                   10992:                     if ($protocol eq 'https') {
                   10993:                         $protocol{$id} = $protocol;
                   10994:                     } else {
                   10995:                         $protocol{$id} = 'http'; 
                   10996:                     }
1.968     raeburn  10997:                 } else {
1.969     raeburn  10998:                     $protocol{$id} = 'http';
1.968     raeburn  10999:                 }
1.1074    raeburn  11000:                 if (defined($intdom)) {
                   11001:                     $internetdom{$id} = $intdom;
                   11002:                 }
1.852     albertel 11003: 	    }
                   11004: 	}
                   11005:     }
1.864     albertel 11006:     
                   11007:     sub reset_hosts_info {
1.897     albertel 11008: 	&purge_remembered();
1.864     albertel 11009: 	&reset_domain_info();
                   11010: 	&reset_hosts_ip_info();
1.892     albertel 11011: 	undef(%name_to_host);
1.864     albertel 11012: 	undef(%hostname);
                   11013: 	undef(%hostdom);
                   11014: 	undef(%libserv);
                   11015: 	undef($loaded);
                   11016:     }
1.1       albertel 11017: 
1.852     albertel 11018:     sub load_hosts_tab {
1.869     albertel 11019: 	my ($ignore_cache) = @_;
                   11020: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11021: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11022: 	my @config = <$config>;
                   11023: 	&parse_hosts_tab(\@config);
                   11024: 	close($config);
                   11025: 	$loaded=1;
1.1       albertel 11026:     }
1.852     albertel 11027: 
1.838     albertel 11028:     sub hostname {
1.852     albertel 11029: 	&load_hosts_tab() if (!$loaded);
                   11030: 
1.838     albertel 11031: 	my ($lonid) = @_;
                   11032: 	return $hostname{$lonid};
                   11033:     }
1.845     albertel 11034: 
1.838     albertel 11035:     sub all_hostnames {
1.852     albertel 11036: 	&load_hosts_tab() if (!$loaded);
                   11037: 
1.838     albertel 11038: 	return %hostname;
                   11039:     }
1.845     albertel 11040: 
1.888     albertel 11041:     sub all_names {
                   11042: 	&load_hosts_tab() if (!$loaded);
                   11043: 
                   11044: 	return %name_to_host;
                   11045:     }
                   11046: 
1.974     raeburn  11047:     sub all_host_domain {
                   11048:         &load_hosts_tab() if (!$loaded);
                   11049:         return %hostdom;
                   11050:     }
                   11051: 
1.845     albertel 11052:     sub is_library {
1.852     albertel 11053: 	&load_hosts_tab() if (!$loaded);
                   11054: 
1.845     albertel 11055: 	return exists($libserv{$_[0]});
                   11056:     }
                   11057: 
                   11058:     sub all_library {
1.852     albertel 11059: 	&load_hosts_tab() if (!$loaded);
                   11060: 
1.845     albertel 11061: 	return %libserv;
                   11062:     }
                   11063: 
1.1062    droeschl 11064:     sub unique_library {
                   11065: 	#2x reverse removes all hostnames that appear more than once
                   11066:         my %unique = reverse &all_library();
                   11067:         return reverse %unique;
                   11068:     }
                   11069: 
1.841     albertel 11070:     sub get_servers {
1.852     albertel 11071: 	&load_hosts_tab() if (!$loaded);
                   11072: 
1.841     albertel 11073: 	my ($domain,$type) = @_;
                   11074: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11075: 	                                          : %hostname;
                   11076: 	my %result;
1.842     albertel 11077: 	if (ref($domain) eq 'ARRAY') {
                   11078: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11079: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11080: 		    $result{$host} = $hostname;
                   11081: 		}
                   11082: 	    }
                   11083: 	} else {
                   11084: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11085: 		if ($hostdom{$host} eq $domain) {
                   11086: 		    $result{$host} = $hostname;
                   11087: 		}
1.841     albertel 11088: 	    }
                   11089: 	}
                   11090: 	return %result;
                   11091:     }
1.845     albertel 11092: 
1.1062    droeschl 11093:     sub get_unique_servers {
                   11094:         my %unique = reverse &get_servers(@_);
                   11095: 	return reverse %unique;
                   11096:     }
                   11097: 
1.844     albertel 11098:     sub host_domain {
1.852     albertel 11099: 	&load_hosts_tab() if (!$loaded);
                   11100: 
1.844     albertel 11101: 	my ($lonid) = @_;
                   11102: 	return $hostdom{$lonid};
                   11103:     }
                   11104: 
1.841     albertel 11105:     sub all_domains {
1.852     albertel 11106: 	&load_hosts_tab() if (!$loaded);
                   11107: 
1.841     albertel 11108: 	my %seen;
                   11109: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11110: 	return @uniq;
                   11111:     }
1.1074    raeburn  11112: 
                   11113:     sub internet_dom {
                   11114:         &load_hosts_tab() if (!$loaded);
                   11115: 
                   11116:         my ($lonid) = @_;
                   11117:         return $internetdom{$lonid};
                   11118:     }
1.1107    raeburn  11119: 
                   11120:     sub is_LC_dns {
                   11121:         &load_hosts_tab() if (!$loaded);
                   11122: 
                   11123:         my ($hostname) = @_;
                   11124:         return exists($LC_dns_serv{$hostname});
                   11125:     }
                   11126: 
1.1       albertel 11127: }
                   11128: 
1.847     albertel 11129: { 
                   11130:     my %iphost;
1.856     albertel 11131:     my %name_to_ip;
                   11132:     my %lonid_to_ip;
1.869     albertel 11133: 
1.847     albertel 11134:     sub get_hosts_from_ip {
                   11135: 	my ($ip) = @_;
                   11136: 	my %iphosts = &get_iphost();
                   11137: 	if (ref($iphosts{$ip})) {
                   11138: 	    return @{$iphosts{$ip}};
                   11139: 	}
                   11140: 	return;
1.839     albertel 11141:     }
1.864     albertel 11142:     
                   11143:     sub reset_hosts_ip_info {
                   11144: 	undef(%iphost);
                   11145: 	undef(%name_to_ip);
                   11146: 	undef(%lonid_to_ip);
                   11147:     }
1.856     albertel 11148: 
                   11149:     sub get_host_ip {
                   11150: 	my ($lonid) = @_;
                   11151: 	if (exists($lonid_to_ip{$lonid})) {
                   11152: 	    return $lonid_to_ip{$lonid};
                   11153: 	}
                   11154: 	my $name=&hostname($lonid);
                   11155:    	my $ip = gethostbyname($name);
                   11156: 	return if (!$ip || length($ip) ne 4);
                   11157: 	$ip=inet_ntoa($ip);
                   11158: 	$name_to_ip{$name}   = $ip;
                   11159: 	$lonid_to_ip{$lonid} = $ip;
                   11160: 	return $ip;
                   11161:     }
1.847     albertel 11162:     
                   11163:     sub get_iphost {
1.869     albertel 11164: 	my ($ignore_cache) = @_;
1.894     albertel 11165: 
1.869     albertel 11166: 	if (!$ignore_cache) {
                   11167: 	    if (%iphost) {
                   11168: 		return %iphost;
                   11169: 	    }
                   11170: 	    my ($ip_info,$cached)=
                   11171: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11172: 	    if ($cached) {
                   11173: 		%iphost      = %{$ip_info->[0]};
                   11174: 		%name_to_ip  = %{$ip_info->[1]};
                   11175: 		%lonid_to_ip = %{$ip_info->[2]};
                   11176: 		return %iphost;
                   11177: 	    }
                   11178: 	}
1.894     albertel 11179: 
                   11180: 	# get yesterday's info for fallback
                   11181: 	my %old_name_to_ip;
                   11182: 	my ($ip_info,$cached)=
                   11183: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11184: 	if ($cached) {
                   11185: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11186: 	}
                   11187: 
1.888     albertel 11188: 	my %name_to_host = &all_names();
                   11189: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11190: 	    my $ip;
                   11191: 	    if (!exists($name_to_ip{$name})) {
                   11192: 		$ip = gethostbyname($name);
                   11193: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11194: 		    if (defined($old_name_to_ip{$name})) {
                   11195: 			$ip = $old_name_to_ip{$name};
                   11196: 			&logthis("Can't find $name defaulting to old $ip");
                   11197: 		    } else {
                   11198: 			&logthis("Name $name no IP found");
                   11199: 			next;
                   11200: 		    }
                   11201: 		} else {
                   11202: 		    $ip=inet_ntoa($ip);
1.847     albertel 11203: 		}
                   11204: 		$name_to_ip{$name} = $ip;
                   11205: 	    } else {
                   11206: 		$ip = $name_to_ip{$name};
1.653     albertel 11207: 	    }
1.888     albertel 11208: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11209: 		$lonid_to_ip{$id} = $ip;
                   11210: 	    }
                   11211: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11212: 	}
1.869     albertel 11213: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11214: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11215: 				      48*60*60);
1.869     albertel 11216: 
1.847     albertel 11217: 	return %iphost;
1.598     albertel 11218:     }
                   11219: 
1.992     raeburn  11220:     #
                   11221:     #  Given a DNS returns the loncapa host name for that DNS 
                   11222:     # 
                   11223:     sub host_from_dns {
                   11224:         my ($dns) = @_;
                   11225:         my @hosts;
                   11226:         my $ip;
                   11227: 
1.993     raeburn  11228:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11229:             $ip = $name_to_ip{$dns};
                   11230:         }
                   11231:         if (!$ip) {
                   11232:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11233:             if (length($ip) == 4) { 
                   11234: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11235:             }
                   11236:         }
                   11237:         if ($ip) {
                   11238: 	    @hosts = get_hosts_from_ip($ip);
                   11239: 	    return $hosts[0];
                   11240:         }
                   11241:         return undef;
1.986     foxr     11242:     }
1.992     raeburn  11243: 
1.1074    raeburn  11244:     sub get_internet_names {
                   11245:         my ($lonid) = @_;
                   11246:         return if ($lonid eq '');
                   11247:         my ($idnref,$cached)=
                   11248:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11249:         if ($cached) {
                   11250:             return $idnref;
                   11251:         }
                   11252:         my $ip = &get_host_ip($lonid);
                   11253:         my @hosts = &get_hosts_from_ip($ip);
                   11254:         my %iphost = &get_iphost();
                   11255:         my (@idns,%seen);
                   11256:         foreach my $id (@hosts) {
                   11257:             my $dom = &host_domain($id);
                   11258:             my $prim_id = &domain($dom,'primary');
                   11259:             my $prim_ip = &get_host_ip($prim_id);
                   11260:             next if ($seen{$prim_ip});
                   11261:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11262:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11263:                     my $intdom = &internet_dom($id);
                   11264:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11265:                         push(@idns,$intdom);
                   11266:                     }
                   11267:                 }
                   11268:             }
                   11269:             $seen{$prim_ip} = 1;
                   11270:         }
                   11271:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11272:     }
                   11273: 
1.986     foxr     11274: }
                   11275: 
1.1079    raeburn  11276: sub all_loncaparevs {
                   11277:     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);
                   11278: }
                   11279: 
1.862     albertel 11280: BEGIN {
                   11281: 
                   11282: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11283:     unless ($readit) {
                   11284: {
                   11285:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11286:     %perlvar = (%perlvar,%{$configvars});
                   11287: }
                   11288: 
                   11289: 
1.1       albertel 11290: # ------------------------------------------------------ Read spare server file
                   11291: {
1.448     albertel 11292:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11293: 
                   11294:     while (my $configline=<$config>) {
                   11295:        chomp($configline);
1.284     matthew  11296:        if ($configline) {
1.784     albertel 11297: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11298: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11299: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11300:        }
                   11301:     }
1.448     albertel 11302:     close($config);
1.1       albertel 11303: }
1.11      www      11304: # ------------------------------------------------------------ Read permissions
                   11305: {
1.448     albertel 11306:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11307: 
                   11308:     while (my $configline=<$config>) {
1.448     albertel 11309: 	chomp($configline);
                   11310: 	if ($configline) {
                   11311: 	    my ($role,$perm)=split(/ /,$configline);
                   11312: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11313: 	}
1.11      www      11314:     }
1.448     albertel 11315:     close($config);
1.11      www      11316: }
                   11317: 
                   11318: # -------------------------------------------- Read plain texts for permissions
                   11319: {
1.448     albertel 11320:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11321: 
                   11322:     while (my $configline=<$config>) {
1.448     albertel 11323: 	chomp($configline);
                   11324: 	if ($configline) {
1.742     raeburn  11325: 	    my ($short,@plain)=split(/:/,$configline);
                   11326:             %{$prp{$short}} = ();
                   11327: 	    if (@plain > 0) {
                   11328:                 $prp{$short}{'std'} = $plain[0];
                   11329:                 for (my $i=1; $i<@plain; $i++) {
                   11330:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11331:                 }
                   11332:             }
1.448     albertel 11333: 	}
1.135     www      11334:     }
1.448     albertel 11335:     close($config);
1.135     www      11336: }
                   11337: 
                   11338: # ---------------------------------------------------------- Read package table
                   11339: {
1.448     albertel 11340:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11341: 
                   11342:     while (my $configline=<$config>) {
1.483     albertel 11343: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11344: 	chomp($configline);
                   11345: 	my ($short,$plain)=split(/:/,$configline);
                   11346: 	my ($pack,$name)=split(/\&/,$short);
                   11347: 	if ($plain ne '') {
                   11348: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11349: 	    $packagetab{$short}=$plain; 
                   11350: 	}
1.11      www      11351:     }
1.448     albertel 11352:     close($config);
1.329     matthew  11353: }
                   11354: 
1.1073    raeburn  11355: # ---------------------------------------------------------- Read loncaparev table
                   11356: {
                   11357:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11358:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11359:             while (my $configline=<$config>) {
                   11360:                 chomp($configline);
                   11361:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11362:                 $loncaparevs{$hostid}=$loncaparev;
                   11363:             }
                   11364:             close($config);
                   11365:         }
                   11366:     }
                   11367: }
                   11368: 
1.1074    raeburn  11369: # ---------------------------------------------------------- Read serverhostID table
                   11370: {
                   11371:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11372:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11373:             while (my $configline=<$config>) {
                   11374:                 chomp($configline);
                   11375:                 my ($name,$id)=split(/:/,$configline);
                   11376:                 $serverhomeIDs{$name}=$id;
                   11377:             }
                   11378:             close($config);
                   11379:         }
                   11380:     }
                   11381: }
                   11382: 
1.1079    raeburn  11383: {
                   11384:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11385:     if (-e $file) {
                   11386:         my $parser = HTML::LCParser->new($file);
                   11387:         while (my $token = $parser->get_token()) {
                   11388:             if ($token->[0] eq 'S') {
                   11389:                 my $item = $token->[1];
                   11390:                 my $name = $token->[2]{'name'};
                   11391:                 my $value = $token->[2]{'value'};
                   11392:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11393:                     my $release = $parser->get_text();
                   11394:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11395:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11396:                 }
                   11397:             }
                   11398:         }
                   11399:     }
1.1073    raeburn  11400: }
                   11401: 
1.1138    raeburn  11402: # ---------------------------------------------------------- Read managers table
                   11403: {
                   11404:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11405:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11406:             while (my $configline=<$config>) {
                   11407:                 chomp($configline);
                   11408:                 next if ($configline =~ /^\#/);
                   11409:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11410:                     $managerstab{$configline} = 1;
                   11411:                 }
                   11412:             }
                   11413:             close($config);
                   11414:         }
                   11415:     }
                   11416: }
                   11417: 
1.329     matthew  11418: # ------------- set up temporary directory
                   11419: {
1.1117    foxr     11420:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11421: 
1.11      www      11422: }
                   11423: 
1.794     albertel 11424: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11425: 				'compress_threshold'=> 20_000,
                   11426:  			        });
1.185     www      11427: 
1.281     www      11428: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11429: $dumpcount=0;
1.958     www      11430: $locknum=0;
1.22      www      11431: 
1.163     harris41 11432: &logtouch();
1.672     albertel 11433: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11434: $readit=1;
1.564     albertel 11435:     {
                   11436: 	use integer;
                   11437: 	my $test=(2**32)+1;
1.568     albertel 11438: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11439: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11440:     }
1.195     www      11441: }
1.1       albertel 11442: }
1.179     www      11443: 
1.1       albertel 11444: 1;
1.191     harris41 11445: __END__
                   11446: 
1.243     albertel 11447: =pod
                   11448: 
1.191     harris41 11449: =head1 NAME
                   11450: 
1.243     albertel 11451: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11452: 
                   11453: =head1 SYNOPSIS
                   11454: 
1.243     albertel 11455: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11456: 
                   11457:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11458: 
1.243     albertel 11459: Common parameters:
                   11460: 
                   11461: =over 4
                   11462: 
                   11463: =item *
                   11464: 
                   11465: $uname : an internal username (if $cname expecting a course Id specifically)
                   11466: 
                   11467: =item *
                   11468: 
                   11469: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11470: 
                   11471: =item *
                   11472: 
                   11473: $symb : a resource instance identifier
                   11474: 
                   11475: =item *
                   11476: 
                   11477: $namespace : the name of a .db file that contains the data needed or
                   11478: being set.
                   11479: 
                   11480: =back
                   11481: 
1.394     bowersj2 11482: =head1 OVERVIEW
1.191     harris41 11483: 
1.394     bowersj2 11484: lonnet provides subroutines which interact with the
                   11485: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11486: about classes, users, and resources.
1.243     albertel 11487: 
                   11488: For many of these objects you can also use this to store data about
                   11489: them or modify them in various ways.
1.191     harris41 11490: 
1.394     bowersj2 11491: =head2 Symbs
1.191     harris41 11492: 
1.394     bowersj2 11493: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11494: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11495: map, the resource number of the resource in the map, and the URL of
                   11496: the resource itself. The latter is somewhat redundant, but might help
                   11497: if maps change.
                   11498: 
                   11499: An example is
                   11500: 
                   11501:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11502: 
                   11503: The respective map entry is
                   11504: 
                   11505:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11506:   title="Problem 2">
                   11507:  </resource>
                   11508: 
                   11509: Symbs are used by the random number generator, as well as to store and
                   11510: restore data specific to a certain instance of for example a problem.
                   11511: 
                   11512: =head2 Storing And Retrieving Data
                   11513: 
                   11514: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11515: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11516: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11517: is is the non-critical message twin of cstore. These functions are for
                   11518: handlers to store a perl hash to a user's permanent data space in an
                   11519: easy manner, and to retrieve it again on another call. It is expected
                   11520: that a handler would use this once at the beginning to retrieve data,
                   11521: and then again once at the end to send only the new data back.
                   11522: 
                   11523: The data is stored in the user's data directory on the user's
                   11524: homeserver under the ID of the course.
                   11525: 
                   11526: The hash that is returned by restore will have all of the previous
                   11527: value for all of the elements of the hash.
                   11528: 
                   11529: Example:
                   11530: 
                   11531:  #creating a hash
                   11532:  my %hash;
                   11533:  $hash{'foo'}='bar';
                   11534: 
                   11535:  #storing it
                   11536:  &Apache::lonnet::cstore(\%hash);
                   11537: 
                   11538:  #changing a value
                   11539:  $hash{'foo'}='notbar';
                   11540: 
                   11541:  #adding a new value
                   11542:  $hash{'bar'}='foo';
                   11543:  &Apache::lonnet::cstore(\%hash);
                   11544: 
                   11545:  #retrieving the hash
                   11546:  my %history=&Apache::lonnet::restore();
                   11547: 
                   11548:  #print the hash
                   11549:  foreach my $key (sort(keys(%history))) {
                   11550:    print("\%history{$key} = $history{$key}");
                   11551:  }
                   11552: 
                   11553: Will print out:
1.191     harris41 11554: 
1.394     bowersj2 11555:  %history{1:foo} = bar
                   11556:  %history{1:keys} = foo:timestamp
                   11557:  %history{1:timestamp} = 990455579
                   11558:  %history{2:bar} = foo
                   11559:  %history{2:foo} = notbar
                   11560:  %history{2:keys} = foo:bar:timestamp
                   11561:  %history{2:timestamp} = 990455580
                   11562:  %history{bar} = foo
                   11563:  %history{foo} = notbar
                   11564:  %history{timestamp} = 990455580
                   11565:  %history{version} = 2
                   11566: 
                   11567: Note that the special hash entries C<keys>, C<version> and
                   11568: C<timestamp> were added to the hash. C<version> will be equal to the
                   11569: total number of versions of the data that have been stored. The
                   11570: C<timestamp> attribute will be the UNIX time the hash was
                   11571: stored. C<keys> is available in every historical section to list which
                   11572: keys were added or changed at a specific historical revision of a
                   11573: hash.
                   11574: 
                   11575: B<Warning>: do not store the hash that restore returns directly. This
                   11576: will cause a mess since it will restore the historical keys as if the
                   11577: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11578: 
1.394     bowersj2 11579: Calling convention:
1.191     harris41 11580: 
1.394     bowersj2 11581:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11582:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11583: 
1.394     bowersj2 11584: For more detailed information, see lonnet specific documentation.
1.191     harris41 11585: 
1.394     bowersj2 11586: =head1 RETURN MESSAGES
1.191     harris41 11587: 
1.394     bowersj2 11588: =over 4
1.191     harris41 11589: 
1.394     bowersj2 11590: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11591: 
1.394     bowersj2 11592: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11593: when the connection is brought back up
1.191     harris41 11594: 
1.394     bowersj2 11595: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11596: for later delivery
1.191     harris41 11597: 
1.967     bisitz   11598: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11599: 
1.394     bowersj2 11600: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11601: that was requested
1.191     harris41 11602: 
1.243     albertel 11603: =back
1.191     harris41 11604: 
1.243     albertel 11605: =head1 PUBLIC SUBROUTINES
1.191     harris41 11606: 
1.243     albertel 11607: =head2 Session Environment Functions
1.191     harris41 11608: 
1.243     albertel 11609: =over 4
1.191     harris41 11610: 
1.394     bowersj2 11611: =item * 
                   11612: X<appenv()>
1.949     raeburn  11613: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11614: the user envirnoment file, and will be restored for each access this
1.620     albertel 11615: user makes during this session, also modifies the %env for the current
1.949     raeburn  11616: process. Optional rolesarrayref - if defined contains a reference to an array
                   11617: of roles which are exempt from the restriction on modifying user.role entries 
                   11618: in the user's environment.db and in %env.    
1.191     harris41 11619: 
                   11620: =item *
1.394     bowersj2 11621: X<delenv()>
1.987     raeburn  11622: B<delenv($delthis,$regexp)>: removes all items from the session
                   11623: environment file that begin with $delthis. If the 
                   11624: optional second arg - $regexp - is true, $delthis is treated as a 
                   11625: regular expression, otherwise \Q$delthis\E is used. 
                   11626: The values are also deleted from the current processes %env.
1.191     harris41 11627: 
1.795     albertel 11628: =item * get_env_multiple($name) 
                   11629: 
                   11630: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11631: values may be defined and end up as an array ref.
                   11632: 
                   11633: returns an array of values
                   11634: 
1.243     albertel 11635: =back
                   11636: 
                   11637: =head2 User Information
1.191     harris41 11638: 
1.243     albertel 11639: =over 4
1.191     harris41 11640: 
                   11641: =item *
1.394     bowersj2 11642: X<queryauthenticate()>
                   11643: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11644: authentication scheme
                   11645: 
                   11646: =item *
1.394     bowersj2 11647: X<authenticate()>
1.1073    raeburn  11648: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11649: authenticate user from domain's lib servers (first use the current
                   11650: one). C<$upass> should be the users password.
1.1073    raeburn  11651: $checkdefauth is optional (value is 1 if a check should be made to
                   11652:    authenticate user using default authentication method, and allow
                   11653:    account creation if username does not have account in the domain).
                   11654: $clientcancheckhost is optional (value is 1 if checking whether the
                   11655:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11656: 
                   11657: =item *
1.394     bowersj2 11658: X<homeserver()>
                   11659: B<homeserver($uname,$udom)>: find the server which has
                   11660: the user's directory and files (there must be only one), this caches
                   11661: the answer, and also caches if there is a borken connection.
1.191     harris41 11662: 
                   11663: =item *
1.394     bowersj2 11664: X<idget()>
                   11665: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11666: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11667: username, and only 1 username per ID in a specific domain) (returns
                   11668: hash: id=>name,id=>name)
1.191     harris41 11669: 
                   11670: =item *
1.394     bowersj2 11671: X<idrget()>
                   11672: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11673: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11674: 
                   11675: =item *
1.394     bowersj2 11676: X<idput()>
                   11677: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11678: 
                   11679: =item *
1.394     bowersj2 11680: X<rolesinit()>
1.1169    droeschl 11681: B<rolesinit($udom,$username)>: get user privileges.
                   11682: returns user role, first access and timer interval hashes
1.243     albertel 11683: 
                   11684: =item *
1.1171    droeschl 11685: X<privileged()>
                   11686: B<privileged($username,$domain)>: returns a true if user has a
                   11687: privileged and active role (i.e. su or dc), false otherwise.
                   11688: 
                   11689: =item *
1.551     albertel 11690: X<getsection()>
                   11691: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11692: course $cname, return section name/number or '' for "not in course"
                   11693: and '-1' for "no section"
                   11694: 
                   11695: =item *
1.394     bowersj2 11696: X<userenvironment()>
                   11697: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11698: passed in @what from the requested user's environment, returns a hash
                   11699: 
1.858     raeburn  11700: =item * 
                   11701: X<userlog_query()>
1.859     albertel 11702: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11703: activity.log file. %filters defines filters applied when parsing the
                   11704: log file. These can be start or end timestamps, or the type of action
                   11705: - log to look for Login or Logout events, check for Checkin or
                   11706: Checkout, role for role selection. The response is in the form
                   11707: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11708: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11709: 
1.243     albertel 11710: =back
                   11711: 
                   11712: =head2 User Roles
                   11713: 
                   11714: =over 4
                   11715: 
                   11716: =item *
                   11717: 
1.810     raeburn  11718: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11719:  F: full access
                   11720:  U,I,K: authentication modes (cxx only)
                   11721:  '': forbidden
                   11722:  1: user needs to choose course
                   11723:  2: browse allowed
1.766     albertel 11724:  A: passphrase authentication needed
1.243     albertel 11725: 
                   11726: =item *
                   11727: 
                   11728: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11729: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11730: and course level
                   11731: 
                   11732: =item *
                   11733: 
1.988     raeburn  11734: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11735: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11736: $type is Course (default) or Community.
1.988     raeburn  11737: If $forcedefault evaluates to true, text returned will be default 
                   11738: text for $type. Otherwise, if this is a course, the text returned 
                   11739: will be a custom name for the role (if defined in the course's 
                   11740: environment).  If no custom name is defined the default is returned.
                   11741:    
1.832     raeburn  11742: =item *
                   11743: 
1.935     raeburn  11744: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11745: All arguments are optional. Returns a hash of a roles, either for
                   11746: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11747: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11748: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11749: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11750: For each key, value is set to colon-separated start and end times for
                   11751: the role.  If no username and domain are specified, will default to
1.934     raeburn  11752: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11753: of role statuses (active, future or previous), roles 
                   11754: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11755: to restrict the list of roles reported. If no array ref is 
                   11756: provided for types, will default to return only active roles.
1.834     albertel 11757: 
1.243     albertel 11758: =back
                   11759: 
                   11760: =head2 User Modification
                   11761: 
                   11762: =over 4
                   11763: 
                   11764: =item *
                   11765: 
1.957     raeburn  11766: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11767: user for the level given by URL.  Optional start and end dates (leave empty
                   11768: string or zero for "no date")
1.191     harris41 11769: 
                   11770: =item *
                   11771: 
1.243     albertel 11772: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11773: change a users, password, possible return values are: ok,
                   11774: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11775: refused
1.191     harris41 11776: 
                   11777: =item *
                   11778: 
1.243     albertel 11779: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11780: 
                   11781: =item *
                   11782: 
1.1058    raeburn  11783: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11784:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11785: 
                   11786: will update user information (firstname,middlename,lastname,generation,
                   11787: permanentemail), and if forceid is true, student/employee ID also.
                   11788: A user's institutional affiliation(s) can also be updated.
                   11789: User information fields will not be overwritten with empty entries 
                   11790: unless the field is included in the $candelete array reference.
                   11791: This array is included when a single user is modified via "Manage Users",
                   11792: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11793: 
                   11794: =item *
                   11795: 
1.286     matthew  11796: modifystudent
                   11797: 
1.957     raeburn  11798: modify a student's enrollment and identification information.
1.286     matthew  11799: The course id is resolved based on the current users environment.  
                   11800: This means the envoking user must be a course coordinator or otherwise
                   11801: associated with a course.
                   11802: 
1.297     matthew  11803: This call is essentially a wrapper for lonnet::modifyuser and
                   11804: lonnet::modify_student_enrollment
1.286     matthew  11805: 
                   11806: Inputs: 
                   11807: 
                   11808: =over 4
                   11809: 
1.957     raeburn  11810: =item B<$udom> Student's loncapa domain
1.286     matthew  11811: 
1.957     raeburn  11812: =item B<$uname> Student's loncapa login name
1.286     matthew  11813: 
1.964     bisitz   11814: =item B<$uid> Student/Employee ID
1.286     matthew  11815: 
1.957     raeburn  11816: =item B<$umode> Student's authentication mode
1.286     matthew  11817: 
1.957     raeburn  11818: =item B<$upass> Student's password
1.286     matthew  11819: 
1.957     raeburn  11820: =item B<$first> Student's first name
1.286     matthew  11821: 
1.957     raeburn  11822: =item B<$middle> Student's middle name
1.286     matthew  11823: 
1.957     raeburn  11824: =item B<$last> Student's last name
1.286     matthew  11825: 
1.957     raeburn  11826: =item B<$gene> Student's generation
1.286     matthew  11827: 
1.957     raeburn  11828: =item B<$usec> Student's section in course
1.286     matthew  11829: 
                   11830: =item B<$end> Unix time of the roles expiration
                   11831: 
                   11832: =item B<$start> Unix time of the roles start date
                   11833: 
                   11834: =item B<$forceid> If defined, allow $uid to be changed
                   11835: 
                   11836: =item B<$desiredhome> server to use as home server for student
                   11837: 
1.957     raeburn  11838: =item B<$email> Student's permanent e-mail address
                   11839: 
                   11840: =item B<$type> Type of enrollment (auto or manual)
                   11841: 
1.963     raeburn  11842: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11843: 
                   11844: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11845: 
1.963     raeburn  11846: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11847: 
1.963     raeburn  11848: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11849: 
1.963     raeburn  11850: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11851: 
1.286     matthew  11852: =back
1.297     matthew  11853: 
                   11854: =item *
                   11855: 
                   11856: modify_student_enrollment
                   11857: 
                   11858: Change a students enrollment status in a class.  The environment variable
                   11859: 'role.request.course' must be defined for this function to proceed.
                   11860: 
                   11861: Inputs:
                   11862: 
                   11863: =over 4
                   11864: 
                   11865: =item $udom, students domain
                   11866: 
                   11867: =item $uname, students name
                   11868: 
                   11869: =item $uid, students user id
                   11870: 
                   11871: =item $first, students first name
                   11872: 
                   11873: =item $middle
                   11874: 
                   11875: =item $last
                   11876: 
                   11877: =item $gene
                   11878: 
                   11879: =item $usec
                   11880: 
                   11881: =item $end
                   11882: 
                   11883: =item $start
                   11884: 
1.957     raeburn  11885: =item $type
                   11886: 
                   11887: =item $locktype
                   11888: 
                   11889: =item $cid
                   11890: 
                   11891: =item $selfenroll
                   11892: 
                   11893: =item $context
                   11894: 
1.297     matthew  11895: =back
                   11896: 
1.191     harris41 11897: 
                   11898: =item *
                   11899: 
1.243     albertel 11900: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11901: custom role; give a custom role to a user for the level given by URL.  Specify
                   11902: name and domain of role author, and role name
1.191     harris41 11903: 
                   11904: =item *
                   11905: 
1.243     albertel 11906: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11907: 
                   11908: =item *
                   11909: 
1.243     albertel 11910: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11911: 
                   11912: =back
                   11913: 
                   11914: =head2 Course Infomation
                   11915: 
                   11916: =over 4
1.191     harris41 11917: 
                   11918: =item *
                   11919: 
1.1118    foxr     11920: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11921: specified course id, including all environment settings for the
                   11922: course, the description of the course will be in the hash under the
                   11923: key 'description'
1.191     harris41 11924: 
1.1118    foxr     11925: $options is an optional parameter that if supplied is a hash reference that controls
                   11926: what how this function works.  It has the following key/values:
                   11927: 
                   11928: =over 4
                   11929: 
                   11930: =item freshen_cache
                   11931: 
                   11932: If defined, and the environment cache for the course is valid, it is 
                   11933: returned in the returned hash.
                   11934: 
                   11935: =item one_time
                   11936: 
                   11937: If defined, the last cache time is set to _now_
                   11938: 
                   11939: =item user
                   11940: 
                   11941: If defined, the supplied username is used instead of the current user.
                   11942: 
                   11943: 
                   11944: =back
                   11945: 
1.191     harris41 11946: =item *
                   11947: 
1.624     albertel 11948: resdata($name,$domain,$type,@which) : request for current parameter
                   11949: setting for a specific $type, where $type is either 'course' or 'user',
                   11950: @what should be a list of parameters to ask about. This routine caches
                   11951: answers for 5 minutes.
1.243     albertel 11952: 
1.877     foxr     11953: =item *
                   11954: 
                   11955: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11956: data base, returning a hash that is keyed by the resource name and has
                   11957: values that are the resource value.  I believe that the timestamps and
                   11958: versions are also returned.
                   11959: 
                   11960: 
1.243     albertel 11961: =back
                   11962: 
                   11963: =head2 Course Modification
                   11964: 
                   11965: =over 4
1.191     harris41 11966: 
                   11967: =item *
                   11968: 
1.243     albertel 11969: writecoursepref($courseid,%prefs) : write preferences (environment
                   11970: database) for a course
1.191     harris41 11971: 
                   11972: =item *
                   11973: 
1.1011    raeburn  11974: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11975: 
                   11976: =item *
                   11977: 
1.1038    raeburn  11978: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11979: 
1.1167    droeschl 11980: =item *
                   11981: 
                   11982: is_course($courseid), is_course($cdom, $cnum)
                   11983: 
                   11984: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   11985: two component version $cdom, $cnum. It checks if the specified course exists.
                   11986: 
                   11987: Returns:
                   11988:     undef if the course doesn't exist, otherwise
                   11989:     in scalar context the combined courseid.
                   11990:     in list context the two components of the course identifier, domain and 
                   11991:     courseid.    
                   11992: 
1.243     albertel 11993: =back
                   11994: 
                   11995: =head2 Resource Subroutines
                   11996: 
                   11997: =over 4
1.191     harris41 11998: 
                   11999: =item *
                   12000: 
1.243     albertel 12001: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12002: 
                   12003: =item *
                   12004: 
1.243     albertel 12005: repcopy($filename) : subscribes to the requested file, and attempts to
                   12006: replicate from the owning library server, Might return
1.607     raeburn  12007: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12008: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12009: resource. Expects the local filesystem pathname
                   12010: (/home/httpd/html/res/....)
                   12011: 
                   12012: =back
                   12013: 
                   12014: =head2 Resource Information
                   12015: 
                   12016: =over 4
1.191     harris41 12017: 
                   12018: =item *
                   12019: 
1.243     albertel 12020: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12021: a vairety of different possible values, $varname should be a request
                   12022: string, and the other parameters can be used to specify who and what
                   12023: one is asking about.
                   12024: 
                   12025: Possible values for $varname are environment.lastname (or other item
                   12026: from the envirnment hash), user.name (or someother aspect about the
                   12027: user), resource.0.maxtries (or some other part and parameter of a
                   12028: resource)
1.204     albertel 12029: 
                   12030: =item *
                   12031: 
1.243     albertel 12032: directcondval($number) : get current value of a condition; reads from a state
                   12033: string
1.204     albertel 12034: 
                   12035: =item *
                   12036: 
1.243     albertel 12037: condval($condidx) : value of condition index based on state
1.204     albertel 12038: 
                   12039: =item *
                   12040: 
1.243     albertel 12041: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12042: resource's metadata, $what should be either a specific key, or either
                   12043: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12044: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12045: 
                   12046: this function automatically caches all requests
1.191     harris41 12047: 
                   12048: =item *
                   12049: 
1.243     albertel 12050: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12051: network of library servers; returns file handle of where SQL and regex results
                   12052: will be stored for query
1.191     harris41 12053: 
                   12054: =item *
                   12055: 
1.243     albertel 12056: symbread($filename) : return symbolic list entry (filename argument optional);
                   12057: returns the data handle
1.191     harris41 12058: 
                   12059: =item *
                   12060: 
1.243     albertel 12061: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 12062: a possible symb for the URL in $thisfn, and if is an encryypted
                   12063: resource that the user accessed using /enc/ returns a 1 on success, 0
                   12064: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 12065: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 12066: 
1.191     harris41 12067: 
                   12068: =item *
                   12069: 
1.243     albertel 12070: symbclean($symb) : removes versions numbers from a symb, returns the
                   12071: cleaned symb
1.191     harris41 12072: 
                   12073: =item *
                   12074: 
1.243     albertel 12075: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12076: course map, user must be in a course for it to work.
1.191     harris41 12077: 
                   12078: =item *
                   12079: 
1.243     albertel 12080: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12081: 
                   12082: =item *
                   12083: 
1.243     albertel 12084: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12085: a random seed, all arguments are optional, if they aren't sent it uses the
                   12086: environment to derive them. Note: if symb isn't sent and it can't get one
                   12087: from &symbread it will use the current time as its return value
1.191     harris41 12088: 
                   12089: =item *
                   12090: 
1.243     albertel 12091: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12092: unfakeable, receipt
1.191     harris41 12093: 
                   12094: =item *
                   12095: 
1.620     albertel 12096: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12097: 
                   12098: =item *
                   12099: 
1.243     albertel 12100: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12101: 
                   12102: =item *
                   12103: 
1.243     albertel 12104: 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 12105: 
                   12106: =item *
                   12107: 
1.243     albertel 12108: 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 12109: 
                   12110: =item *
                   12111: 
1.243     albertel 12112: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12113: 
                   12114: =item *
                   12115: 
1.243     albertel 12116: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12117: forcing spreadsheet to reevaluate the resource scores next time.
                   12118: 
                   12119: =back
                   12120: 
                   12121: =head2 Storing/Retreiving Data
                   12122: 
                   12123: =over 4
1.191     harris41 12124: 
                   12125: =item *
                   12126: 
1.243     albertel 12127: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12128: for this url; hashref needs to be given and should be a \%hashname; the
                   12129: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12130: be derived from the env
1.191     harris41 12131: 
                   12132: =item *
                   12133: 
1.243     albertel 12134: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12135: uses critical subroutine
1.191     harris41 12136: 
                   12137: =item *
                   12138: 
1.243     albertel 12139: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12140: all args are optional
1.191     harris41 12141: 
                   12142: =item *
                   12143: 
1.717     albertel 12144: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12145: dumps the complete (or key matching regexp) namespace into a hash
                   12146: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12147: normally &store()ed into
                   12148: 
                   12149: $range should be either an integer '100' (give me the first 100
                   12150:                                            matching records)
                   12151:               or be  two integers sperated by a - with no spaces
                   12152:                  '30-50' (give me the 30th through the 50th matching
                   12153:                           records)
                   12154: 
                   12155: 
                   12156: =item *
                   12157: 
                   12158: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12159: replaces a &store() version of data with a replacement set of data
                   12160: for a particular resource in a namespace passed in the $storehash hash 
                   12161: reference
                   12162: 
                   12163: =item *
                   12164: 
1.243     albertel 12165: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12166: works very similar to store/cstore, but all data is stored in a
                   12167: temporary location and can be reset using tmpreset, $storehash should
                   12168: be a hash reference, returns nothing on success
1.191     harris41 12169: 
                   12170: =item *
                   12171: 
1.243     albertel 12172: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12173: similar to restore, but all data is stored in a temporary location and
                   12174: can be reset using tmpreset. Returns a hash of values on success,
                   12175: error string otherwise.
1.191     harris41 12176: 
                   12177: =item *
                   12178: 
1.243     albertel 12179: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12180: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12181: 
                   12182: =item *
                   12183: 
1.243     albertel 12184: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12185: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12186: 
                   12187: =item *
                   12188: 
1.243     albertel 12189: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12190: namesp ($udom and $uname are optional)
1.191     harris41 12191: 
                   12192: =item *
                   12193: 
1.702     albertel 12194: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12195: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12196: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12197: 
1.702     albertel 12198: $range should be either an integer '100' (give me the first 100
                   12199:                                            matching records)
                   12200:               or be  two integers sperated by a - with no spaces
                   12201:                  '30-50' (give me the 30th through the 50th matching
                   12202:                           records)
1.449     matthew  12203: =item *
                   12204: 
                   12205: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12206: $store can be a scalar, an array reference, or if the amount to be 
                   12207: incremented is > 1, a hash reference.
                   12208: 
                   12209: ($udom and $uname are optional)
1.191     harris41 12210: 
                   12211: =item *
                   12212: 
1.243     albertel 12213: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12214: ($udom and $uname are optional)
1.191     harris41 12215: 
                   12216: =item *
                   12217: 
1.243     albertel 12218: cput($namespace,$storehash,$udom,$uname) : critical put
                   12219: ($udom and $uname are optional)
1.191     harris41 12220: 
                   12221: =item *
                   12222: 
1.748     albertel 12223: newput($namespace,$storehash,$udom,$uname) :
                   12224: 
                   12225: Attempts to store the items in the $storehash, but only if they don't
                   12226: currently exist, if this succeeds you can be certain that you have 
                   12227: successfully created a new key value pair in the $namespace db.
                   12228: 
                   12229: 
                   12230: Args:
                   12231:  $namespace: name of database to store values to
                   12232:  $storehash: hashref to store to the db
                   12233:  $udom: (optional) domain of user containing the db
                   12234:  $uname: (optional) name of user caontaining the db
                   12235: 
                   12236: Returns:
                   12237:  'ok' -> succeeded in storing all keys of $storehash
                   12238:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12239:                         least <key> already existed in the db (other
                   12240:                         requested keys may also already exist)
1.967     bisitz   12241:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12242:  'con_lost' -> unable to contact request server
                   12243:  'refused' -> action was not allowed by remote machine
                   12244: 
                   12245: 
                   12246: =item *
                   12247: 
1.243     albertel 12248: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12249: reference filled in from namesp (encrypts the return communication)
                   12250: ($udom and $uname are optional)
1.191     harris41 12251: 
                   12252: =item *
                   12253: 
1.243     albertel 12254: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12255: critical subroutine
                   12256: 
1.806     raeburn  12257: =item *
                   12258: 
1.860     raeburn  12259: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12260: array reference filled in from namespace found in domain level on either
                   12261: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12262: 
                   12263: =item *
                   12264: 
1.860     raeburn  12265: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12266: domain level either on specified domain server ($uhome) or primary domain 
                   12267: server ($udom and $uhome are optional)
1.806     raeburn  12268: 
1.943     raeburn  12269: =item * 
                   12270: 
                   12271: get_domain_defaults($target_domain) : returns hash with defaults for
                   12272: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12273: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12274: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12275: Values are retrieved from cache (if current), or from domain's configuration.db
                   12276: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12277: or lonTabs/domain.tab. 
                   12278: 
                   12279: %domdefaults = &get_auth_defaults($target_domain);
                   12280: 
1.243     albertel 12281: =back
                   12282: 
                   12283: =head2 Network Status Functions
                   12284: 
                   12285: =over 4
1.191     harris41 12286: 
                   12287: =item *
                   12288: 
1.1137    raeburn  12289: dirlist() : return directory list based on URI (first arg).
                   12290: 
                   12291: Inputs: 1 required, 5 optional.
                   12292: 
                   12293: =over
                   12294: 
                   12295: =item 
                   12296: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12297: 
                   12298: =item
                   12299: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12300: 
                   12301: =item
                   12302: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12303: 
                   12304: =item
                   12305: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12306: 
                   12307: =item
                   12308: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12309: 
                   12310: =item 
                   12311: $alternateRoot - path to prepend in place of path from $uri.
                   12312: 
                   12313: =back
                   12314: 
                   12315: Returns: Array of up to two items.
                   12316: 
                   12317: =over
                   12318: 
                   12319: a reference to an array of files/subdirectories
                   12320: 
                   12321: =over
                   12322: 
                   12323: Each element in the array of files/subdirectories is a & separated list of
                   12324: item name and the result of running stat on the item.  If dirlist was requested
                   12325: for a file instead of a directory, the item name will be ''. For a directory 
                   12326: listing, if the item is a metadata file, the element will end &N&M 
                   12327: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12328: default copyright set (1).  
                   12329: 
                   12330: =back
                   12331: 
                   12332: a scalar containing error condition (if encountered).
                   12333: 
                   12334: =over
                   12335: 
                   12336: =item 
                   12337: no_host (no homeserver identified for $username:$domain).
                   12338: 
                   12339: =item 
                   12340: no_such_host (server contacted for listing not identified as valid host).
                   12341: 
                   12342: =item 
                   12343: con_lost (connection to remote server failed).
                   12344: 
                   12345: =item 
                   12346: refused (invalid $username:$domain received on lond side).
                   12347: 
                   12348: =item 
                   12349: no_such_dir (directory at specified path on lond side does not exist). 
                   12350: 
                   12351: =item 
                   12352: empty (directory at specified path on lond side is empty).
                   12353: 
                   12354: =over
                   12355: 
                   12356: This is currently not encountered because the &ls3, &ls2, 
                   12357: &ls (_handler) routines on the lond side do not filter out
                   12358: . and .. from a directory listing. 
                   12359: 
                   12360: =back
                   12361: 
                   12362: =back
                   12363: 
                   12364: =back
1.191     harris41 12365: 
                   12366: =item *
                   12367: 
1.243     albertel 12368: spareserver() : find server with least workload from spare.tab
                   12369: 
1.986     foxr     12370: 
                   12371: =item *
                   12372: 
                   12373: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12374: if there is no corresponding loncapa host.
                   12375: 
1.243     albertel 12376: =back
                   12377: 
1.986     foxr     12378: 
1.243     albertel 12379: =head2 Apache Request
                   12380: 
                   12381: =over 4
1.191     harris41 12382: 
                   12383: =item *
                   12384: 
1.243     albertel 12385: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12386: localhost, posts hash
                   12387: 
                   12388: =back
                   12389: 
                   12390: =head2 Data to String to Data
                   12391: 
                   12392: =over 4
1.191     harris41 12393: 
                   12394: =item *
                   12395: 
1.243     albertel 12396: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12397: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12398: 
                   12399: =item *
                   12400: 
1.243     albertel 12401: hashref2str($hashref) : convert a hashref into a string complete with
                   12402: escaping and '=' and '&' separators, supports elements that are
                   12403: arrayrefs and hashrefs
1.191     harris41 12404: 
                   12405: =item *
                   12406: 
1.243     albertel 12407: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12408: with escaping and '&' separators, supports elements that are arrayrefs
                   12409: and hashrefs
1.191     harris41 12410: 
                   12411: =item *
                   12412: 
1.243     albertel 12413: str2hash($string) : convert string to hash using unescaping and
                   12414: splitting on '=' and '&', supports elements that are arrayrefs and
                   12415: hashrefs
1.191     harris41 12416: 
                   12417: =item *
                   12418: 
1.243     albertel 12419: str2array($string) : convert string to hash using unescaping and
                   12420: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12421: 
                   12422: =back
                   12423: 
                   12424: =head2 Logging Routines
                   12425: 
                   12426: 
                   12427: These routines allow one to make log messages in the lonnet.log and
                   12428: lonnet.perm logfiles.
1.191     harris41 12429: 
1.1119    foxr     12430: =over 4
                   12431: 
1.191     harris41 12432: =item *
                   12433: 
1.243     albertel 12434: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12435: 
                   12436: =item *
                   12437: 
1.243     albertel 12438: logthis() : append message to the normal lonnet.log file, it gets
                   12439: preiodically rolled over and deleted.
1.191     harris41 12440: 
                   12441: =item *
                   12442: 
1.243     albertel 12443: logperm() : append a permanent message to lonnet.perm.log, this log
                   12444: file never gets deleted by any automated portion of the system, only
                   12445: messages of critical importance should go in here.
                   12446: 
1.1119    foxr     12447: 
1.243     albertel 12448: =back
                   12449: 
                   12450: =head2 General File Helper Routines
                   12451: 
                   12452: =over 4
1.191     harris41 12453: 
                   12454: =item *
                   12455: 
1.481     raeburn  12456: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12457: (a) files in /uploaded
                   12458:   (i) If a local copy of the file exists - 
                   12459:       compares modification date of local copy with last-modified date for 
                   12460:       definitive version stored on home server for course. If local copy is 
                   12461:       stale, requests a new version from the home server and stores it. 
                   12462:       If the original has been removed from the home server, then local copy 
                   12463:       is unlinked.
                   12464:   (ii) If local copy does not exist -
                   12465:       requests the file from the home server and stores it. 
                   12466:   
                   12467:   If $caller is 'uploadrep':  
                   12468:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12469:     for request for files originally uploaded via DOCS. 
                   12470:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12471:   
                   12472:   Otherwise:
                   12473:      This indicates a call from the content generation phase of the request.
                   12474:      -  returns the entire contents of the file or -1.
                   12475:      
                   12476: (b) files in /res
                   12477:    - returns the entire contents of a file or -1; 
                   12478:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12479: 
1.712     albertel 12480: 
                   12481: =item *
                   12482: 
                   12483: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12484:                   reference
                   12485: 
                   12486: returns either a stat() list of data about the file or an empty list
                   12487: if the file doesn't exist or couldn't find out about it (connection
                   12488: problems or user unknown)
                   12489: 
1.191     harris41 12490: =item *
                   12491: 
1.243     albertel 12492: filelocation($dir,$file) : returns file system location of a file
                   12493: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12494: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12495: and a file of ../bob will become /a/bob)
1.191     harris41 12496: 
                   12497: =item *
                   12498: 
                   12499: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12500: filelocation except for hrefs
                   12501: 
                   12502: =item *
                   12503: 
                   12504: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12505: 
1.243     albertel 12506: =back
                   12507: 
1.608     albertel 12508: =head2 Usererfile file routines (/uploaded*)
                   12509: 
                   12510: =over 4
                   12511: 
                   12512: =item *
                   12513: 
                   12514: userfileupload(): main rotine for putting a file in a user or course's
                   12515:                   filespace, arguments are,
                   12516: 
1.620     albertel 12517:  formname - required - this is the name of the element in $env where the
1.608     albertel 12518:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12519:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12520:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12521:  context - if coursedoc, store the file in the course of the active role
                   12522:              of the current user; 
                   12523:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12524:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12525:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12526:          if undefined, it will be placed in "unknown"
                   12527: 
                   12528:  (This routine calls clean_filename() to remove any dangerous
                   12529:  characters from the filename, and then calls finuserfileupload() to
                   12530:  complete the transaction)
                   12531: 
                   12532:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12533:  and /adm/notfound.html if unsuccessful
                   12534: 
                   12535: =item *
                   12536: 
                   12537: clean_filename(): routine for cleaing a filename up for storage in
                   12538:                  userfile space, argument is:
                   12539: 
                   12540:  filename - proposed filename
                   12541: 
                   12542: returns: the new clean filename
                   12543: 
                   12544: =item *
                   12545: 
1.1090    raeburn  12546: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12547: userspace, probably shouldn't be called directly
                   12548: 
                   12549:   docuname: username or courseid of destination for the file
                   12550:   docudom: domain of user/course of destination for the file
                   12551:   formname: same as for userfileupload()
1.1090    raeburn  12552:   fname: filename (including subdirectories) for the file
                   12553:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12554:   allfiles: reference to hash used to store objects found by parser
                   12555:   codebase: reference to hash used for codebases of java objects found by parser
                   12556:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12557:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12558:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12559:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12560:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12561:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12562:   mimetype: reference to scalar to accommodate mime type determined
                   12563:             from File::MMagic if $parser = parse.
1.608     albertel 12564: 
                   12565:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12566:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12567:  was 'overwrite').
                   12568:  
1.608     albertel 12569: 
                   12570: =item *
                   12571: 
                   12572: renameuserfile(): renames an existing userfile to a new name
                   12573: 
                   12574:   Args:
                   12575:    docuname: username or courseid of destination for the file
                   12576:    docudom: domain of user/course of destination for the file
                   12577:    old: current file name (including any subdirs under userfiles)
                   12578:    new: desired file name (including any subdirs under userfiles)
                   12579: 
                   12580: =item *
                   12581: 
                   12582: mkdiruserfile(): creates a directory is a userfiles dir
                   12583: 
                   12584:   Args:
                   12585:    docuname: username or courseid of destination for the file
                   12586:    docudom: domain of user/course of destination for the file
                   12587:    dir: dir to create (including any subdirs under userfiles)
                   12588: 
                   12589: =item *
                   12590: 
                   12591: removeuserfile(): removes a file that exists in userfiles
                   12592: 
                   12593:   Args:
                   12594:    docuname: username or courseid of destination for the file
                   12595:    docudom: domain of user/course of destination for the file
                   12596:    fname: filname to delete (including any subdirs under userfiles)
                   12597: 
                   12598: =item *
                   12599: 
                   12600: removeuploadedurl(): convience function for removeuserfile()
                   12601: 
                   12602:   Args:
                   12603:    url:  a full /uploaded/... url to delete
                   12604: 
1.747     albertel 12605: =item * 
                   12606: 
                   12607: get_portfile_permissions():
                   12608:   Args:
                   12609:     domain: domain of user or course contain the portfolio files
                   12610:     user: name of user or num of course contain the portfolio files
                   12611:   Returns:
                   12612:     hashref of a dump of the proper file_permissions.db
                   12613:    
                   12614: 
                   12615: =item * 
                   12616: 
                   12617: get_access_controls():
                   12618: 
                   12619: Args:
                   12620:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12621:   group: (optional) the group you want the files associated with
                   12622:   file: (optional) the file you want access info on
                   12623: 
                   12624: Returns:
1.749     raeburn  12625:     a hash (keys are file names) of hashes containing
                   12626:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12627:         values are XML containing access control settings (see below) 
1.747     albertel 12628: 
                   12629: Internal notes:
                   12630: 
1.749     raeburn  12631:  access controls are stored in file_permissions.db as key=value pairs.
                   12632:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12633:         where scope -> public,guest,course,group,domains or users.
                   12634:               end -> UNIX time for end of access (0 -> no end date)
                   12635:               start -> UNIX time for start of access
                   12636: 
                   12637:     value -> XML description of access control
                   12638:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12639:             <start></start>
                   12640:             <end></end>
                   12641: 
                   12642:             <password></password>  for scope type = guest
                   12643: 
                   12644:             <domain></domain>     for scope type = course or group
                   12645:             <number></number>
                   12646:             <roles id="">
                   12647:              <role></role>
                   12648:              <access></access>
                   12649:              <section></section>
                   12650:              <group></group>
                   12651:             </roles>
                   12652: 
                   12653:             <dom></dom>         for scope type = domains
                   12654: 
                   12655:             <users>             for scope type = users
                   12656:              <user>
                   12657:               <uname></uname>
                   12658:               <udom></udom>
                   12659:              </user>
                   12660:             </users>
                   12661:            </scope> 
                   12662:               
                   12663:  Access data is also aggregated for each file in an additional key=value pair:
                   12664:  key -> path to file/file_name\0accesscontrol 
                   12665:  value -> reference to hash
                   12666:           hash contains key = value pairs
                   12667:           where key = uniqueID:scope_end_start
                   12668:                 value = UNIX time record was last updated
                   12669: 
                   12670:           Used to improve speed of look-ups of access controls for each file.  
                   12671:  
                   12672:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12673: 
                   12674: modify_access_controls():
                   12675: 
                   12676: Modifies access controls for a portfolio file
                   12677: Args
                   12678: 1. file name
                   12679: 2. reference to hash of required changes,
                   12680: 3. domain
                   12681: 4. username
                   12682:   where domain,username are the domain of the portfolio owner 
                   12683:   (either a user or a course) 
                   12684: 
                   12685: Returns:
                   12686: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12687: 2. result of deletions ('ok' or 'error', with error message).
                   12688: 3. reference to hash of any new or updated access controls.
                   12689: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12690:    key = integer (inbound ID)
                   12691:    value = uniqueID  
1.747     albertel 12692: 
1.608     albertel 12693: =back
                   12694: 
1.243     albertel 12695: =head2 HTTP Helper Routines
                   12696: 
                   12697: =over 4
                   12698: 
1.191     harris41 12699: =item *
                   12700: 
                   12701: escape() : unpack non-word characters into CGI-compatible hex codes
                   12702: 
                   12703: =item *
                   12704: 
                   12705: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12706: 
1.243     albertel 12707: =back
                   12708: 
                   12709: =head1 PRIVATE SUBROUTINES
                   12710: 
                   12711: =head2 Underlying communication routines (Shouldn't call)
                   12712: 
                   12713: =over 4
                   12714: 
                   12715: =item *
                   12716: 
                   12717: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12718: 
                   12719: =item *
                   12720: 
                   12721: reply() : uses subreply to send a message to remote machine, logs all failures
                   12722: 
                   12723: =item *
                   12724: 
                   12725: critical() : passes a critical message to another server; if cannot
                   12726: get through then place message in connection buffer directory and
                   12727: returns con_delayed, if incapable of saving message, returns
                   12728: con_failed
                   12729: 
                   12730: =item *
                   12731: 
                   12732: reconlonc() : tries to reconnect lonc client processes.
                   12733: 
                   12734: =back
                   12735: 
                   12736: =head2 Resource Access Logging
                   12737: 
                   12738: =over 4
                   12739: 
                   12740: =item *
                   12741: 
                   12742: flushcourselogs() : flush (save) buffer logs and access logs
                   12743: 
                   12744: =item *
                   12745: 
                   12746: courselog($what) : save message for course in hash
                   12747: 
                   12748: =item *
                   12749: 
                   12750: courseacclog($what) : save message for course using &courselog().  Perform
                   12751: special processing for specific resource types (problems, exams, quizzes, etc).
                   12752: 
1.191     harris41 12753: =item *
                   12754: 
                   12755: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12756: as a PerlChildExitHandler
1.243     albertel 12757: 
                   12758: =back
                   12759: 
                   12760: =head2 Other
                   12761: 
                   12762: =over 4
                   12763: 
                   12764: =item *
                   12765: 
                   12766: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12767: 
                   12768: =back
                   12769: 
                   12770: =cut
1.877     foxr     12771: 

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