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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1131  ! raeburn     4: # $Id: lonnet.pm,v 1.1130 2011/08/17 00:32:27 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.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.1079    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871     albertel   80: 
                     81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     82:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     83:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        84:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        85: 
1.1       albertel   86: use IO::Socket;
1.31      www        87: use GDBM_File;
1.208     albertel   88: use HTML::LCParser;
1.88      www        89: use Fcntl qw(:flock);
1.870     albertel   90: use Storable qw(thaw nfreeze);
1.539     albertel   91: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   92: use Cache::Memcached;
1.676     albertel   93: use Digest::MD5;
1.790     albertel   94: use Math::Random;
1.1024    raeburn    95: use File::MMagic;
1.807     albertel   96: use LONCAPA qw(:DEFAULT :match);
1.740     www        97: use LONCAPA::Configuration;
1.1117    foxr       98: 
1.1090    raeburn    99: use File::Copy;
1.676     albertel  100: 
1.195     www       101: my $readit;
1.550     foxr      102: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  103: 
1.619     albertel  104: require Exporter;
                    105: 
                    106: our @ISA = qw (Exporter);
                    107: our @EXPORT = qw(%env);
                    108: 
1.449     matthew   109: 
1.1       albertel  110: # --------------------------------------------------------------------- Logging
1.729     www       111: {
                    112:     my $logid;
                    113:     sub instructor_log {
1.957     raeburn   114: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    115:         if (($cnum eq '') || ($cdom eq '')) {
                    116:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    117:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    118:         }
1.729     www       119: 	$logid++;
1.957     raeburn   120:         my $now = time();
                    121: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       122: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       123: 				    { $id => {
                    124: 					'exe_uname' => $env{'user.name'},
                    125: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   126: 					'exe_time'  => $now,
1.730     www       127: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    128: 					'delflag'   => $delflag,
                    129: 					'logentry'  => $storehash,
                    130: 					'uname'     => $uname,
                    131: 					'udom'      => $udom,
                    132: 				    }
1.957     raeburn   133: 				  },$cdom,$cnum);
1.729     www       134:     }
                    135: }
1.1       albertel  136: 
1.163     harris41  137: sub logtouch {
                    138:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  139:     unless (-e "$execdir/logs/lonnet.log") {	
                    140: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  141: 	close $fh;
                    142:     }
                    143:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    144:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    145: }
                    146: 
1.1       albertel  147: sub logthis {
                    148:     my $message=shift;
                    149:     my $execdir=$perlvar{'lonDaemons'};
                    150:     my $now=time;
                    151:     my $local=localtime($now);
1.448     albertel  152:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      153: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    154: 	print $fh $logstring;
1.448     albertel  155: 	close($fh);
                    156:     }
1.1       albertel  157:     return 1;
                    158: }
                    159: 
                    160: sub logperm {
                    161:     my $message=shift;
                    162:     my $execdir=$perlvar{'lonDaemons'};
                    163:     my $now=time;
                    164:     my $local=localtime($now);
1.448     albertel  165:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    166: 	print $fh "$now:$message:$local\n";
                    167: 	close($fh);
                    168:     }
1.1       albertel  169:     return 1;
                    170: }
                    171: 
1.850     albertel  172: sub create_connection {
1.853     albertel  173:     my ($hostname,$lonid) = @_;
1.851     albertel  174:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  175: 				     Type    => SOCK_STREAM,
                    176: 				     Timeout => 10);
                    177:     return 0 if (!$client);
1.890     albertel  178:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  179:     my $result = <$client>;
                    180:     chomp($result);
                    181:     return 1 if ($result eq 'done');
                    182:     return 0;
                    183: }
                    184: 
1.983     raeburn   185: sub get_server_timezone {
                    186:     my ($cnum,$cdom) = @_;
                    187:     my $home=&homeserver($cnum,$cdom);
                    188:     if ($home ne 'no_host') {
                    189:         my $cachetime = 24*3600;
                    190:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    191:         if (defined($cached)) {
                    192:             return $timezone;
                    193:         } else {
                    194:             my $timezone = &reply('servertimezone',$home);
                    195:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    196:         }
                    197:     }
                    198: }
1.850     albertel  199: 
1.1106    raeburn   200: sub get_server_distarch {
                    201:     my ($lonhost,$ignore_cache) = @_;
                    202:     if (defined($lonhost)) {
                    203:         if (!defined(&hostname($lonhost))) {
                    204:             return;
                    205:         }
                    206:         my $cachetime = 12*3600;
                    207:         if (!$ignore_cache) {
                    208:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    209:             if (defined($cached)) {
                    210:                 return $distarch;
                    211:             }
                    212:         }
                    213:         my $rep = &reply('serverdistarch',$lonhost);
                    214:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    215:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    216:                 $rep eq '') {
                    217:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    218:         }
                    219:     }
                    220:     return;
                    221: }
                    222: 
1.993     raeburn   223: sub get_server_loncaparev {
1.1073    raeburn   224:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   225:     if (defined($lonhost)) {
                    226:         if (!defined(&hostname($lonhost))) {
                    227:             undef($lonhost);
                    228:         }
                    229:     }
                    230:     if (!defined($lonhost)) {
                    231:         if (defined(&domain($dom,'primary'))) {
                    232:             $lonhost=&domain($dom,'primary');
                    233:             if ($lonhost eq 'no_host') {
                    234:                 undef($lonhost);
                    235:             }
                    236:         }
                    237:     }
                    238:     if (defined($lonhost)) {
1.1073    raeburn   239:         my $cachetime = 12*3600;
                    240:         if (!$ignore_cache) {
                    241:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    242:             if (defined($cached)) {
                    243:                 return $loncaparev;
                    244:             }
                    245:         }
                    246:         my ($answer,$loncaparev);
                    247:         my @ids=&current_machine_ids();
                    248:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    249:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   250:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   251:                 $loncaparev = $1;
                    252:             }
                    253:         } else {
                    254:             $answer = &reply('serverloncaparev',$lonhost);
                    255:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    256:                 if ($caller eq 'loncron') {
                    257:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   258:                     $ua->timeout(4);
1.1073    raeburn   259:                     my $protocol = $protocol{$lonhost};
                    260:                     $protocol = 'http' if ($protocol ne 'https');
                    261:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    262:                     my $request=new HTTP::Request('GET',$url);
                    263:                     my $response=$ua->request($request);
                    264:                     unless ($response->is_error()) {
                    265:                         my $content = $response->content;
1.1081    raeburn   266:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   267:                             $loncaparev = $1;
                    268:                         }
                    269:                     }
                    270:                 } else {
                    271:                     $loncaparev = $loncaparevs{$lonhost};
                    272:                 }
1.1081    raeburn   273:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   274:                 $loncaparev = $1;
                    275:             }
1.993     raeburn   276:         }
1.1073    raeburn   277:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   278:     }
                    279: }
                    280: 
1.1074    raeburn   281: sub get_server_homeID {
                    282:     my ($hostname,$ignore_cache,$caller) = @_;
                    283:     unless ($ignore_cache) {
                    284:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    285:         if (defined($cached)) {
                    286:             return $serverhomeID;
                    287:         }
                    288:     }
                    289:     my $cachetime = 12*3600;
                    290:     my $serverhomeID;
                    291:     if ($caller eq 'loncron') { 
                    292:         my @machine_ids = &machine_ids($hostname);
                    293:         foreach my $id (@machine_ids) {
                    294:             my $response = &reply('serverhomeID',$id);
                    295:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    296:                 $serverhomeID = $response;
                    297:                 last;
                    298:             }
                    299:         }
                    300:         if ($serverhomeID eq '') {
                    301:             $serverhomeID = $machine_ids[-1];
                    302:         }
                    303:     } else {
                    304:         $serverhomeID = $serverhomeIDs{$hostname};
                    305:     }
                    306:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    307: }
                    308: 
1.1121    raeburn   309: sub get_remote_globals {
                    310:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   311:     my ($result,%returnhash,%whatneeded);
                    312:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   313:         foreach my $what (sort(keys(%{$whathash}))) {
                    314:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   315:             my ($response,$cached);
1.1121    raeburn   316:             unless ($ignore_cache) {
1.1125    raeburn   317:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   318:             }
                    319:             if (defined($cached)) {
1.1125    raeburn   320:                 $returnhash{$what} = $response;
1.1121    raeburn   321:             } else {
1.1125    raeburn   322:                 $whatneeded{$what} = 1;
1.1121    raeburn   323:             }
                    324:         }
1.1125    raeburn   325:         if (keys(%whatneeded) == 0) {
                    326:             $result = 'ok';
                    327:         } else {
1.1121    raeburn   328:             my $requested = &freeze_escape(\%whatneeded);
                    329:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   330:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    331:                 ($rep eq 'unknown_cmd')) {
                    332:                 $result = $rep;
                    333:             } else {
                    334:                 $result = 'ok';
1.1121    raeburn   335:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   336:                 foreach my $item (@pairs) {
                    337:                     my ($key,$value)=split(/=/,$item,2);
                    338:                     my $what = &unescape($key);
                    339:                     my $hashid = $lonhost.'-'.$what;
                    340:                     $returnhash{$what}=&thaw_unescape($value);
                    341:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   342:                 }
                    343:             }
                    344:         }
                    345:     }
1.1125    raeburn   346:     return ($result,\%returnhash);
1.1121    raeburn   347: }
                    348: 
1.1124    raeburn   349: sub remote_devalidate_cache {
                    350:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   351:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   352:     return $response;
                    353: }
                    354: 
1.1       albertel  355: # -------------------------------------------------- Non-critical communication
                    356: sub subreply {
                    357:     my ($cmd,$server)=@_;
1.838     albertel  358:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      359:     #
                    360:     #  With loncnew process trimming, there's a timing hole between lonc server
                    361:     #  process exit and the master server picking up the listen on the AF_UNIX
                    362:     #  socket.  In that time interval, a lock file will exist:
                    363: 
                    364:     my $lockfile=$peerfile.".lock";
                    365:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    366: 	sleep(1);
                    367:     }
                    368:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      369:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      370:     #
1.550     foxr      371:     #   We'll give the connection a few tries before abandoning it.  If
                    372:     #   connection is not possible, we'll con_lost back to the client.
                    373:     #   
                    374:     my $client;
                    375:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    376: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    377: 				      Type    => SOCK_STREAM,
                    378: 				      Timeout => 10);
1.869     albertel  379: 	if ($client) {
1.550     foxr      380: 	    last;		# Connected!
1.850     albertel  381: 	} else {
1.853     albertel  382: 	    &create_connection(&hostname($server),$server);
1.550     foxr      383: 	}
1.850     albertel  384:         sleep(1);		# Try again later if failed connection.
1.550     foxr      385:     }
                    386:     my $answer;
                    387:     if ($client) {
1.704     albertel  388: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      389: 	$answer=<$client>;
                    390: 	if (!$answer) { $answer="con_lost"; }
                    391: 	chomp($answer);
                    392:     } else {
                    393: 	$answer = 'con_lost';	# Failed connection.
                    394:     }
1.1       albertel  395:     return $answer;
                    396: }
                    397: 
                    398: sub reply {
                    399:     my ($cmd,$server)=@_;
1.838     albertel  400:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  401:     my $answer=subreply($cmd,$server);
1.65      www       402:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  403:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       404:                 " $cmd to $server returned $answer</font>");
                    405:     }
1.1       albertel  406:     return $answer;
                    407: }
                    408: 
                    409: # ----------------------------------------------------------- Send USR1 to lonc
                    410: 
                    411: sub reconlonc {
1.891     albertel  412:     my ($lonid) = @_;
                    413:     my $hostname = &hostname($lonid);
                    414:     if ($lonid) {
                    415: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    416: 	if ($hostname && -e $peerfile) {
                    417: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    418: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    419: 					     Type    => SOCK_STREAM,
                    420: 					     Timeout => 10);
                    421: 	    if ($client) {
                    422: 		print $client ("reset_retries\n");
                    423: 		my $answer=<$client>;
                    424: 		#reset just this one.
                    425: 	    }
                    426: 	}
                    427: 	return;
                    428:     }
                    429: 
1.836     www       430:     &logthis("Trying to reconnect lonc");
1.1       albertel  431:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  432:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  433: 	my $loncpid=<$fh>;
                    434:         chomp($loncpid);
                    435:         if (kill 0 => $loncpid) {
                    436: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    437:             kill USR1 => $loncpid;
                    438:             sleep 1;
1.836     www       439:          } else {
1.12      www       440: 	    &logthis(
1.672     albertel  441:                "<font color=\"blue\">WARNING:".
1.12      www       442:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  443:         }
                    444:     } else {
1.836     www       445: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  446:     }
                    447: }
                    448: 
                    449: # ------------------------------------------------------ Critical communication
1.12      www       450: 
1.1       albertel  451: sub critical {
                    452:     my ($cmd,$server)=@_;
1.838     albertel  453:     unless (&hostname($server)) {
1.672     albertel  454:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       455:                " Critical message to unknown server ($server)</font>");
                    456:         return 'no_such_host';
                    457:     }
1.1       albertel  458:     my $answer=reply($cmd,$server);
                    459:     if ($answer eq 'con_lost') {
                    460: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  461: 	my $answer=reply($cmd,$server);
1.1       albertel  462:         if ($answer eq 'con_lost') {
                    463:             my $now=time;
                    464:             my $middlename=$cmd;
1.5       www       465:             $middlename=substr($middlename,0,16);
1.1       albertel  466:             $middlename=~s/\W//g;
                    467:             my $dfilename=
1.305     www       468:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    469:             $dumpcount++;
1.1       albertel  470:             {
1.448     albertel  471: 		my $dfh;
                    472: 		if (open($dfh,">$dfilename")) {
                    473: 		    print $dfh "$cmd\n"; 
                    474: 		    close($dfh);
                    475: 		}
1.1       albertel  476:             }
                    477:             sleep 2;
                    478:             my $wcmd='';
                    479:             {
1.448     albertel  480: 		my $dfh;
                    481: 		if (open($dfh,"<$dfilename")) {
                    482: 		    $wcmd=<$dfh>; 
                    483: 		    close($dfh);
                    484: 		}
1.1       albertel  485:             }
                    486:             chomp($wcmd);
1.7       www       487:             if ($wcmd eq $cmd) {
1.672     albertel  488: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       489:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  490:                 &logperm("D:$server:$cmd");
                    491: 	        return 'con_delayed';
                    492:             } else {
1.672     albertel  493:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       494:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  495:                 &logperm("F:$server:$cmd");
                    496:                 return 'con_failed';
                    497:             }
                    498:         }
                    499:     }
                    500:     return $answer;
1.405     albertel  501: }
                    502: 
1.755     albertel  503: # ------------------------------------------- check if return value is an error
                    504: 
                    505: sub error {
                    506:     my ($result) = @_;
1.756     albertel  507:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  508: 	if ($2 == 2) { return undef; }
                    509: 	return $1;
                    510:     }
                    511:     return undef;
                    512: }
                    513: 
1.783     albertel  514: sub convert_and_load_session_env {
                    515:     my ($lonidsdir,$handle)=@_;
                    516:     my @profile;
                    517:     {
1.917     albertel  518: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    519: 	if (!$opened) {
1.915     albertel  520: 	    return 0;
                    521: 	}
1.783     albertel  522: 	flock($idf,LOCK_SH);
                    523: 	@profile=<$idf>;
                    524: 	close($idf);
                    525:     }
                    526:     my %temp_env;
                    527:     foreach my $line (@profile) {
1.786     albertel  528: 	if ($line !~ m/=/) {
                    529: 	    return 0;
                    530: 	}
1.783     albertel  531: 	chomp($line);
                    532: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    533: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    534:     }
                    535:     unlink("$lonidsdir/$handle.id");
                    536:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    537: 	    0640)) {
                    538: 	%disk_env = %temp_env;
                    539: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    540: 	untie(%disk_env);
                    541:     }
1.786     albertel  542:     return 1;
1.783     albertel  543: }
                    544: 
1.374     www       545: # ------------------------------------------- Transfer profile into environment
1.780     albertel  546: my $env_loaded;
                    547: sub transfer_profile_to_env {
1.788     albertel  548:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    549:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       550: 
1.720     albertel  551:     if (!defined($lonidsdir)) {
                    552: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    553:     }
                    554:     if (!defined($handle)) {
                    555:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    556:     }
                    557: 
1.786     albertel  558:     my $convert;
                    559:     {
1.917     albertel  560:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    561: 	if (!$opened) {
1.915     albertel  562: 	    return;
                    563: 	}
1.786     albertel  564: 	flock($idf,LOCK_SH);
                    565: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    566: 		&GDBM_READER(),0640)) {
                    567: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    568: 	    untie(%disk_env);
                    569: 	} else {
                    570: 	    $convert = 1;
                    571: 	}
                    572:     }
                    573:     if ($convert) {
                    574: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    575: 	    &logthis("Failed to load session, or convert session.");
                    576: 	}
1.374     www       577:     }
1.783     albertel  578: 
1.786     albertel  579:     my %remove;
1.783     albertel  580:     while ( my $envname = each(%env) ) {
1.433     matthew   581:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    582:             if ($time < time-300) {
1.783     albertel  583:                 $remove{$key}++;
1.433     matthew   584:             }
                    585:         }
                    586:     }
1.783     albertel  587: 
1.619     albertel  588:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  589:     $env_loaded=1;
1.783     albertel  590:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   591:         &delenv($expired_key);
1.374     www       592:     }
1.1       albertel  593: }
                    594: 
1.916     albertel  595: # ---------------------------------------------------- Check for valid session 
                    596: sub check_for_valid_session {
                    597:     my ($r) = @_;
                    598:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    599:     my $lonid=$cookies{'lonID'};
                    600:     return undef if (!$lonid);
                    601: 
                    602:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    603:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    604:     return undef if (!-e "$lonidsdir/$handle.id");
                    605: 
1.917     albertel  606:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    607:     return undef if (!$opened);
1.916     albertel  608: 
                    609:     flock($idf,LOCK_SH);
                    610:     my %disk_env;
                    611:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    612: 	    &GDBM_READER(),0640)) {
                    613: 	return undef;	
                    614:     }
                    615: 
                    616:     if (!defined($disk_env{'user.name'})
                    617: 	|| !defined($disk_env{'user.domain'})) {
                    618: 	return undef;
                    619:     }
                    620:     return $handle;
                    621: }
                    622: 
1.830     albertel  623: sub timed_flock {
                    624:     my ($file,$lock_type) = @_;
                    625:     my $failed=0;
                    626:     eval {
                    627: 	local $SIG{__DIE__}='DEFAULT';
                    628: 	local $SIG{ALRM}=sub {
                    629: 	    $failed=1;
                    630: 	    die("failed lock");
                    631: 	};
                    632: 	alarm(13);
                    633: 	flock($file,$lock_type);
                    634: 	alarm(0);
                    635:     };
                    636:     if ($failed) {
                    637: 	return undef;
                    638:     } else {
                    639: 	return 1;
                    640:     }
                    641: }
                    642: 
1.5       www       643: # ---------------------------------------------------------- Append Environment
                    644: 
                    645: sub appenv {
1.949     raeburn   646:     my ($newenv,$roles) = @_;
                    647:     if (ref($newenv) eq 'HASH') {
                    648:         foreach my $key (keys(%{$newenv})) {
                    649:             my $refused = 0;
                    650: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    651:                 $refused = 1;
                    652:                 if (ref($roles) eq 'ARRAY') {
                    653:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    654:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    655:                         $refused = 0;
                    656:                     }
                    657:                 }
                    658:             }
                    659:             if ($refused) {
                    660:                 &logthis("<font color=\"blue\">WARNING: ".
                    661:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    662:                          .'</font>');
                    663: 	        delete($newenv->{$key});
                    664:             } else {
                    665:                 $env{$key}=$newenv->{$key};
                    666:             }
                    667:         }
                    668:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    669:         if ($opened
                    670: 	    && &timed_flock($env_file,LOCK_EX)
                    671: 	    &&
                    672: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    673: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    674: 	    while (my ($key,$value) = each(%{$newenv})) {
                    675: 	        $disk_env{$key} = $value;
                    676: 	    }
                    677: 	    untie(%disk_env);
1.35      www       678:         }
1.191     harris41  679:     }
1.56      www       680:     return 'ok';
                    681: }
                    682: # ----------------------------------------------------- Delete from Environment
                    683: 
                    684: sub delenv {
1.1104    raeburn   685:     my ($delthis,$regexp,$roles) = @_;
                    686:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    687:         my $refused = 1;
                    688:         if (ref($roles) eq 'ARRAY') {
                    689:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    690:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    691:                 $refused = 0;
                    692:             }
                    693:         }
                    694:         if ($refused) {
                    695:             &logthis("<font color=\"blue\">WARNING: ".
                    696:                      "Attempt to delete from environment ".$delthis);
                    697:             return 'error';
                    698:         }
1.56      www       699:     }
1.917     albertel  700:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    701:     if ($opened
1.915     albertel  702: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  703: 	&&
                    704: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    705: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  706: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   707: 	    if ($regexp) {
                    708:                 if ($key=~/^$delthis/) {
                    709:                     delete($env{$key});
                    710:                     delete($disk_env{$key});
                    711:                 } 
                    712:             } else {
                    713:                 if ($key=~/^\Q$delthis\E/) {
                    714: 		    delete($env{$key});
                    715: 		    delete($disk_env{$key});
                    716: 	        }
                    717:             }
1.448     albertel  718: 	}
1.783     albertel  719: 	untie(%disk_env);
1.5       www       720:     }
                    721:     return 'ok';
1.369     albertel  722: }
                    723: 
1.790     albertel  724: sub get_env_multiple {
                    725:     my ($name) = @_;
                    726:     my @values;
                    727:     if (defined($env{$name})) {
                    728:         # exists is it an array
                    729:         if (ref($env{$name})) {
                    730:             @values=@{ $env{$name} };
                    731:         } else {
                    732:             $values[0]=$env{$name};
                    733:         }
                    734:     }
                    735:     return(@values);
                    736: }
                    737: 
1.958     www       738: # ------------------------------------------------------------------- Locking
                    739: 
                    740: sub set_lock {
                    741:     my ($text)=@_;
                    742:     $locknum++;
                    743:     my $id=$$.'-'.$locknum;
                    744:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    745:              'session.lock.'.$id => $text});
                    746:     return $id;
                    747: }
                    748: 
                    749: sub get_locks {
                    750:     my $num=0;
                    751:     my %texts=();
                    752:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    753:        if ($lock=~/\w/) {
                    754:           $num++;
                    755:           $texts{$lock}=$env{'session.lock.'.$lock};
                    756:        }
                    757:    }
                    758:    return ($num,%texts);
                    759: }
                    760: 
                    761: sub remove_lock {
                    762:     my ($id)=@_;
                    763:     my $newlocks='';
                    764:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    765:        if (($lock=~/\w/) && ($lock ne $id)) {
                    766:           $newlocks.=','.$lock;
                    767:        }
                    768:     }
                    769:     &appenv({'session.locks' => $newlocks});
                    770:     &delenv('session.lock.'.$id);
                    771: }
                    772: 
                    773: sub remove_all_locks {
                    774:     my $activelocks=$env{'session.locks'};
                    775:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    776:        if ($lock=~/\w/) {
                    777:           &remove_lock($lock);
                    778:        }
                    779:     }
                    780: }
                    781: 
                    782: 
1.369     albertel  783: # ------------------------------------------ Find out current server userload
                    784: sub userload {
                    785:     my $numusers=0;
                    786:     {
                    787: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    788: 	my $filename;
                    789: 	my $curtime=time;
                    790: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  791: 	    next if ($filename eq '.' || $filename eq '..');
                    792: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  793: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  794: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  795: 	}
                    796: 	closedir(LONIDS);
                    797:     }
                    798:     my $userloadpercent=0;
                    799:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    800:     if ($maxuserload) {
1.371     albertel  801: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  802:     }
1.372     albertel  803:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  804:     return $userloadpercent;
1.283     www       805: }
                    806: 
1.1       albertel  807: # ------------------------------ Find server with least workload from spare.tab
1.11      www       808: 
1.1       albertel  809: sub spareserver {
1.1083    raeburn   810:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  811:     my $spare_server;
1.370     albertel  812:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  813:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    814:                                                      :  $userloadpercent;
1.1083    raeburn   815:     my ($uint_dom,$remotesessions);
                    816:     if (($udom ne '') && (&domain($udom) ne '')) {
                    817:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    818:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    819:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    820:         $remotesessions = $udomdefaults{'remotesessions'};
                    821:     }
1.1123    raeburn   822:     my $spareshash = &this_host_spares($udom);
                    823:     if (ref($spareshash) eq 'HASH') {
                    824:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    825:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    826:                 if ($uint_dom) {
                    827:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    828:                                                  $try_server));
                    829:                 }
                    830: 	        ($spare_server, $lowest_load) =
                    831: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    832:             }
1.1083    raeburn   833:         }
1.784     albertel  834: 
1.1123    raeburn   835:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    836: 
                    837:         if (!$found_server) {
                    838:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    839: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    840:                     if ($uint_dom) {
                    841:                         next unless (&spare_can_host($udom,$uint_dom,
                    842:                                                      $remotesessions,$try_server));
                    843:                     }
                    844: 	            ($spare_server, $lowest_load) =
                    845: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    846:                 }
                    847: 	    }
                    848:         }
1.784     albertel  849:     }
                    850: 
                    851:     if (!$want_server_name) {
1.968     raeburn   852:         my $protocol = 'http';
                    853:         if ($protocol{$spare_server} eq 'https') {
                    854:             $protocol = $protocol{$spare_server};
                    855:         }
1.1001    raeburn   856:         if (defined($spare_server)) {
                    857:             my $hostname = &hostname($spare_server);
1.1083    raeburn   858:             if (defined($hostname)) {
1.1001    raeburn   859: 	        $spare_server = $protocol.'://'.$hostname;
                    860:             }
                    861:         }
1.784     albertel  862:     }
                    863:     return $spare_server;
                    864: }
                    865: 
                    866: sub compare_server_load {
                    867:     my ($try_server, $spare_server, $lowest_load) = @_;
                    868: 
                    869:     my $loadans     = &reply('load',    $try_server);
                    870:     my $userloadans = &reply('userload',$try_server);
                    871: 
                    872:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   873: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  874:     }
                    875: 
                    876:     my $load;
                    877:     if ($loadans =~ /\d/) {
                    878: 	if ($userloadans =~ /\d/) {
                    879: 	    #both are numbers, pick the bigger one
                    880: 	    $load = ($loadans > $userloadans) ? $loadans 
                    881: 		                              : $userloadans;
1.411     albertel  882: 	} else {
1.784     albertel  883: 	    $load = $loadans;
1.411     albertel  884: 	}
1.784     albertel  885:     } else {
                    886: 	$load = $userloadans;
                    887:     }
                    888: 
                    889:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    890: 	$spare_server = $try_server;
                    891: 	$lowest_load  = $load;
1.370     albertel  892:     }
1.784     albertel  893:     return ($spare_server,$lowest_load);
1.202     matthew   894: }
1.914     albertel  895: 
                    896: # --------------------------- ask offload servers if user already has a session
                    897: sub find_existing_session {
                    898:     my ($udom,$uname) = @_;
1.1123    raeburn   899:     my $spareshash = &this_host_spares($udom);
                    900:     if (ref($spareshash) eq 'HASH') {
                    901:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    902:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    903:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    904:             }
                    905:         }
                    906:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    907:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    908:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    909:             }
                    910:         }
1.914     albertel  911:     }
                    912:     return;
                    913: }
                    914: 
                    915: # -------------------------------- ask if server already has a session for user
                    916: sub has_user_session {
                    917:     my ($lonid,$udom,$uname) = @_;
                    918:     my $result = &reply(join(':','userhassession',
                    919: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    920:     return 1 if ($result eq 'ok');
                    921: 
                    922:     return 0;
                    923: }
                    924: 
1.1076    raeburn   925: # --------- determine least loaded server in a user's domain which allows login
                    926: 
                    927: sub choose_server {
1.1115    raeburn   928:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   929:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   930:     my %servers = &get_servers($udom);
1.1076    raeburn   931:     my $lowest_load = 30000;
1.1116    raeburn   932:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   933:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   934:         my $loginvia;
                    935:         if ($checkloginvia) {
                    936:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   937:             if ($loginvia) {
                    938:                 my ($server,$path) = split(/:/,$loginvia);
                    939:                 ($login_host, $lowest_load) =
                    940:                     &compare_server_load($server, $login_host, $lowest_load);
                    941:                 if ($login_host eq $server) {
                    942:                     $portal_path = $path;
                    943:                 }
                    944:             } else {
                    945:                 ($login_host, $lowest_load) =
                    946:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    947:                 if ($login_host eq $lonhost) {
                    948:                     $portal_path = '';
                    949:                 }
                    950:             }
                    951:         } else {
1.1076    raeburn   952:             ($login_host, $lowest_load) =
1.1116    raeburn   953:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   954:         }
                    955:     }
                    956:     if ($login_host ne '') {
1.1116    raeburn   957:         $hostname = &hostname($login_host);
1.1076    raeburn   958:     }
1.1116    raeburn   959:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   960: }
                    961: 
1.202     matthew   962: # --------------------------------------------- Try to change a user's password
                    963: 
                    964: sub changepass {
1.799     raeburn   965:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   966:     $currentpass = &escape($currentpass);
                    967:     $newpass     = &escape($newpass);
1.1030    raeburn   968:     my $lonhost = $perlvar{'lonHostID'};
                    969:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   970: 		       $server);
                    971:     if (! $answer) {
                    972: 	&logthis("No reply on password change request to $server ".
                    973: 		 "by $uname in domain $udom.");
                    974:     } elsif ($answer =~ "^ok") {
                    975:         &logthis("$uname in $udom successfully changed their password ".
                    976: 		 "on $server.");
                    977:     } elsif ($answer =~ "^pwchange_failure") {
                    978: 	&logthis("$uname in $udom was unable to change their password ".
                    979: 		 "on $server.  The action was blocked by either lcpasswd ".
                    980: 		 "or pwchange");
                    981:     } elsif ($answer =~ "^non_authorized") {
                    982:         &logthis("$uname in $udom did not get their password correct when ".
                    983: 		 "attempting to change it on $server.");
                    984:     } elsif ($answer =~ "^auth_mode_error") {
                    985:         &logthis("$uname in $udom attempted to change their password despite ".
                    986: 		 "not being locally or internally authenticated on $server.");
                    987:     } elsif ($answer =~ "^unknown_user") {
                    988:         &logthis("$uname in $udom attempted to change their password ".
                    989: 		 "on $server but were unable to because $server is not ".
                    990: 		 "their home server.");
                    991:     } elsif ($answer =~ "^refused") {
                    992: 	&logthis("$server refused to change $uname in $udom password because ".
                    993: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   994:     } elsif ($answer =~ "invalid_client") {
                    995:         &logthis("$server refused to change $uname in $udom password because ".
                    996:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   997:     }
                    998:     return $answer;
1.1       albertel  999: }
                   1000: 
1.169     harris41 1001: # ----------------------- Try to determine user's current authentication scheme
                   1002: 
                   1003: sub queryauthenticate {
                   1004:     my ($uname,$udom)=@_;
1.456     albertel 1005:     my $uhome=&homeserver($uname,$udom);
                   1006:     if (!$uhome) {
                   1007: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1008: 	return 'no_host';
                   1009:     }
                   1010:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1011:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1012: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1013:     }
1.456     albertel 1014:     return $answer;
1.169     harris41 1015: }
                   1016: 
1.1       albertel 1017: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1018: 
1.1       albertel 1019: sub authenticate {
1.1073    raeburn  1020:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1021:     $upass=&escape($upass);
                   1022:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1023:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1024:     my $newhome;
1.836     www      1025:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1026: # Maybe the machine was offline and only re-appeared again recently?
                   1027:         &reconlonc();
                   1028: # One more
1.952     raeburn  1029: 	$uhome=&homeserver($uname,$udom,1);
                   1030:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1031:             if (defined(&domain($udom,'primary'))) {
                   1032:                 $newhome=&domain($udom,'primary');
                   1033:             }
                   1034:             if ($newhome ne '') {
                   1035:                 $uhome = $newhome;
                   1036:             }
                   1037:         }
1.836     www      1038: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1039: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1040: 	    return 'no_host';
                   1041:         }
1.1       albertel 1042:     }
1.1073    raeburn  1043:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1044:     if ($answer eq 'authorized') {
1.952     raeburn  1045:         if ($newhome) {
                   1046:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1047:             return 'no_account_on_host'; 
                   1048:         } else {
                   1049:             &logthis("User $uname at $udom authorized by $uhome");
                   1050:             return $uhome;
                   1051:         }
1.471     albertel 1052:     }
                   1053:     if ($answer eq 'non_authorized') {
                   1054: 	&logthis("User $uname at $udom rejected by $uhome");
                   1055: 	return 'no_host'; 
1.9       www      1056:     }
1.471     albertel 1057:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1058:     return 'no_host';
                   1059: }
                   1060: 
1.1073    raeburn  1061: sub can_host_session {
1.1074    raeburn  1062:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1063:     my $canhost = 1;
1.1074    raeburn  1064:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1065:     if (ref($remotesessions) eq 'HASH') {
                   1066:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1067:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1068:                 $canhost = 0;
                   1069:             } else {
                   1070:                 $canhost = 1;
                   1071:             }
                   1072:         }
                   1073:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1074:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1075:                 $canhost = 1;
                   1076:             } else {
                   1077:                 $canhost = 0;
                   1078:             }
                   1079:         }
                   1080:         if ($canhost) {
                   1081:             if ($remotesessions->{'version'} ne '') {
                   1082:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1083:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1084:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1085:                         my $major = $1;
                   1086:                         my $minor = $2;
                   1087:                         if (($major < $reqmajor ) ||
                   1088:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1089:                             $canhost = 0;
                   1090:                         }
                   1091:                     } else {
                   1092:                         $canhost = 0;
                   1093:                     }
                   1094:                 }
                   1095:             }
                   1096:         }
                   1097:     }
                   1098:     if ($canhost) {
                   1099:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1100:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1101:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1102:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1103:                 if (($uint_dom ne '') && 
                   1104:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1105:                     $canhost = 0;
                   1106:                 } else {
                   1107:                     $canhost = 1;
                   1108:                 }
                   1109:             }
                   1110:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1111:                 if (($uint_dom ne '') && 
                   1112:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1113:                     $canhost = 1;
                   1114:                 } else {
                   1115:                     $canhost = 0;
                   1116:                 }
                   1117:             }
                   1118:         }
                   1119:     }
                   1120:     return $canhost;
                   1121: }
                   1122: 
1.1083    raeburn  1123: sub spare_can_host {
                   1124:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1125:     my $canhost=1;
                   1126:     my @intdoms;
                   1127:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1128:     if (ref($internet_names) eq 'ARRAY') {
                   1129:         @intdoms = @{$internet_names};
                   1130:     }
                   1131:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1132:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1133:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1134:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1135:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1136:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1137:                                      $remotesessions,
                   1138:                                      $defdomdefaults{'hostedsessions'});
                   1139:     }
                   1140:     return $canhost;
                   1141: }
                   1142: 
1.1123    raeburn  1143: sub this_host_spares {
                   1144:     my ($dom) = @_;
1.1126    raeburn  1145:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1146:     my @hosts = &current_machine_ids();
                   1147:     foreach my $lonhost (@hosts) {
                   1148:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1149:             $dom_in_use = $dom;
                   1150:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1151:             last;
                   1152:         }
                   1153:     }
1.1126    raeburn  1154:     if ($dom_in_use ne '') {
                   1155:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1156:     }
                   1157:     if (ref($result) ne 'HASH') {
                   1158:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1159:         $dom_in_use = &host_domain($lonhost_in_use);
                   1160:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1161:         if (ref($result) ne 'HASH') {
                   1162:             $result = \%spareid;
                   1163:         }
                   1164:     }
                   1165:     return $result;
                   1166: }
                   1167: 
                   1168: sub spares_for_offload  {
                   1169:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1170:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1171:     if (defined($cached)) {
                   1172:         return $result;
                   1173:     } else {
1.1126    raeburn  1174:         my $cachetime = 60*60*24;
                   1175:         my %domconfig =
                   1176:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1177:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1178:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1179:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1180:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1181:                 }
                   1182:             }
                   1183:         }
                   1184:     }
1.1126    raeburn  1185:     return;
1.1123    raeburn  1186: }
                   1187: 
1.1129    raeburn  1188: sub get_lonbalancer_config {
                   1189:     my ($servers) = @_;
                   1190:     my ($currbalancer,$currtargets);
                   1191:     if (ref($servers) eq 'HASH') {
                   1192:         foreach my $server (keys(%{$servers})) {
                   1193:             my %what = (
                   1194:                          spareid => 1,
                   1195:                          perlvar => 1,
                   1196:                        );
                   1197:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1198:             if ($result eq 'ok') {
                   1199:                 if (ref($returnhash) eq 'HASH') {
                   1200:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1201:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1202:                             $currbalancer = $server;
                   1203:                             $currtargets = {};
                   1204:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1205:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1206:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1207:                                 }
                   1208:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1209:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1210:                                 }
                   1211:                             }
                   1212:                             last;
                   1213:                         }
                   1214:                     }
                   1215:                 }
                   1216:             }
                   1217:         }
                   1218:     }
                   1219:     return ($currbalancer,$currtargets);
                   1220: }
                   1221: 
                   1222: sub check_loadbalancing {
                   1223:     my ($uname,$udom) = @_;
                   1224:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1225:         $offloadto,$otherserver);
                   1226:     my $lonhost = $perlvar{'lonHostID'};
                   1227:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1228:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1229:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1230:     my $serverhomedom = &host_domain($lonhost);
                   1231: 
                   1232:     my $cachetime = 60*60*24;
                   1233: 
                   1234:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1235:         $dom_in_use = $udom;
                   1236:         $homeintdom = 1;
                   1237:     } else {
                   1238:         $dom_in_use = $serverhomedom;
                   1239:     }
                   1240:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1241:     unless (defined($cached)) {
                   1242:         my %domconfig =
                   1243:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1244:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1245:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1246:         }
                   1247:     }
                   1248:     if (ref($result) eq 'HASH') {
                   1249:         my $currbalancer = $result->{'lonhost'};
                   1250:         my $currtargets = $result->{'targets'};
                   1251:         my $currrules = $result->{'rules'};
                   1252:         if ($currbalancer ne '') {
                   1253:             my @hosts = &current_machine_ids();
                   1254:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1255:                 $is_balancer = 1;
                   1256:             }
                   1257:         }
                   1258:         if ($is_balancer) {
                   1259:             if (ref($currrules) eq 'HASH') {
                   1260:                 if ($homeintdom) {
                   1261:                     if ($uname ne '') {
                   1262:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1263:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1264:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1265:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1266:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1267:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1268:                             }
                   1269:                         }
                   1270:                         if ($rule_in_effect eq '') {
                   1271:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1272:                             if ($userenv{'inststatus'} ne '') {
                   1273:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1274:                                 my ($othertitle,$usertypes,$types) =
                   1275:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1276:                                 if (ref($types) eq 'ARRAY') {
                   1277:                                     foreach my $type (@{$types}) {
                   1278:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1279:                                             if (exists($currrules->{$type})) {
                   1280:                                                 $rule_in_effect = $currrules->{$type};
                   1281:                                             }
                   1282:                                         }
                   1283:                                     }
                   1284:                                 }
                   1285:                             } else {
                   1286:                                 if (exists($currrules->{'default'})) {
                   1287:                                     $rule_in_effect = $currrules->{'default'};
                   1288:                                 }
                   1289:                             }
                   1290:                         }
                   1291:                     } else {
                   1292:                         if (exists($currrules->{'default'})) {
                   1293:                             $rule_in_effect = $currrules->{'default'};
                   1294:                         }
                   1295:                     }
                   1296:                 } else {
                   1297:                     if ($currrules->{'_LC_external'} ne '') {
                   1298:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1299:                     }
                   1300:                 }
                   1301:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1302:                                                        $uname,$udom);
                   1303:             }
                   1304:         }
                   1305:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1306:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1307:         unless (defined($cached)) {
                   1308:             my %domconfig =
                   1309:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1310:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1311:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1312:             }
                   1313:         }
                   1314:         if (ref($result) eq 'HASH') {
                   1315:             my $currbalancer = $result->{'lonhost'};
                   1316:             my $currtargets = $result->{'targets'};
                   1317:             my $currrules = $result->{'rules'};
                   1318: 
                   1319:             if ($currbalancer eq $lonhost) {
                   1320:                 $is_balancer = 1;
                   1321:                 if (ref($currrules) eq 'HASH') {
                   1322:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1323:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1324:                     }
                   1325:                 }
                   1326:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1327:                                                        $uname,$udom);
                   1328:             }
                   1329:         } else {
                   1330:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1331:                 $is_balancer = 1;
                   1332:                 $offloadto = &this_host_spares($dom_in_use);
                   1333:             }
                   1334:         }
                   1335:     } else {
                   1336:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1337:             $is_balancer = 1;
                   1338:             $offloadto = &this_host_spares($dom_in_use);
                   1339:         }
                   1340:     }
                   1341:     my $lowest_load = 30000;
                   1342:     if (ref($offloadto) eq 'HASH') {
                   1343:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1344:             foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1345:                 ($otherserver,$lowest_load) =
                   1346:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1347:             }
                   1348:         }
                   1349:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
                   1350: 
                   1351:         if (!$found_server) {
                   1352:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1353:                 foreach my $try_server (@{$offloadto->{'default'}}) {
                   1354:                     ($otherserver,$lowest_load) =
                   1355:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1356:                 }
                   1357:             }
                   1358:         }
                   1359:     } elsif (ref($offloadto) eq 'ARRAY') {
                   1360:         if (@{$offloadto} == 1) {
                   1361:             $otherserver = $offloadto->[0];
                   1362:         } elsif (@{$offloadto} > 1) {
                   1363:             foreach my $try_server (@{$offloadto}) {
                   1364:                 ($otherserver,$lowest_load) =
                   1365:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1366:             }
                   1367:         }
                   1368:     }
                   1369:     return ($is_balancer,$otherserver);
                   1370: }
                   1371: 
                   1372: sub get_loadbalancer_targets {
                   1373:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1374:     my $offloadto;
                   1375:     if ($rule_in_effect eq '') {
                   1376:         $offloadto = $currtargets;
                   1377:     } else {
                   1378:         if ($rule_in_effect eq 'homeserver') {
                   1379:             my $homeserver = &homeserver($uname,$udom);
                   1380:             if ($homeserver ne 'no_host') {
                   1381:                 $offloadto = [$homeserver];
                   1382:             }
                   1383:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1384:             my %domconfig =
                   1385:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1386:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1387:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1388:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1389:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1390:                     }
                   1391:                 }
                   1392:             } else {
                   1393:                 my %servers = &dom_servers($udom);
                   1394:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1395:                 if (&hostname($remotebalancer) ne '') {
                   1396:                     $offloadto = [$remotebalancer];
                   1397:                 }
                   1398:             }
                   1399:         } elsif (&hostname($rule_in_effect) ne '') {
                   1400:             $offloadto = [$rule_in_effect];
                   1401:         }
                   1402:     }
                   1403:     return $offloadto;
                   1404: }
                   1405: 
1.1127    raeburn  1406: sub internet_dom_servers {
                   1407:     my ($dom) = @_;
                   1408:     my (%uniqservers,%servers);
                   1409:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1410:     my @machinedoms = &machine_domains($primaryserver);
                   1411:     foreach my $mdom (@machinedoms) {
                   1412:         my %currservers = %servers;
                   1413:         my %server = &get_servers($mdom);
                   1414:         %servers = (%currservers,%server);
                   1415:     }
                   1416:     my %by_hostname;
                   1417:     foreach my $id (keys(%servers)) {
                   1418:         push(@{$by_hostname{$servers{$id}}},$id);
                   1419:     }
                   1420:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1421:         if (@{$by_hostname{$hostname}} > 1) {
                   1422:             my $match = 0;
                   1423:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1424:                 if (&host_domain($id) eq $dom) {
                   1425:                     $uniqservers{$id} = $hostname;
                   1426:                     $match = 1;
                   1427:                 }
                   1428:             }
                   1429:             unless ($match) {
                   1430:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1431:             }
                   1432:         } else {
                   1433:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1434:         }
                   1435:     }
                   1436:     return %uniqservers;
                   1437: }
                   1438: 
1.1       albertel 1439: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1440: 
1.599     albertel 1441: my %homecache;
1.1       albertel 1442: sub homeserver {
1.230     stredwic 1443:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1444:     my $index="$uname:$udom";
1.426     albertel 1445: 
1.599     albertel 1446:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1447: 
                   1448:     my %servers = &get_servers($udom,'library');
                   1449:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1450:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1451: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1452: 
                   1453: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1454: 	if ($answer eq 'found') {
                   1455: 	    delete($badServerCache{$tryserver}); 
                   1456: 	    return $homecache{$index}=$tryserver;
                   1457: 	} elsif ($answer eq 'no_host') {
                   1458: 	    $badServerCache{$tryserver}=1;
                   1459: 	}
1.1       albertel 1460:     }    
                   1461:     return 'no_host';
1.70      www      1462: }
                   1463: 
                   1464: # ------------------------------------- Find the usernames behind a list of IDs
                   1465: 
                   1466: sub idget {
                   1467:     my ($udom,@ids)=@_;
                   1468:     my %returnhash=();
                   1469:     
1.841     albertel 1470:     my %servers = &get_servers($udom,'library');
                   1471:     foreach my $tryserver (keys(%servers)) {
                   1472: 	my $idlist=join('&',@ids);
                   1473: 	$idlist=~tr/A-Z/a-z/; 
                   1474: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1475: 	my @answer=();
                   1476: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1477: 	    @answer=split(/\&/,$reply);
                   1478: 	}                    ;
                   1479: 	my $i;
                   1480: 	for ($i=0;$i<=$#ids;$i++) {
                   1481: 	    if ($answer[$i]) {
                   1482: 		$returnhash{$ids[$i]}=$answer[$i];
                   1483: 	    } 
                   1484: 	}
                   1485:     } 
1.70      www      1486:     return %returnhash;
                   1487: }
                   1488: 
                   1489: # ------------------------------------- Find the IDs behind a list of usernames
                   1490: 
                   1491: sub idrget {
                   1492:     my ($udom,@unames)=@_;
                   1493:     my %returnhash=();
1.800     albertel 1494:     foreach my $uname (@unames) {
                   1495:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1496:     }
1.70      www      1497:     return %returnhash;
                   1498: }
                   1499: 
                   1500: # ------------------------------- Store away a list of names and associated IDs
                   1501: 
                   1502: sub idput {
                   1503:     my ($udom,%ids)=@_;
                   1504:     my %servers=();
1.800     albertel 1505:     foreach my $uname (keys(%ids)) {
                   1506: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1507:         my $uhom=&homeserver($uname,$udom);
1.70      www      1508:         if ($uhom ne 'no_host') {
1.800     albertel 1509:             my $id=&escape($ids{$uname});
1.70      www      1510:             $id=~tr/A-Z/a-z/;
1.800     albertel 1511:             my $esc_unam=&escape($uname);
1.70      www      1512: 	    if ($servers{$uhom}) {
1.800     albertel 1513: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1514:             } else {
1.800     albertel 1515:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1516:             }
                   1517:         }
1.191     harris41 1518:     }
1.800     albertel 1519:     foreach my $server (keys(%servers)) {
                   1520:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1521:     }
1.344     www      1522: }
                   1523: 
1.1023    raeburn  1524: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1525: sub dump_dom {
1.1023    raeburn  1526:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1527:     if (!$udom) {
                   1528:         $udom=$env{'user.domain'};
                   1529:     }
                   1530:     my %returnhash;
1.1023    raeburn  1531:     if ($udom) {
                   1532:         my $uname = &get_domainconfiguser($udom);
                   1533:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1534:     }
                   1535:     return %returnhash;
                   1536: }
                   1537: 
1.1023    raeburn  1538: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1539: 
                   1540: sub get_dom {
1.860     raeburn  1541:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1542:     my $items='';
                   1543:     foreach my $item (@$storearr) {
                   1544:         $items.=&escape($item).'&';
                   1545:     }
                   1546:     $items=~s/\&$//;
1.860     raeburn  1547:     if (!$udom) {
                   1548:         $udom=$env{'user.domain'};
                   1549:         if (defined(&domain($udom,'primary'))) {
                   1550:             $uhome=&domain($udom,'primary');
                   1551:         } else {
1.874     albertel 1552:             undef($uhome);
1.860     raeburn  1553:         }
                   1554:     } else {
                   1555:         if (!$uhome) {
                   1556:             if (defined(&domain($udom,'primary'))) {
                   1557:                 $uhome=&domain($udom,'primary');
                   1558:             }
                   1559:         }
                   1560:     }
                   1561:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1562:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1563:         my %returnhash;
1.875     albertel 1564:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1565:             return %returnhash;
                   1566:         }
1.806     raeburn  1567:         my @pairs=split(/\&/,$rep);
                   1568:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1569:             return @pairs;
                   1570:         }
                   1571:         my $i=0;
                   1572:         foreach my $item (@$storearr) {
                   1573:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1574:             $i++;
                   1575:         }
                   1576:         return %returnhash;
                   1577:     } else {
1.880     banghart 1578:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1579:     }
                   1580: }
                   1581: 
                   1582: # -------------------------------------------- put items in domain db files 
                   1583: 
                   1584: sub put_dom {
1.860     raeburn  1585:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1586:     if (!$udom) {
                   1587:         $udom=$env{'user.domain'};
                   1588:         if (defined(&domain($udom,'primary'))) {
                   1589:             $uhome=&domain($udom,'primary');
                   1590:         } else {
1.874     albertel 1591:             undef($uhome);
1.860     raeburn  1592:         }
                   1593:     } else {
                   1594:         if (!$uhome) {
                   1595:             if (defined(&domain($udom,'primary'))) {
                   1596:                 $uhome=&domain($udom,'primary');
                   1597:             }
                   1598:         }
                   1599:     } 
                   1600:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1601:         my $items='';
                   1602:         foreach my $item (keys(%$storehash)) {
                   1603:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1604:         }
                   1605:         $items=~s/\&$//;
                   1606:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1607:     } else {
1.860     raeburn  1608:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1609:     }
                   1610: }
                   1611: 
1.1023    raeburn  1612: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1613: sub newput_dom {
1.1023    raeburn  1614:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1615:     my $result;
                   1616:     if (!$udom) {
                   1617:         $udom=$env{'user.domain'};
                   1618:     }
1.1023    raeburn  1619:     if ($udom) {
                   1620:         my $uname = &get_domainconfiguser($udom);
                   1621:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1622:     }
                   1623:     return $result;
                   1624: }
                   1625: 
1.1023    raeburn  1626: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1627: sub del_dom {
1.1023    raeburn  1628:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1629:     if (ref($storearr) eq 'ARRAY') {
                   1630:         if (!$udom) {
                   1631:             $udom=$env{'user.domain'};
                   1632:         }
1.1023    raeburn  1633:         if ($udom) {
                   1634:             my $uname = &get_domainconfiguser($udom); 
                   1635:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1636:         }
                   1637:     }
                   1638: }
                   1639: 
1.1023    raeburn  1640: # ----------------------------------construct domainconfig user for a domain 
                   1641: sub get_domainconfiguser {
                   1642:     my ($udom) = @_;
                   1643:     return $udom.'-domainconfig';
                   1644: }
                   1645: 
1.837     raeburn  1646: sub retrieve_inst_usertypes {
                   1647:     my ($udom) = @_;
                   1648:     my (%returnhash,@order);
1.989     raeburn  1649:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1650:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1651:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1652:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1653:         @order = @{$domdefs{'inststatusorder'}};
                   1654:     } else {
                   1655:         if (defined(&domain($udom,'primary'))) {
                   1656:             my $uhome=&domain($udom,'primary');
                   1657:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1658:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1659:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1660:                 return (\%returnhash,\@order);
                   1661:             }
                   1662:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1663:             my @pairs=split(/\&/,$hashitems);
                   1664:             foreach my $item (@pairs) {
                   1665:                 my ($key,$value)=split(/=/,$item,2);
                   1666:                 $key = &unescape($key);
                   1667:                 next if ($key =~ /^error: 2 /);
                   1668:                 $returnhash{$key}=&thaw_unescape($value);
                   1669:             }
                   1670:             my @esc_order = split(/\&/,$orderitems);
                   1671:             foreach my $item (@esc_order) {
                   1672:                 push(@order,&unescape($item));
                   1673:             }
                   1674:         } else {
                   1675:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1676:         }
                   1677:     }
                   1678:     return (\%returnhash,\@order);
                   1679: }
                   1680: 
1.868     raeburn  1681: sub is_domainimage {
                   1682:     my ($url) = @_;
                   1683:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1684:         if (&domain($1) ne '') {
                   1685:             return '1';
                   1686:         }
                   1687:     }
                   1688:     return;
                   1689: }
                   1690: 
1.899     raeburn  1691: sub inst_directory_query {
                   1692:     my ($srch) = @_;
                   1693:     my $udom = $srch->{'srchdomain'};
                   1694:     my %results;
                   1695:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1696:     my $outcome;
1.899     raeburn  1697:     if ($homeserver ne '') {
1.904     albertel 1698: 	my $queryid=&reply("querysend:instdirsearch:".
                   1699: 			   &escape($srch->{'srchby'}).':'.
                   1700: 			   &escape($srch->{'srchterm'}).':'.
                   1701: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1702: 	my $host=&hostname($homeserver);
                   1703: 	if ($queryid !~/^\Q$host\E\_/) {
                   1704: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1705: 	    return;
                   1706: 	}
                   1707: 	my $response = &get_query_reply($queryid);
                   1708: 	my $maxtries = 5;
                   1709: 	my $tries = 1;
                   1710: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1711: 	    $response = &get_query_reply($queryid);
                   1712: 	    $tries ++;
                   1713: 	}
                   1714: 
                   1715:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1716:             if ($response eq 'unavailable') {
                   1717:                 $outcome = $response;
                   1718:             } else {
                   1719:                 $outcome = 'ok';
                   1720:                 my @matches = split(/\n/,$response);
                   1721:                 foreach my $match (@matches) {
                   1722:                     my ($key,$value) = split(/=/,$match);
                   1723:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1724:                 }
1.899     raeburn  1725:             }
                   1726:         }
                   1727:     }
1.909     raeburn  1728:     return ($outcome,%results);
1.899     raeburn  1729: }
                   1730: 
                   1731: sub usersearch {
                   1732:     my ($srch) = @_;
                   1733:     my $dom = $srch->{'srchdomain'};
                   1734:     my %results;
                   1735:     my %libserv = &all_library();
                   1736:     my $query = 'usersearch';
                   1737:     foreach my $tryserver (keys(%libserv)) {
                   1738:         if (&host_domain($tryserver) eq $dom) {
                   1739:             my $host=&hostname($tryserver);
                   1740:             my $queryid=
1.911     raeburn  1741:                 &reply("querysend:".&escape($query).':'.
                   1742:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1743:                        &escape($srch->{'srchtype'}).':'.
                   1744:                        &escape($srch->{'srchterm'}),$tryserver);
                   1745:             if ($queryid !~/^\Q$host\E\_/) {
                   1746:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1747:                 next;
1.899     raeburn  1748:             }
                   1749:             my $reply = &get_query_reply($queryid);
                   1750:             my $maxtries = 1;
                   1751:             my $tries = 1;
                   1752:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1753:                 $reply = &get_query_reply($queryid);
                   1754:                 $tries ++;
                   1755:             }
                   1756:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1757:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1758:             } else {
1.911     raeburn  1759:                 my @matches;
                   1760:                 if ($reply =~ /\n/) {
                   1761:                     @matches = split(/\n/,$reply);
                   1762:                 } else {
                   1763:                     @matches = split(/\&/,$reply);
                   1764:                 }
1.899     raeburn  1765:                 foreach my $match (@matches) {
                   1766:                     my ($uname,$udom,%userhash);
1.911     raeburn  1767:                     foreach my $entry (split(/:/,$match)) {
                   1768:                         my ($key,$value) =
                   1769:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1770:                         $userhash{$key} = $value;
                   1771:                         if ($key eq 'username') {
                   1772:                             $uname = $value;
                   1773:                         } elsif ($key eq 'domain') {
                   1774:                             $udom = $value;
1.911     raeburn  1775:                         }
1.899     raeburn  1776:                     }
                   1777:                     $results{$uname.':'.$udom} = \%userhash;
                   1778:                 }
                   1779:             }
                   1780:         }
                   1781:     }
                   1782:     return %results;
                   1783: }
                   1784: 
1.912     raeburn  1785: sub get_instuser {
                   1786:     my ($udom,$uname,$id) = @_;
                   1787:     my $homeserver = &domain($udom,'primary');
                   1788:     my ($outcome,%results);
                   1789:     if ($homeserver ne '') {
                   1790:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1791:                            &escape($id).':'.&escape($udom),$homeserver);
                   1792:         my $host=&hostname($homeserver);
                   1793:         if ($queryid !~/^\Q$host\E\_/) {
                   1794:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1795:             return;
                   1796:         }
                   1797:         my $response = &get_query_reply($queryid);
                   1798:         my $maxtries = 5;
                   1799:         my $tries = 1;
                   1800:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1801:             $response = &get_query_reply($queryid);
                   1802:             $tries ++;
                   1803:         }
                   1804:         if (!&error($response) && $response ne 'refused') {
                   1805:             if ($response eq 'unavailable') {
                   1806:                 $outcome = $response;
                   1807:             } else {
                   1808:                 $outcome = 'ok';
                   1809:                 my @matches = split(/\n/,$response);
                   1810:                 foreach my $match (@matches) {
                   1811:                     my ($key,$value) = split(/=/,$match);
                   1812:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1813:                 }
                   1814:             }
                   1815:         }
                   1816:     }
                   1817:     my %userinfo;
                   1818:     if (ref($results{$uname}) eq 'HASH') {
                   1819:         %userinfo = %{$results{$uname}};
                   1820:     } 
                   1821:     return ($outcome,%userinfo);
                   1822: }
                   1823: 
                   1824: sub inst_rulecheck {
1.923     raeburn  1825:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1826:     my %returnhash;
                   1827:     if ($udom ne '') {
                   1828:         if (ref($rules) eq 'ARRAY') {
                   1829:             @{$rules} = map {&escape($_);} (@{$rules});
                   1830:             my $rulestr = join(':',@{$rules});
                   1831:             my $homeserver=&domain($udom,'primary');
                   1832:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1833:                 my $response;
                   1834:                 if ($item eq 'username') {                
                   1835:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1836:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1837:                                               $homeserver));
1.923     raeburn  1838:                 } elsif ($item eq 'id') {
                   1839:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1840:                                               ':'.&escape($id).':'.$rulestr,
                   1841:                                               $homeserver));
1.945     raeburn  1842:                 } elsif ($item eq 'selfcreate') {
                   1843:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1844:                                                &escape($udom).':'.&escape($uname).
                   1845:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1846:                 }
1.912     raeburn  1847:                 if ($response ne 'refused') {
                   1848:                     my @pairs=split(/\&/,$response);
                   1849:                     foreach my $item (@pairs) {
                   1850:                         my ($key,$value)=split(/=/,$item,2);
                   1851:                         $key = &unescape($key);
                   1852:                         next if ($key =~ /^error: 2 /);
                   1853:                         $returnhash{$key}=&thaw_unescape($value);
                   1854:                     }
                   1855:                 }
                   1856:             }
                   1857:         }
                   1858:     }
                   1859:     return %returnhash;
                   1860: }
                   1861: 
                   1862: sub inst_userrules {
1.923     raeburn  1863:     my ($udom,$check) = @_;
1.912     raeburn  1864:     my (%ruleshash,@ruleorder);
                   1865:     if ($udom ne '') {
                   1866:         my $homeserver=&domain($udom,'primary');
                   1867:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1868:             my $response;
                   1869:             if ($check eq 'id') {
                   1870:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1871:                                  $homeserver);
1.943     raeburn  1872:             } elsif ($check eq 'email') {
                   1873:                 $response=&reply('instemailrules:'.&escape($udom),
                   1874:                                  $homeserver);
1.923     raeburn  1875:             } else {
                   1876:                 $response=&reply('instuserrules:'.&escape($udom),
                   1877:                                  $homeserver);
                   1878:             }
1.912     raeburn  1879:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1880:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1881:                 ($response ne 'no_such_host')) {
                   1882:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1883:                 my @pairs=split(/\&/,$hashitems);
                   1884:                 foreach my $item (@pairs) {
                   1885:                     my ($key,$value)=split(/=/,$item,2);
                   1886:                     $key = &unescape($key);
                   1887:                     next if ($key =~ /^error: 2 /);
                   1888:                     $ruleshash{$key}=&thaw_unescape($value);
                   1889:                 }
                   1890:                 my @esc_order = split(/\&/,$orderitems);
                   1891:                 foreach my $item (@esc_order) {
                   1892:                     push(@ruleorder,&unescape($item));
                   1893:                 }
                   1894:             }
                   1895:         }
                   1896:     }
                   1897:     return (\%ruleshash,\@ruleorder);
                   1898: }
                   1899: 
1.976     raeburn  1900: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1901: 
                   1902: sub get_domain_defaults {
                   1903:     my ($domain) = @_;
                   1904:     my $cachetime = 60*60*24;
                   1905:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1906:     if (defined($cached)) {
                   1907:         if (ref($result) eq 'HASH') {
                   1908:             return %{$result};
                   1909:         }
                   1910:     }
                   1911:     my %domdefaults;
                   1912:     my %domconfig =
1.989     raeburn  1913:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1914:                                   'requestcourses','inststatus',
1.1073    raeburn  1915:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1916:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1917:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1918:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1919:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1920:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1921:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943     raeburn  1922:     } else {
                   1923:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1924:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1925:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1926:     }
1.976     raeburn  1927:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1928:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1929:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1930:         } else {
                   1931:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1932:         } 
                   1933:         my @usertools = ('aboutme','blog','portfolio');
                   1934:         foreach my $item (@usertools) {
                   1935:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1936:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1937:             }
                   1938:         }
                   1939:     }
1.985     raeburn  1940:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1941:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1942:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1943:         }
                   1944:     }
1.989     raeburn  1945:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1946:         foreach my $item ('inststatustypes','inststatusorder') {
                   1947:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1948:         }
                   1949:     }
1.1047    raeburn  1950:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1951:         foreach my $item ('canuse_pdfforms') {
                   1952:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1953:         }
                   1954:     }
1.1073    raeburn  1955:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1956:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1957:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1958:         }
                   1959:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1960:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1961:         }
                   1962:     }
1.943     raeburn  1963:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1964:                                   $cachetime);
                   1965:     return %domdefaults;
                   1966: }
                   1967: 
1.344     www      1968: # --------------------------------------------------- Assign a key to a student
                   1969: 
                   1970: sub assign_access_key {
1.364     www      1971: #
                   1972: # a valid key looks like uname:udom#comments
                   1973: # comments are being appended
                   1974: #
1.498     www      1975:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1976:     $kdom=
1.620     albertel 1977:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1978:     $knum=
1.620     albertel 1979:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1980:     $cdom=
1.620     albertel 1981:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1982:     $cnum=
1.620     albertel 1983:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1984:     $udom=$env{'user.name'} unless (defined($udom));
                   1985:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1986:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1987:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1988:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1989:                                                   # assigned to this person
                   1990:                                                   # - this should not happen,
1.345     www      1991:                                                   # unless something went wrong
                   1992:                                                   # the first time around
                   1993: # ready to assign
1.364     www      1994:         $logentry=$1.'; '.$logentry;
1.496     www      1995:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1996:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1997: # key now belongs to user
1.346     www      1998: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      1999:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2000:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2001:                 return 'ok';
                   2002:             } else {
                   2003:                 return 
                   2004:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2005: 	    }
                   2006:         } else {
                   2007:             return 'error: Could not assign key, try again later.';
                   2008:         }
1.364     www      2009:     } elsif (!$existing{$ckey}) {
1.345     www      2010: # the key does not exist
                   2011: 	return 'error: The key does not exist';
                   2012:     } else {
                   2013: # the key is somebody else's
                   2014: 	return 'error: The key is already in use';
                   2015:     }
1.344     www      2016: }
                   2017: 
1.364     www      2018: # ------------------------------------------ put an additional comment on a key
                   2019: 
                   2020: sub comment_access_key {
                   2021: #
                   2022: # a valid key looks like uname:udom#comments
                   2023: # comments are being appended
                   2024: #
                   2025:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2026:     $cdom=
1.620     albertel 2027:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2028:     $cnum=
1.620     albertel 2029:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2030:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2031:     if ($existing{$ckey}) {
                   2032:         $existing{$ckey}.='; '.$logentry;
                   2033: # ready to assign
1.367     www      2034:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2035:                                                  $cdom,$cnum) eq 'ok') {
                   2036: 	    return 'ok';
                   2037:         } else {
                   2038: 	    return 'error: Count not store comment.';
                   2039:         }
                   2040:     } else {
                   2041: # the key does not exist
                   2042: 	return 'error: The key does not exist';
                   2043:     }
                   2044: }
                   2045: 
1.344     www      2046: # ------------------------------------------------------ Generate a set of keys
                   2047: 
                   2048: sub generate_access_keys {
1.364     www      2049:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2050:     $cdom=
1.620     albertel 2051:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2052:     $cnum=
1.620     albertel 2053:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2054:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2055:     unless (($cdom) && ($cnum)) { return 0; }
                   2056:     if ($number>10000) { return 0; }
                   2057:     sleep(2); # make sure don't get same seed twice
                   2058:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2059:     my $total=0;
                   2060:     for (my $i=1;$i<=$number;$i++) {
                   2061:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2062:                   sprintf("%lx",int(100000*rand)).'-'.
                   2063:                   sprintf("%lx",int(100000*rand));
                   2064:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2065:        $newkey=~s/0/h/g; # and also 0 and O
                   2066:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2067:        if ($existing{$newkey}) {
                   2068:            $i--;
                   2069:        } else {
1.364     www      2070: 	  if (&put('accesskeys',
                   2071:               { $newkey => '# generated '.localtime().
1.620     albertel 2072:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2073:                            '; '.$logentry },
                   2074: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2075:               $total++;
                   2076: 	  }
                   2077:        }
                   2078:     }
1.620     albertel 2079:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2080:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2081:     return $total;
                   2082: }
                   2083: 
                   2084: # ------------------------------------------------------- Validate an accesskey
                   2085: 
                   2086: sub validate_access_key {
                   2087:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2088:     $cdom=
1.620     albertel 2089:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2090:     $cnum=
1.620     albertel 2091:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2092:     $udom=$env{'user.domain'} unless (defined($udom));
                   2093:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2094:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2095:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2096: }
                   2097: 
                   2098: # ------------------------------------- Find the section of student in a course
1.652     albertel 2099: sub devalidate_getsection_cache {
                   2100:     my ($udom,$unam,$courseid)=@_;
                   2101:     my $hashid="$udom:$unam:$courseid";
                   2102:     &devalidate_cache_new('getsection',$hashid);
                   2103: }
1.298     matthew  2104: 
1.815     albertel 2105: sub courseid_to_courseurl {
                   2106:     my ($courseid) = @_;
                   2107:     #already url style courseid
                   2108:     return $courseid if ($courseid =~ m{^/});
                   2109: 
                   2110:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2111: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2112: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2113: 	return "/$cdom/$cnum";
                   2114:     }
                   2115: 
                   2116:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2117:     if (exists($courseinfo{'num'})) {
                   2118: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2119:     }
                   2120: 
                   2121:     return undef;
                   2122: }
                   2123: 
1.298     matthew  2124: sub getsection {
                   2125:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2126:     my $cachetime=1800;
1.551     albertel 2127: 
                   2128:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2129:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2130:     if (defined($cached)) { return $result; }
                   2131: 
1.298     matthew  2132:     my %Pending; 
                   2133:     my %Expired;
                   2134:     #
                   2135:     # Each role can either have not started yet (pending), be active, 
                   2136:     #    or have expired.
                   2137:     #
                   2138:     # If there is an active role, we are done.
                   2139:     #
                   2140:     # If there is more than one role which has not started yet, 
                   2141:     #     choose the one which will start sooner
                   2142:     # If there is one role which has not started yet, return it.
                   2143:     #
                   2144:     # If there is more than one expired role, choose the one which ended last.
                   2145:     # If there is a role which has expired, return it.
                   2146:     #
1.815     albertel 2147:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  2148:     my $extra = &freeze_escape({'skipcheck' => 1});
                   2149:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  2150:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2151:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2152:         my $section=$1;
                   2153:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2154:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2155:         my $now=time;
1.548     albertel 2156:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2157:             $Expired{$end}=$section;
                   2158:             next;
                   2159:         }
1.548     albertel 2160:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2161:             $Pending{$start}=$section;
                   2162:             next;
                   2163:         }
1.599     albertel 2164:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2165:     }
                   2166:     #
                   2167:     # Presumedly there will be few matching roles from the above
                   2168:     # loop and the sorting time will be negligible.
                   2169:     if (scalar(keys(%Pending))) {
                   2170:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2171:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2172:     } 
                   2173:     if (scalar(keys(%Expired))) {
                   2174:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2175:         my $time = pop(@sorted);
1.599     albertel 2176:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2177:     }
1.599     albertel 2178:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2179: }
1.70      www      2180: 
1.599     albertel 2181: sub save_cache {
                   2182:     &purge_remembered();
1.722     albertel 2183:     #&Apache::loncommon::validate_page();
1.620     albertel 2184:     undef(%env);
1.780     albertel 2185:     undef($env_loaded);
1.599     albertel 2186: }
1.452     albertel 2187: 
1.599     albertel 2188: my $to_remember=-1;
                   2189: my %remembered;
                   2190: my %accessed;
                   2191: my $kicks=0;
                   2192: my $hits=0;
1.849     albertel 2193: sub make_key {
                   2194:     my ($name,$id) = @_;
1.872     albertel 2195:     if (length($id) > 65 
                   2196: 	&& length(&escape($id)) > 200) {
                   2197: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2198:     }
1.849     albertel 2199:     return &escape($name.':'.$id);
                   2200: }
                   2201: 
1.599     albertel 2202: sub devalidate_cache_new {
                   2203:     my ($name,$id,$debug) = @_;
                   2204:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2205:     $id=&make_key($name,$id);
1.599     albertel 2206:     $memcache->delete($id);
                   2207:     delete($remembered{$id});
                   2208:     delete($accessed{$id});
                   2209: }
                   2210: 
                   2211: sub is_cached_new {
                   2212:     my ($name,$id,$debug) = @_;
1.849     albertel 2213:     $id=&make_key($name,$id);
1.599     albertel 2214:     if (exists($remembered{$id})) {
                   2215: 	if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
                   2216: 	$accessed{$id}=[&gettimeofday()];
                   2217: 	$hits++;
                   2218: 	return ($remembered{$id},1);
                   2219:     }
                   2220:     my $value = $memcache->get($id);
                   2221:     if (!(defined($value))) {
                   2222: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2223: 	return (undef,undef);
1.416     albertel 2224:     }
1.599     albertel 2225:     if ($value eq '__undef__') {
                   2226: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2227: 	$value=undef;
                   2228:     }
                   2229:     &make_room($id,$value,$debug);
                   2230:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2231:     return ($value,1);
                   2232: }
                   2233: 
                   2234: sub do_cache_new {
                   2235:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2236:     $id=&make_key($name,$id);
1.599     albertel 2237:     my $setvalue=$value;
                   2238:     if (!defined($setvalue)) {
                   2239: 	$setvalue='__undef__';
                   2240:     }
1.623     albertel 2241:     if (!defined($time) ) {
                   2242: 	$time=600;
                   2243:     }
1.599     albertel 2244:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2245:     my $result = $memcache->set($id,$setvalue,$time);
                   2246:     if (! $result) {
1.872     albertel 2247: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2248: 	$memcache->disconnect_all();
1.872     albertel 2249:     }
1.600     albertel 2250:     # need to make a copy of $value
1.919     albertel 2251:     &make_room($id,$value,$debug);
1.599     albertel 2252:     return $value;
                   2253: }
                   2254: 
                   2255: sub make_room {
                   2256:     my ($id,$value,$debug)=@_;
1.919     albertel 2257: 
                   2258:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2259:                                     : $value;
1.599     albertel 2260:     if ($to_remember<0) { return; }
                   2261:     $accessed{$id}=[&gettimeofday()];
                   2262:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2263:     my $to_kick;
                   2264:     my $max_time=0;
                   2265:     foreach my $other (keys(%accessed)) {
                   2266: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2267: 	    $to_kick=$other;
                   2268: 	    $max_time=&tv_interval($accessed{$other});
                   2269: 	}
                   2270:     }
                   2271:     delete($remembered{$to_kick});
                   2272:     delete($accessed{$to_kick});
                   2273:     $kicks++;
                   2274:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2275:     return;
                   2276: }
                   2277: 
1.599     albertel 2278: sub purge_remembered {
1.604     albertel 2279:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2280:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2281:     undef(%remembered);
                   2282:     undef(%accessed);
1.428     albertel 2283: }
1.70      www      2284: # ------------------------------------- Read an entry from a user's environment
                   2285: 
                   2286: sub userenvironment {
                   2287:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2288:     my $items;
                   2289:     foreach my $item (@what) {
                   2290:         $items.=&escape($item).'&';
                   2291:     }
                   2292:     $items=~s/\&$//;
1.70      www      2293:     my %returnhash=();
1.1009    raeburn  2294:     my $uhome = &homeserver($unam,$udom);
                   2295:     unless ($uhome eq 'no_host') {
                   2296:         my @answer=split(/\&/, 
                   2297:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2298:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2299:             return %returnhash;
                   2300:         }
1.1009    raeburn  2301:         my $i;
                   2302:         for ($i=0;$i<=$#what;$i++) {
                   2303: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2304:         }
1.70      www      2305:     }
                   2306:     return %returnhash;
1.1       albertel 2307: }
                   2308: 
1.617     albertel 2309: # ---------------------------------------------------------- Get a studentphoto
                   2310: sub studentphoto {
                   2311:     my ($udom,$unam,$ext) = @_;
                   2312:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2313:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2314:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2315:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2316:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2317:             } else {
                   2318:                 my ($result,$perm_reqd)=
1.707     albertel 2319: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2320:                 if ($result eq 'ok') {
                   2321:                     if (!($perm_reqd eq 'yes')) {
                   2322:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2323:                     }
                   2324:                 }
                   2325:             }
                   2326:         }
                   2327:     } else {
                   2328:         my ($result,$perm_reqd) = 
1.707     albertel 2329: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2330:         if ($result eq 'ok') {
                   2331:             if (!($perm_reqd eq 'yes')) {
                   2332:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2333:             }
                   2334:         }
                   2335:     }
                   2336:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2337: }
                   2338: 
                   2339: sub retrievestudentphoto {
                   2340:     my ($udom,$unam,$ext,$type) = @_;
                   2341:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2342:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2343:     if ($ret eq 'ok') {
                   2344:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2345:         if ($type eq 'thumbnail') {
                   2346:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2347:         }
                   2348:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2349:         return $tokenurl;
                   2350:     } else {
                   2351:         if ($type eq 'thumbnail') {
                   2352:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2353:         } else { 
                   2354:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2355:         }
1.617     albertel 2356:     }
                   2357: }
                   2358: 
1.263     www      2359: # -------------------------------------------------------------------- New chat
                   2360: 
                   2361: sub chatsend {
1.724     raeburn  2362:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2363:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2364:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2365:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2366:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2367: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2368: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2369: }
                   2370: 
                   2371: # ------------------------------------------ Find current version of a resource
                   2372: 
                   2373: sub getversion {
                   2374:     my $fname=&clutter(shift);
                   2375:     unless ($fname=~/^\/res\//) { return -1; }
                   2376:     return &currentversion(&filelocation('',$fname));
                   2377: }
                   2378: 
                   2379: sub currentversion {
                   2380:     my $fname=shift;
                   2381:     my $author=$fname;
                   2382:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2383:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2384:     my $home=&homeserver($uname,$udom);
1.292     www      2385:     if ($home eq 'no_host') { 
                   2386:         return -1; 
                   2387:     }
1.1112    www      2388:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2389:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2390: 	return -1;
                   2391:     }
1.1112    www      2392:     return $answer;
1.263     www      2393: }
                   2394: 
1.1111    www      2395: #
                   2396: # Return special version number of resource if set by override, empty otherwise
                   2397: #
                   2398: sub usedversion {
                   2399:     my $fname=shift;
                   2400:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2401:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2402:     if ($urlversion) { return $urlversion; }
                   2403:     return '';
                   2404: }
                   2405: 
1.1       albertel 2406: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2407: 
1.1       albertel 2408: sub subscribe {
                   2409:     my $fname=shift;
1.761     raeburn  2410:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2411:     $fname=~s/[\n\r]//g;
1.1       albertel 2412:     my $author=$fname;
                   2413:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2414:     my ($udom,$uname)=split(/\//,$author);
                   2415:     my $home=homeserver($uname,$udom);
1.335     albertel 2416:     if ($home eq 'no_host') {
                   2417:         return 'not_found';
1.1       albertel 2418:     }
                   2419:     my $answer=reply("sub:$fname",$home);
1.64      www      2420:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2421: 	$answer.=' by '.$home;
                   2422:     }
1.1       albertel 2423:     return $answer;
                   2424: }
                   2425:     
1.8       www      2426: # -------------------------------------------------------------- Replicate file
                   2427: 
                   2428: sub repcopy {
                   2429:     my $filename=shift;
1.23      www      2430:     $filename=~s/\/+/\//g;
1.607     raeburn  2431:     if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
                   2432:     if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 2433:     if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609     banghart 2434: 	$filename=~m -^/*(uploaded|editupload)/-) { 
1.538     albertel 2435: 	return &repcopy_userfile($filename);
                   2436:     }
1.532     albertel 2437:     $filename=~s/[\n\r]//g;
1.8       www      2438:     my $transname="$filename.in.transfer";
1.828     www      2439: # FIXME: this should flock
1.607     raeburn  2440:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2441:     my $remoteurl=subscribe($filename);
1.64      www      2442:     if ($remoteurl =~ /^con_lost by/) {
                   2443: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2444:            return 'unavailable';
1.8       www      2445:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2446: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2447: 	   return 'not_found';
1.64      www      2448:     } elsif ($remoteurl =~ /^rejected by/) {
                   2449: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2450:            return 'forbidden';
1.20      www      2451:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2452:            return 'ok';
1.8       www      2453:     } else {
1.290     www      2454:         my $author=$filename;
                   2455:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2456:         my ($udom,$uname)=split(/\//,$author);
                   2457:         my $home=homeserver($uname,$udom);
                   2458:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2459:            my @parts=split(/\//,$filename);
                   2460:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
                   2461:            if ($path ne "$perlvar{'lonDocRoot'}/res") {
                   2462:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2463: 	       return 'bad_request';
1.8       www      2464:            }
                   2465:            my $count;
                   2466:            for ($count=5;$count<$#parts;$count++) {
                   2467:                $path.="/$parts[$count]";
                   2468:                if ((-e $path)!=1) {
                   2469: 		   mkdir($path,0777);
                   2470:                }
                   2471:            }
                   2472:            my $ua=new LWP::UserAgent;
                   2473:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2474:            my $response=$ua->request($request,$transname);
                   2475:            if ($response->is_error()) {
                   2476: 	       unlink($transname);
                   2477:                my $message=$response->status_line;
1.672     albertel 2478:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2479:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2480:                return 'unavailable';
1.8       www      2481:            } else {
1.16      www      2482: 	       if ($remoteurl!~/\.meta$/) {
                   2483:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2484:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2485:                   if ($mresponse->is_error()) {
                   2486: 		      unlink($filename.'.meta');
                   2487:                       &logthis(
1.672     albertel 2488:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2489:                   }
                   2490: 	       }
1.8       www      2491:                rename($transname,$filename);
1.607     raeburn  2492:                return 'ok';
1.8       www      2493:            }
1.290     www      2494:        }
1.8       www      2495:     }
1.330     www      2496: }
                   2497: 
                   2498: # ------------------------------------------------ Get server side include body
                   2499: sub ssi_body {
1.381     albertel 2500:     my ($filelink,%form)=@_;
1.606     matthew  2501:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2502:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2503:     }
1.953     www      2504:     my $output='';
                   2505:     my $response;
1.980     raeburn  2506:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2507:        ($output,$response)=&externalssi($filelink);
1.953     www      2508:     } else {
1.1004    droeschl 2509:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2510:        $filelink .= 'inhibitmenu=yes';
1.953     www      2511:        ($output,$response)=&ssi($filelink,%form);
                   2512:     }
1.778     albertel 2513:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2514:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2515:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2516:     if (wantarray) {
                   2517:         return ($output, $response);
                   2518:     } else {
                   2519:         return $output;
                   2520:     }
1.8       www      2521: }
                   2522: 
1.15      www      2523: # --------------------------------------------------------- Server Side Include
                   2524: 
1.782     albertel 2525: sub absolute_url {
                   2526:     my ($host_name) = @_;
                   2527:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2528:     if ($host_name eq '') {
                   2529: 	$host_name = $ENV{'SERVER_NAME'};
                   2530:     }
                   2531:     return $protocol.$host_name;
                   2532: }
                   2533: 
1.942     foxr     2534: #
                   2535: #   Server side include.
                   2536: # Parameters:
                   2537: #  fn     Possibly encrypted resource name/id.
                   2538: #  form   Hash that describes how the rendering should be done
                   2539: #         and other things.
1.944     foxr     2540: # Returns:
1.950     raeburn  2541: #   Scalar context: The content of the response.
                   2542: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2543: #     
1.15      www      2544: sub ssi {
                   2545: 
1.944     foxr     2546:     my ($fn,%form)=@_;
1.15      www      2547:     my $ua=new LWP::UserAgent;
1.23      www      2548:     my $request;
1.711     albertel 2549: 
                   2550:     $form{'no_update_last_known'}=1;
1.895     albertel 2551:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2552:     if (%form) {
1.782     albertel 2553:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2554:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2555:     } else {
1.782     albertel 2556:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2557:     }
                   2558: 
1.15      www      2559:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2560:     my $response=$ua->request($request);
                   2561: 
1.944     foxr     2562:     if (wantarray) {
                   2563: 	return ($response->content, $response);
                   2564:     } else {
                   2565: 	return $response->content;
1.942     foxr     2566:     }
1.324     www      2567: }
                   2568: 
                   2569: sub externalssi {
                   2570:     my ($url)=@_;
                   2571:     my $ua=new LWP::UserAgent;
                   2572:     my $request=new HTTP::Request('GET',$url);
                   2573:     my $response=$ua->request($request);
1.954     raeburn  2574:     if (wantarray) {
                   2575:         return ($response->content, $response);
                   2576:     } else {
                   2577:         return $response->content;
                   2578:     }
1.15      www      2579: }
1.254     www      2580: 
1.492     albertel 2581: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2582: 
                   2583: sub allowuploaded {
                   2584:     my ($srcurl,$url)=@_;
                   2585:     $url=&clutter(&declutter($url));
                   2586:     my $dir=$url;
                   2587:     $dir=~s/\/[^\/]+$//;
                   2588:     my %httpref=();
                   2589:     my $httpurl=&hreflocation('',$url);
                   2590:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2591:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2592: }
1.477     raeburn  2593: 
1.478     albertel 2594: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2595: # input: action, courseID, current domain, intended
1.637     raeburn  2596: #        path to file, source of file, instruction to parse file for objects,
                   2597: #        ref to hash for embedded objects,
                   2598: #        ref to hash for codebase of java objects.
1.1095    raeburn  2599: #        reference to scalar to accommodate mime type determined
                   2600: #          from File::MMagic if $parser = parse.
1.637     raeburn  2601: #
1.485     raeburn  2602: # output: url to file (if action was uploaddoc), 
                   2603: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2604: #
1.478     albertel 2605: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2606: # course.
1.477     raeburn  2607: #
1.478     albertel 2608: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2609: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2610: #          course's home server.
1.477     raeburn  2611: #
1.478     albertel 2612: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2613: #          be copied from $source (current location) to 
                   2614: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2615: #         and will then be copied to
                   2616: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2617: #         course's home server.
1.485     raeburn  2618: #
1.481     raeburn  2619: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2620: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2621: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2622: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2623: #         in course's home server.
1.637     raeburn  2624: #
1.477     raeburn  2625: 
                   2626: sub process_coursefile {
1.1095    raeburn  2627:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2628:         $mimetype)=@_;
1.477     raeburn  2629:     my $fetchresult;
1.638     albertel 2630:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2631:     if ($action eq 'propagate') {
1.638     albertel 2632:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2633: 			     $home);
1.481     raeburn  2634:     } else {
1.477     raeburn  2635:         my $fpath = '';
                   2636:         my $fname = $file;
1.478     albertel 2637:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2638:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2639:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2640:         if ($action eq 'copy') {
                   2641:             if ($source eq '') {
                   2642:                 $fetchresult = 'no source file';
                   2643:                 return $fetchresult;
                   2644:             } else {
                   2645:                 my $destination = $filepath.'/'.$fname;
                   2646:                 rename($source,$destination);
                   2647:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2648:                                  $home);
1.481     raeburn  2649:             }
                   2650:         } elsif ($action eq 'uploaddoc') {
                   2651:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2652:             print $fh $env{'form.'.$source};
1.481     raeburn  2653:             close($fh);
1.637     raeburn  2654:             if ($parser eq 'parse') {
1.1024    raeburn  2655:                 my $mm = new File::MMagic;
1.1095    raeburn  2656:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2657:                 if ($type eq 'text/html') {
1.1024    raeburn  2658:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2659:                     unless ($parse_result eq 'ok') {
                   2660:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2661:                     }
1.637     raeburn  2662:                 }
1.1095    raeburn  2663:                 if (ref($mimetype)) {
                   2664:                     $$mimetype = $type;
                   2665:                 } 
1.637     raeburn  2666:             }
1.477     raeburn  2667:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2668:                                  $home);
1.481     raeburn  2669:             if ($fetchresult eq 'ok') {
                   2670:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2671:             } else {
                   2672:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2673:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2674:                 return '/adm/notfound.html';
                   2675:             }
1.477     raeburn  2676:         }
                   2677:     }
1.485     raeburn  2678:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2679:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2680:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2681:     }
                   2682:     return $fetchresult;
                   2683: }
                   2684: 
1.637     raeburn  2685: sub build_filepath {
                   2686:     my ($fpath) = @_;
                   2687:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2688:     unless ($fpath eq '') {
                   2689:         my @parts=split('/',$fpath);
                   2690:         foreach my $part (@parts) {
                   2691:             $filepath.= '/'.$part;
                   2692:             if ((-e $filepath)!=1) {
                   2693:                 mkdir($filepath,0777);
                   2694:             }
                   2695:         }
                   2696:     }
                   2697:     return $filepath;
                   2698: }
                   2699: 
                   2700: sub store_edited_file {
1.638     albertel 2701:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2702:     my $file = $primary_url;
                   2703:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2704:     my $fpath = '';
                   2705:     my $fname = $file;
                   2706:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2707:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2708:     my $filepath = &build_filepath($fpath);
                   2709:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2710:     print $fh $content;
                   2711:     close($fh);
1.638     albertel 2712:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2713:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2714: 			  $home);
1.637     raeburn  2715:     if ($$fetchresult eq 'ok') {
                   2716:         return '/uploaded/'.$fpath.'/'.$fname;
                   2717:     } else {
1.638     albertel 2718:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2719: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2720:         return '/adm/notfound.html';
                   2721:     }
                   2722: }
                   2723: 
1.531     albertel 2724: sub clean_filename {
1.831     albertel 2725:     my ($fname,$args)=@_;
1.315     www      2726: # Replace Windows backslashes by forward slashes
1.257     www      2727:     $fname=~s/\\/\//g;
1.831     albertel 2728:     if (!$args->{'keep_path'}) {
                   2729:         # Get rid of everything but the actual filename
                   2730: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2731:     }
1.315     www      2732: # Replace spaces by underscores
                   2733:     $fname=~s/\s+/\_/g;
                   2734: # Replace all other weird characters by nothing
1.831     albertel 2735:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2736: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2737: # numbers
                   2738:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2739:     return $fname;
                   2740: }
1.1051    raeburn  2741: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2742: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2743: # image with the same aspect ratio as the original, but with dimensions which do 
                   2744: # not exceed $resizewidth and $resizeheight.
                   2745:  
1.984     neumanie 2746: sub resizeImage {
1.1051    raeburn  2747:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2748:     my $ima = Image::Magick->new;
                   2749:     my $resized;
                   2750:     if (-e $img_path) {
                   2751:         $ima->Read($img_path);
                   2752:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2753:             my $width = $ima->Get('width');
                   2754:             my $height = $ima->Get('height');
                   2755:             if ($width > $resizewidth) {
                   2756: 	        my $factor = $width/$resizewidth;
                   2757:                 my $newheight = $height/$factor;
                   2758:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2759:                 $resized = 1;
                   2760:             }
                   2761:         }
                   2762:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2763:             my $width = $ima->Get('width');
                   2764:             my $height = $ima->Get('height');
                   2765:             if ($height > $resizeheight) {
                   2766:                 my $factor = $height/$resizeheight;
                   2767:                 my $newwidth = $width/$factor;
                   2768:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2769:                 $resized = 1;
                   2770:             }
                   2771:         }
                   2772:         if ($resized) {
                   2773:             $ima->Write($img_path);
                   2774:         }
                   2775:     }
                   2776:     return;
1.977     amueller 2777: }
                   2778: 
1.608     albertel 2779: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2780: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2781: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2782: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2783: #                                    canceloverwrite, or ''. 
                   2784: #                   if 'coursedoc': upload to the current course
                   2785: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2786: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2787: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2788: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2789: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2790: #        $allfiles - reference to hash for embedded objects
                   2791: #        $codebase - reference to hash for codebase of java objects
                   2792: #        $desuname - username for permanent storage of uploaded file
                   2793: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2794: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2795: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2796: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2797: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2798: #        $mimetype - reference to scalar to accommodate mime type determined
                   2799: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2800: # 
1.686     albertel 2801: # output: url of file in userspace, or error: <message> 
                   2802: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2803: 
1.531     albertel 2804: sub userfileupload {
1.1090    raeburn  2805:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2806:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2807:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2808:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2809:     $fname=&clean_filename($fname);
1.1090    raeburn  2810:     # See if there is anything left
1.257     www      2811:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2812:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2813:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2814:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2815:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2816:         my $now = time;
1.1090    raeburn  2817:         my $filepath;
1.1095    raeburn  2818:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2819:              $filepath = 'tmp/helprequests/'.$now;
                   2820:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2821:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2822:                          '_'.$env{'user.domain'}.'/pending';
                   2823:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2824:             my ($docuname,$docudom);
                   2825:             if ($destudom) {
                   2826:                 $docudom = $destudom;
                   2827:             } else {
                   2828:                 $docudom = $env{'user.domain'};
                   2829:             }
                   2830:             if ($destuname) {
                   2831:                 $docuname = $destuname;
                   2832:             } else {
                   2833:                 $docuname = $env{'user.name'};
                   2834:             }
                   2835:             if (exists($env{'form.group'})) {
                   2836:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2837:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2838:             }
                   2839:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2840:             if ($context eq 'canceloverwrite') {
                   2841:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2842:                 if (-e  $tempfile) {
                   2843:                     my @info = stat($tempfile);
                   2844:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2845:                         unlink($tempfile);
                   2846:                     }
                   2847:                 }
                   2848:                 return;
1.523     raeburn  2849:             }
                   2850:         }
1.1090    raeburn  2851:         # Create the directory if not present
1.741     raeburn  2852:         my @parts=split(/\//,$filepath);
                   2853:         my $fullpath = $perlvar{'lonDaemons'};
                   2854:         for (my $i=0;$i<@parts;$i++) {
                   2855:             $fullpath .= '/'.$parts[$i];
                   2856:             if ((-e $fullpath)!=1) {
                   2857:                 mkdir($fullpath,0777);
                   2858:             }
                   2859:         }
                   2860:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2861:         print $fh $env{'form.'.$formname};
                   2862:         close($fh);
1.1090    raeburn  2863:         if ($context eq 'existingfile') {
                   2864:             my @info = stat($fullpath.'/'.$fname);
                   2865:             return ($fullpath.'/'.$fname,$info[9]);
                   2866:         } else {
                   2867:             return $fullpath.'/'.$fname;
                   2868:         }
1.523     raeburn  2869:     }
1.995     raeburn  2870:     if ($subdir eq 'scantron') {
                   2871:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2872:     } else {
1.995     raeburn  2873:         $fname="$subdir/$fname";
                   2874:     }
1.1090    raeburn  2875:     if ($context eq 'coursedoc') {
1.638     albertel 2876: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2877: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2878:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2879:             return &finishuserfileupload($docuname,$docudom,
                   2880: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2881: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2882:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2883:         } else {
1.620     albertel 2884:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2885:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2886: 				       $fname,$formname,$parser,
1.1095    raeburn  2887: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2888:         }
1.719     banghart 2889:     } elsif (defined($destuname)) {
                   2890:         my $docuname=$destuname;
                   2891:         my $docudom=$destudom;
1.860     raeburn  2892: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2893: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2894:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2895:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2896:     } else {
1.638     albertel 2897:         my $docuname=$env{'user.name'};
                   2898:         my $docudom=$env{'user.domain'};
1.714     raeburn  2899:         if (exists($env{'form.group'})) {
                   2900:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2901:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2902:         }
1.860     raeburn  2903: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2904: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2905:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2906:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2907:     }
1.271     www      2908: }
                   2909: 
                   2910: sub finishuserfileupload {
1.860     raeburn  2911:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2912:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2913:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2914:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2915:   
1.860     raeburn  2916:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2917:     $file=$fname;
                   2918:     if ($fname=~m|/|) {
                   2919:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2920: 	$path.=$fnamepath.'/';
                   2921:     }
1.259     www      2922:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2923:     my $count;
                   2924:     for ($count=4;$count<=$#parts;$count++) {
                   2925:         $filepath.="/$parts[$count]";
                   2926:         if ((-e $filepath)!=1) {
                   2927: 	    mkdir($filepath,0777);
                   2928:         }
                   2929:     }
1.984     neumanie 2930: 
1.258     www      2931: # Save the file
                   2932:     {
1.701     albertel 2933: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2934: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2935: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2936: 	    return '/adm/notfound.html';
                   2937: 	}
1.1090    raeburn  2938:         if ($context eq 'overwrite') {
1.1117    foxr     2939:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2940:             my $target = $filepath.'/'.$file;
                   2941:             if (-e $source) {
                   2942:                 my @info = stat($source);
                   2943:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2944:                     unless (&File::Copy::move($source,$target)) {
                   2945:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2946:                         return "Moving from $source failed";
                   2947:                     }
                   2948:                 } else {
                   2949:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2950:                 }
                   2951:             } else {
                   2952:                 return "Temporary file: $source missing";
                   2953:             }
                   2954:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2955: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2956: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2957: 	    return '/adm/notfound.html';
                   2958: 	}
1.570     albertel 2959: 	close(FH);
1.1051    raeburn  2960:         if ($resizewidth && $resizeheight) {
                   2961:             my $mm = new File::MMagic;
                   2962:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2963:             if ($mime_type =~ m{^image/}) {
                   2964: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2965:             }  
1.977     amueller 2966: 	}
1.258     www      2967:     }
1.637     raeburn  2968:     if ($parser eq 'parse') {
1.1024    raeburn  2969:         my $mm = new File::MMagic;
1.1095    raeburn  2970:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2971:         if ($type eq 'text/html') {
1.1024    raeburn  2972:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2973:                                                        $allfiles,$codebase);
                   2974:             unless ($parse_result eq 'ok') {
                   2975:                 &logthis('Failed to parse '.$filepath.$file.
                   2976: 	   	         ' for embedded media: '.$parse_result); 
                   2977:             }
1.637     raeburn  2978:         }
1.1095    raeburn  2979:         if (ref($mimetype)) {
                   2980:             $$mimetype = $type;
                   2981:         }
1.637     raeburn  2982:     }
1.860     raeburn  2983:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2984:         my $input = $filepath.'/'.$file;
                   2985:         my $output = $filepath.'/'.'tn-'.$file;
                   2986:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2987:         system("convert -sample $thumbsize $input $output");
                   2988:         if (-e $filepath.'/'.'tn-'.$file) {
                   2989:             $fetchthumb  = 1; 
                   2990:         }
                   2991:     }
1.858     raeburn  2992:  
1.259     www      2993: # Notify homeserver to grep it
                   2994: #
1.984     neumanie 2995:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2996:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      2997:     if ($fetchresult eq 'ok') {
1.860     raeburn  2998:         if ($fetchthumb) {
                   2999:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3000:             if ($thumbresult ne 'ok') {
                   3001:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3002:                          $docuhome.': '.$thumbresult);
                   3003:             }
                   3004:         }
1.259     www      3005: #
1.258     www      3006: # Return the URL to it
1.494     albertel 3007:         return '/uploaded/'.$path.$file;
1.263     www      3008:     } else {
1.494     albertel 3009:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3010: 		 ': '.$fetchresult);
1.263     www      3011:         return '/adm/notfound.html';
1.858     raeburn  3012:     }
1.493     albertel 3013: }
                   3014: 
1.637     raeburn  3015: sub extract_embedded_items {
1.961     raeburn  3016:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3017:     my @state = ();
                   3018:     my %javafiles = (
                   3019:                       codebase => '',
                   3020:                       code => '',
                   3021:                       archive => ''
                   3022:                     );
                   3023:     my %mediafiles = (
                   3024:                       src => '',
                   3025:                       movie => '',
                   3026:                      );
1.648     raeburn  3027:     my $p;
                   3028:     if ($content) {
                   3029:         $p = HTML::LCParser->new($content);
                   3030:     } else {
1.961     raeburn  3031:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3032:     }
1.641     albertel 3033:     while (my $t=$p->get_token()) {
1.640     albertel 3034: 	if ($t->[0] eq 'S') {
                   3035: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3036: 	    push(@state, $tagname);
1.648     raeburn  3037:             if (lc($tagname) eq 'allow') {
                   3038:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3039:             }
1.640     albertel 3040: 	    if (lc($tagname) eq 'img') {
                   3041: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3042: 	    }
1.886     albertel 3043: 	    if (lc($tagname) eq 'a') {
                   3044: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3045: 	    }
1.645     raeburn  3046:             if (lc($tagname) eq 'script') {
                   3047:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3048:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3049:                 } else {
                   3050:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   3051:                 }
                   3052:             }
                   3053:             if (lc($tagname) eq 'link') {
                   3054:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3055:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3056:                 }
                   3057:             }
1.640     albertel 3058: 	    if (lc($tagname) eq 'object' ||
                   3059: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3060: 		foreach my $item (keys(%javafiles)) {
                   3061: 		    $javafiles{$item} = '';
                   3062: 		}
                   3063: 	    }
                   3064: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3065: 		my $name = lc($attr->{'name'});
                   3066: 		foreach my $item (keys(%javafiles)) {
                   3067: 		    if ($name eq $item) {
                   3068: 			$javafiles{$item} = $attr->{'value'};
                   3069: 			last;
                   3070: 		    }
                   3071: 		}
                   3072: 		foreach my $item (keys(%mediafiles)) {
                   3073: 		    if ($name eq $item) {
                   3074: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   3075: 			last;
                   3076: 		    }
                   3077: 		}
                   3078: 	    }
                   3079: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3080: 		foreach my $item (keys(%javafiles)) {
                   3081: 		    if ($attr->{$item}) {
                   3082: 			$javafiles{$item} = $attr->{$item};
                   3083: 			last;
                   3084: 		    }
                   3085: 		}
                   3086: 		foreach my $item (keys(%mediafiles)) {
                   3087: 		    if ($attr->{$item}) {
                   3088: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3089: 			last;
                   3090: 		    }
                   3091: 		}
                   3092: 	    }
                   3093: 	} elsif ($t->[0] eq 'E') {
                   3094: 	    my ($tagname) = ($t->[1]);
                   3095: 	    if ($javafiles{'codebase'} ne '') {
                   3096: 		$javafiles{'codebase'} .= '/';
                   3097: 	    }  
                   3098: 	    if (lc($tagname) eq 'applet' ||
                   3099: 		lc($tagname) eq 'object' ||
                   3100: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3101: 		) {
                   3102: 		foreach my $item (keys(%javafiles)) {
                   3103: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3104: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3105: 			&add_filetype($allfiles,$file,$item);
                   3106: 		    }
                   3107: 		}
                   3108: 	    } 
                   3109: 	    pop @state;
                   3110: 	}
                   3111:     }
1.637     raeburn  3112:     return 'ok';
                   3113: }
                   3114: 
1.639     albertel 3115: sub add_filetype {
                   3116:     my ($allfiles,$file,$type)=@_;
                   3117:     if (exists($allfiles->{$file})) {
                   3118: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3119: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3120: 	}
                   3121:     } else {
                   3122: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3123:     }
                   3124: }
                   3125: 
1.493     albertel 3126: sub removeuploadedurl {
1.984     neumanie 3127:     my ($url)=@_;	
                   3128:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3129:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3130: }
                   3131: 
                   3132: sub removeuserfile {
                   3133:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3134:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3135:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3136:     if ($result eq 'ok') {	
1.798     raeburn  3137:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3138:             my $metafile = $fname.'.meta';
                   3139:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3140: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3141:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3142:             my $sqlresult = 
1.823     albertel 3143:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3144:                                         'portfolio_metadata',$group,
                   3145:                                         'delete');
1.798     raeburn  3146:         }
                   3147:     }
                   3148:     return $result;
1.257     www      3149: }
1.15      www      3150: 
1.530     albertel 3151: sub mkdiruserfile {
                   3152:     my ($docuname,$docudom,$dir)=@_;
                   3153:     my $home=&homeserver($docuname,$docudom);
                   3154:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3155: }
                   3156: 
1.531     albertel 3157: sub renameuserfile {
                   3158:     my ($docuname,$docudom,$old,$new)=@_;
                   3159:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3160:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3161:                         &escape("$old").':'.&escape("$new"),$home);
                   3162:     if ($result eq 'ok') {
                   3163:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3164:             my $oldmeta = $old.'.meta';
                   3165:             my $newmeta = $new.'.meta';
                   3166:             my $metaresult = 
                   3167:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3168: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3169:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3170:             my $sqlresult = 
1.823     albertel 3171:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3172:                                         'portfolio_metadata',$group,
                   3173:                                         'delete');
1.798     raeburn  3174:         }
                   3175:     }
                   3176:     return $result;
1.531     albertel 3177: }
                   3178: 
1.14      www      3179: # ------------------------------------------------------------------------- Log
                   3180: 
                   3181: sub log {
                   3182:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3183:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3184: }
                   3185: 
                   3186: # ------------------------------------------------------------------ Course Log
1.352     www      3187: #
                   3188: # This routine flushes several buffers of non-mission-critical nature
                   3189: #
1.157     www      3190: 
                   3191: sub flushcourselogs {
1.352     www      3192:     &logthis('Flushing log buffers');
                   3193: #
                   3194: # course logs
                   3195: # This is a log of all transactions in a course, which can be used
                   3196: # for data mining purposes
                   3197: #
                   3198: # It also collects the courseid database, which lists last transaction
                   3199: # times and course titles for all courseids
                   3200: #
                   3201:     my %courseidbuffer=();
1.921     raeburn  3202:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3203:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3204: 		          &escape($courselogs{$crsid}),
                   3205: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3206: 	    delete $courselogs{$crsid};
                   3207:         } else {
                   3208:             &logthis('Failed to flush log buffer for '.$crsid);
                   3209:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3210:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3211:                         " exceeded maximum size, deleting.</font>");
                   3212:                delete $courselogs{$crsid};
                   3213:             }
1.352     www      3214:         }
1.920     raeburn  3215:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3216:             'description' => $coursedescrbuf{$crsid},
                   3217:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3218:             'type'        => $coursetypebuf{$crsid},
                   3219:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3220:         };
1.191     harris41 3221:     }
1.352     www      3222: #
                   3223: # Write course id database (reverse lookup) to homeserver of courses 
                   3224: # Is used in pickcourse
                   3225: #
1.840     albertel 3226:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3227:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3228:                                     $courseidbuffer{$crs_home},
                   3229:                                     $crs_home,'timeonly');
1.352     www      3230:     }
                   3231: #
                   3232: # File accesses
                   3233: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3234: #
1.449     matthew  3235:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3236:         if ($entry =~ /___count$/) {
                   3237:             my ($dom,$name);
1.807     albertel 3238:             ($dom,$name,undef)=
1.811     albertel 3239: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3240:             if (! defined($dom) || $dom eq '' || 
                   3241:                 ! defined($name) || $name eq '') {
1.620     albertel 3242:                 my $cid = $env{'request.course.id'};
                   3243:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3244:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3245:             }
1.450     matthew  3246:             my $value = $accesshash{$entry};
                   3247:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3248:             my %temphash=($url => $value);
1.449     matthew  3249:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3250:             if ($result eq 'ok') {
                   3251:                 delete $accesshash{$entry};
                   3252:             } elsif ($result eq 'unknown_cmd') {
                   3253:                 # Target server has old code running on it.
1.450     matthew  3254:                 my %temphash=($entry => $value);
1.449     matthew  3255:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3256:                     delete $accesshash{$entry};
                   3257:                 }
                   3258:             }
                   3259:         } else {
1.811     albertel 3260:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  3261:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3262:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3263:                 delete $accesshash{$entry};
                   3264:             }
1.185     www      3265:         }
1.191     harris41 3266:     }
1.352     www      3267: #
                   3268: # Roles
                   3269: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3270: #
1.800     albertel 3271:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3272:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3273: 	    split(/\:/,$entry);
                   3274:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3275:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3276:                 $rudom,$runame) eq 'ok') {
                   3277: 	    delete $userrolehash{$entry};
                   3278:         }
                   3279:     }
1.662     raeburn  3280: #
                   3281: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3282: #
                   3283:     my %domrolebuffer = ();
1.1000    raeburn  3284:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3285:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3286:         if ($domrolebuffer{$rudom}) {
                   3287:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3288:                       '='.&escape($domainrolehash{$entry});
                   3289:         } else {
                   3290:             $domrolebuffer{$rudom}.=&escape($entry).
                   3291:                       '='.&escape($domainrolehash{$entry});
                   3292:         }
                   3293:         delete $domainrolehash{$entry};
                   3294:     }
                   3295:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3296: 	my %servers = &get_servers($dom,'library');
                   3297: 	foreach my $tryserver (keys(%servers)) {
                   3298: 	    unless (&reply('domroleput:'.$dom.':'.
                   3299: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3300: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3301: 	    }
1.662     raeburn  3302:         }
                   3303:     }
1.186     www      3304:     $dumpcount++;
1.157     www      3305: }
                   3306: 
                   3307: sub courselog {
                   3308:     my $what=shift;
1.158     www      3309:     $what=time.':'.$what;
1.620     albertel 3310:     unless ($env{'request.course.id'}) { return ''; }
                   3311:     $coursedombuf{$env{'request.course.id'}}=
                   3312:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3313:     $coursenumbuf{$env{'request.course.id'}}=
                   3314:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3315:     $coursehombuf{$env{'request.course.id'}}=
                   3316:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3317:     $coursedescrbuf{$env{'request.course.id'}}=
                   3318:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3319:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3320:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3321:     $courseownerbuf{$env{'request.course.id'}}=
                   3322:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3323:     $coursetypebuf{$env{'request.course.id'}}=
                   3324:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3325:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3326: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3327:     } else {
1.620     albertel 3328: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3329:     }
1.620     albertel 3330:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3331: 	&flushcourselogs();
                   3332:     }
1.158     www      3333: }
                   3334: 
                   3335: sub courseacclog {
                   3336:     my $fnsymb=shift;
1.620     albertel 3337:     unless ($env{'request.course.id'}) { return ''; }
                   3338:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657     albertel 3339:     if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187     www      3340:         $what.=':POST';
1.583     matthew  3341:         # FIXME: Probably ought to escape things....
1.800     albertel 3342: 	foreach my $key (keys(%env)) {
                   3343:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3344:                 my $formitem = $1;
                   3345:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3346:                     $what.=':'.$formitem.'='.$env{$key};
                   3347:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3348:                     $what.=':'.$formitem.'='.$env{$key};
                   3349:                 }
1.158     www      3350:             }
1.191     harris41 3351:         }
1.583     matthew  3352:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3353:         # FIXME: We should not be depending on a form parameter that someone
                   3354:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3355:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3356:             $what.= ':POST';
                   3357:             # FIXME: Probably ought to escape things....
                   3358:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3359:                                  'crsdiscuss') {
1.620     albertel 3360:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3361:             }
                   3362:         }
1.158     www      3363:     }
                   3364:     &courselog($what);
1.149     www      3365: }
                   3366: 
1.185     www      3367: sub countacc {
                   3368:     my $url=&declutter(shift);
1.458     matthew  3369:     return if (! defined($url) || $url eq '');
1.620     albertel 3370:     unless ($env{'request.course.id'}) { return ''; }
                   3371:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3372:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3373:     $accesshash{$key}++;
1.185     www      3374: }
1.349     www      3375: 
1.361     www      3376: sub linklog {
                   3377:     my ($from,$to)=@_;
                   3378:     $from=&declutter($from);
                   3379:     $to=&declutter($to);
                   3380:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3381:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3382: }
                   3383:   
1.349     www      3384: sub userrolelog {
                   3385:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3386:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3387:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3388:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3389:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3390:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3391:        $userrolehash
                   3392:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3393:                     =$tend.':'.$tstart;
1.662     raeburn  3394:     }
1.898     albertel 3395:     if (($env{'request.role'} =~ /dc\./) &&
                   3396: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3397: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3398: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3399:          ($trole=~/^co/))) {
1.898     albertel 3400:        $userrolehash
                   3401:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3402:                     =$tend.':'.$tstart;
                   3403:     }
1.662     raeburn  3404:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3405:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3406:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3407:         ($trole=~/^sc/)) {
                   3408:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3409:        $domainrolehash
                   3410:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3411:                     = $tend.':'.$tstart;
                   3412:     }
1.351     www      3413: }
                   3414: 
1.957     raeburn  3415: sub courserolelog {
                   3416:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3417:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3418:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3419:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3420:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3421:         ($trole eq 'co')) {
1.957     raeburn  3422:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3423:             my $cdom = $1;
                   3424:             my $cnum = $2;
                   3425:             my $sec = $3;
                   3426:             my $namespace = 'rolelog';
                   3427:             my %storehash = (
                   3428:                                role    => $trole,
                   3429:                                start   => $tstart,
                   3430:                                end     => $tend,
                   3431:                                selfenroll => $selfenroll,
                   3432:                                context    => $context,
                   3433:                             );
                   3434:             if ($trole eq 'gr') {
                   3435:                 $namespace = 'groupslog';
                   3436:                 $storehash{'group'} = $sec;
                   3437:             } else {
                   3438:                 $storehash{'section'} = $sec;
                   3439:             }
                   3440:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3441:             if (($trole ne 'st') || ($sec ne '')) {
                   3442:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3443:             }
1.957     raeburn  3444:         }
                   3445:     }
                   3446:     return;
                   3447: }
                   3448: 
1.351     www      3449: sub get_course_adv_roles {
1.948     raeburn  3450:     my ($cid,$codes) = @_;
1.620     albertel 3451:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3452:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3453:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3454:     my %nothide=();
1.800     albertel 3455:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3456:         if ($user !~ /:/) {
                   3457: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3458:         } else {
                   3459:             $nothide{$user}=1;
                   3460:         }
1.470     www      3461:     }
1.351     www      3462:     my %returnhash=();
                   3463:     my %dumphash=
                   3464:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3465:     my $now=time;
1.997     raeburn  3466:     my %privileged;
1.1000    raeburn  3467:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3468: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3469:         if (($tstart) && ($tstart<0)) { next; }
                   3470:         if (($tend) && ($tend<$now)) { next; }
                   3471:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3472:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3473: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3474:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3475:             my %dompersonnel =
1.998     raeburn  3476:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3477:             $privileged{$domain} = {};
                   3478:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3479:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3480:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3481:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3482:                         $privileged{$udom}{$uname} = 1;
                   3483:                     }
                   3484:                 }
                   3485:             }
                   3486:         }
                   3487:         if ((exists($privileged{$domain}{$username})) && 
                   3488:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3489: 	if ($role eq 'cr') { next; }
1.948     raeburn  3490:         if ($codes) {
                   3491:             if ($section) { $role .= ':'.$section; }
                   3492:             if ($returnhash{$role}) {
                   3493:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3494:             } else {
                   3495:                 $returnhash{$role}=$username.':'.$domain;
                   3496:             }
1.351     www      3497:         } else {
1.988     raeburn  3498:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3499:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3500:             if ($returnhash{$key}) {
                   3501: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3502:             } else {
                   3503:                 $returnhash{$key}=$username.':'.$domain;
                   3504:             }
1.351     www      3505:         }
1.948     raeburn  3506:     }
1.400     www      3507:     return %returnhash;
                   3508: }
                   3509: 
                   3510: sub get_my_roles {
1.937     raeburn  3511:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3512:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3513:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3514:     my (%dumphash,%nothide);
1.1086    raeburn  3515:     if ($context eq 'userroles') {
                   3516:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3517:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3518:     } else {
                   3519:         %dumphash=
1.400     www      3520:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3521:         if ($hidepriv) {
                   3522:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3523:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3524:                 if ($user !~ /:/) {
                   3525:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3526:                 } else {
                   3527:                     $nothide{$user} = 1;
                   3528:                 }
                   3529:             }
                   3530:         }
1.858     raeburn  3531:     }
1.400     www      3532:     my %returnhash=();
                   3533:     my $now=time;
1.999     raeburn  3534:     my %privileged;
1.800     albertel 3535:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3536:         my ($role,$tend,$tstart);
                   3537:         if ($context eq 'userroles') {
                   3538: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3539:         } else {
                   3540:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3541:         }
1.400     www      3542:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3543:         my $status = 'active';
1.939     raeburn  3544:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3545:             $status = 'previous';
                   3546:         } 
                   3547:         if (($tstart) && ($now<$tstart)) {
                   3548:             $status = 'future';
                   3549:         }
                   3550:         if (ref($types) eq 'ARRAY') {
                   3551:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3552:                 next;
                   3553:             } 
                   3554:         } else {
                   3555:             if ($status ne 'active') {
                   3556:                 next;
                   3557:             }
                   3558:         }
1.867     raeburn  3559:         my ($rolecode,$username,$domain,$section,$area);
                   3560:         if ($context eq 'userroles') {
                   3561:             ($area,$rolecode) = split(/_/,$entry);
                   3562:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3563:         } else {
                   3564:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3565:         }
1.832     raeburn  3566:         if (ref($roledoms) eq 'ARRAY') {
                   3567:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3568:                 next;
                   3569:             }
                   3570:         }
                   3571:         if (ref($roles) eq 'ARRAY') {
                   3572:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3573:                 if ($role =~ /^cr\//) {
                   3574:                     if (!grep(/^cr$/,@{$roles})) {
                   3575:                         next;
                   3576:                     }
1.1104    raeburn  3577:                 } elsif ($role =~ /^gr\//) {
                   3578:                     if (!grep(/^gr$/,@{$roles})) {
                   3579:                         next;
                   3580:                     }
1.922     raeburn  3581:                 } else {
                   3582:                     next;
                   3583:                 }
1.832     raeburn  3584:             }
1.867     raeburn  3585:         }
1.937     raeburn  3586:         if ($hidepriv) {
1.999     raeburn  3587:             if ($context eq 'userroles') {
                   3588:                 if ((&privileged($username,$domain)) &&
                   3589:                     (!$nothide{$username.':'.$domain})) {
                   3590:                     next;
                   3591:                 }
                   3592:             } else {
                   3593:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3594:                     my %dompersonnel =
                   3595:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3596:                     $privileged{$domain} = {};
                   3597:                     if (keys(%dompersonnel)) {
                   3598:                         foreach my $server (keys(%dompersonnel)) {
                   3599:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3600:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3601:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3602:                                     $privileged{$udom}{$uname} = $trole;
                   3603:                                 }
                   3604:                             }
                   3605:                         }
                   3606:                     }
                   3607:                 }
                   3608:                 if (exists($privileged{$domain}{$username})) {
                   3609:                     if (!$nothide{$username.':'.$domain}) {
                   3610:                         next;
                   3611:                     }
                   3612:                 }
1.937     raeburn  3613:             }
                   3614:         }
1.933     raeburn  3615:         if ($withsec) {
                   3616:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3617:                 $tstart.':'.$tend;
                   3618:         } else {
                   3619:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3620:         }
1.832     raeburn  3621:     }
1.373     www      3622:     return %returnhash;
1.399     www      3623: }
                   3624: 
                   3625: # ----------------------------------------------------- Frontpage Announcements
                   3626: #
                   3627: #
                   3628: 
                   3629: sub postannounce {
                   3630:     my ($server,$text)=@_;
1.844     albertel 3631:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3632:     unless ($text=~/\w/) { $text=''; }
                   3633:     return &reply('setannounce:'.&escape($text),$server);
                   3634: }
                   3635: 
                   3636: sub getannounce {
1.448     albertel 3637: 
                   3638:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3639: 	my $announcement='';
1.800     albertel 3640: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3641: 	close($fh);
1.399     www      3642: 	if ($announcement=~/\w/) { 
                   3643: 	    return 
                   3644:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3645:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3646: 	} else {
                   3647: 	    return '';
                   3648: 	}
                   3649:     } else {
                   3650: 	return '';
                   3651:     }
1.351     www      3652: }
1.353     www      3653: 
                   3654: # ---------------------------------------------------------- Course ID routines
                   3655: # Deal with domain's nohist_courseid.db files
                   3656: #
                   3657: 
                   3658: sub courseidput {
1.921     raeburn  3659:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3660:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3661:     my $outcome;
                   3662:     if ($caller eq 'timeonly') {
                   3663:         my $cids = '';
                   3664:         foreach my $item (keys(%$storehash)) {
                   3665:             $cids.=&escape($item).'&';
                   3666:         }
                   3667:         $cids=~s/\&$//;
                   3668:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3669:                           $coursehome);       
                   3670:     } else {
                   3671:         my $items = '';
                   3672:         foreach my $item (keys(%$storehash)) {
                   3673:             $items.= &escape($item).'='.
                   3674:                      &freeze_escape($$storehash{$item}).'&';
                   3675:         }
                   3676:         $items=~s/\&$//;
                   3677:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3678:                           $coursehome);
1.918     raeburn  3679:     }
                   3680:     if ($outcome eq 'unknown_cmd') {
                   3681:         my $what;
                   3682:         foreach my $cid (keys(%$storehash)) {
                   3683:             $what .= &escape($cid).'=';
1.921     raeburn  3684:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3685:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3686:             }
                   3687:             $what =~ s/\:$/&/;
                   3688:         }
                   3689:         $what =~ s/\&$//;  
                   3690:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3691:     } else {
                   3692:         return $outcome;
                   3693:     }
1.353     www      3694: }
                   3695: 
                   3696: sub courseiddump {
1.921     raeburn  3697:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3698:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3699:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3700:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3701:     my $as_hash = 1;
                   3702:     my %returnhash;
                   3703:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3704:     my %libserv = &all_library();
                   3705:     foreach my $tryserver (keys(%libserv)) {
                   3706:         if ( (  $hostidflag == 1 
                   3707: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3708: 	     || (!defined($hostidflag)) ) {
                   3709: 
1.918     raeburn  3710: 	    if (($domfilter eq '') ||
                   3711: 		(&host_domain($tryserver) eq $domfilter)) {
                   3712:                 my $rep = 
                   3713:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3714:                          $sincefilter.':'.&escape($descfilter).':'.
                   3715:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3716:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3717:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3718:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3719:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3720:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3721:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3722:                          &escape($creationcontext).':'.$domcloner,
                   3723:                          $tryserver);
1.918     raeburn  3724:                 my @pairs=split(/\&/,$rep);
                   3725:                 foreach my $item (@pairs) {
                   3726:                     my ($key,$value)=split(/\=/,$item,2);
                   3727:                     $key = &unescape($key);
                   3728:                     next if ($key =~ /^error: 2 /);
                   3729:                     my $result = &thaw_unescape($value);
                   3730:                     if (ref($result) eq 'HASH') {
                   3731:                         $returnhash{$key}=$result;
                   3732:                     } else {
1.921     raeburn  3733:                         my @responses = split(/:/,$value);
                   3734:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3735:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3736:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3737:                         }
1.1008    raeburn  3738:                     }
1.353     www      3739:                 }
                   3740:             }
                   3741:         }
                   3742:     }
                   3743:     return %returnhash;
                   3744: }
                   3745: 
1.1055    raeburn  3746: sub courselastaccess {
                   3747:     my ($cdom,$cnum,$hostidref) = @_;
                   3748:     my %returnhash;
                   3749:     if ($cdom && $cnum) {
                   3750:         my $chome = &homeserver($cnum,$cdom);
                   3751:         if ($chome ne 'no_host') {
                   3752:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3753:             &extract_lastaccess(\%returnhash,$rep);
                   3754:         }
                   3755:     } else {
                   3756:         if (!$cdom) { $cdom=''; }
                   3757:         my %libserv = &all_library();
                   3758:         foreach my $tryserver (keys(%libserv)) {
                   3759:             if (ref($hostidref) eq 'ARRAY') {
                   3760:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3761:             } 
                   3762:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3763:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3764:                 &extract_lastaccess(\%returnhash,$rep);
                   3765:             }
                   3766:         }
                   3767:     }
                   3768:     return %returnhash;
                   3769: }
                   3770: 
                   3771: sub extract_lastaccess {
                   3772:     my ($returnhash,$rep) = @_;
                   3773:     if (ref($returnhash) eq 'HASH') {
                   3774:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3775:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3776:                  $rep eq '') {
                   3777:             my @pairs=split(/\&/,$rep);
                   3778:             foreach my $item (@pairs) {
                   3779:                 my ($key,$value)=split(/\=/,$item,2);
                   3780:                 $key = &unescape($key);
                   3781:                 next if ($key =~ /^error: 2 /);
                   3782:                 $returnhash->{$key} = &thaw_unescape($value);
                   3783:             }
                   3784:         }
                   3785:     }
                   3786:     return;
                   3787: }
                   3788: 
1.658     raeburn  3789: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3790: 
                   3791: sub dcmailput {
1.685     raeburn  3792:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3793:     my $status = &Apache::lonnet::critical(
1.740     www      3794:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3795:        &escape($message),$server);
1.662     raeburn  3796:     return $status;
                   3797: }
                   3798: 
1.658     raeburn  3799: sub dcmaildump {
                   3800:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3801:     my %returnhash=();
1.846     albertel 3802: 
                   3803:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3804:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3805:                                                          &escape($enddate).':';
                   3806: 	my @esc_senders=map { &escape($_)} @$senders;
                   3807: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3808: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3809:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3810:             if (($key) && ($value)) {
                   3811:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3812:             }
                   3813:         }
                   3814:     }
                   3815:     return %returnhash;
                   3816: }
1.662     raeburn  3817: # ---------------------------------------------------------- Domain roles
                   3818: 
                   3819: sub get_domain_roles {
                   3820:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3821:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3822:         $startdate = '.';
                   3823:     }
1.1018    raeburn  3824:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3825:         $enddate = '.';
                   3826:     }
1.922     raeburn  3827:     my $rolelist;
                   3828:     if (ref($roles) eq 'ARRAY') {
                   3829:         $rolelist = join(':',@{$roles});
                   3830:     }
1.662     raeburn  3831:     my %personnel = ();
1.841     albertel 3832: 
                   3833:     my %servers = &get_servers($dom,'library');
                   3834:     foreach my $tryserver (keys(%servers)) {
                   3835: 	%{$personnel{$tryserver}}=();
                   3836: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3837: 					    &escape($startdate).':'.
                   3838: 					    &escape($enddate).':'.
                   3839: 					    &escape($rolelist), $tryserver))) {
                   3840: 	    my ($key,$value) = split(/\=/,$line,2);
                   3841: 	    if (($key) && ($value)) {
                   3842: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3843: 	    }
                   3844: 	}
1.662     raeburn  3845:     }
                   3846:     return %personnel;
                   3847: }
1.658     raeburn  3848: 
1.1057    www      3849: # ----------------------------------------------------------- Interval timing 
1.149     www      3850: 
1.504     albertel 3851: sub get_first_access {
                   3852:     my ($type,$argsymb)=@_;
1.790     albertel 3853:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3854:     if ($argsymb) { $symb=$argsymb; }
                   3855:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3856:     if ($type eq 'course') {
                   3857: 	$res='course';
                   3858:     } elsif ($type eq 'map') {
1.588     albertel 3859: 	$res=&symbread($map);
                   3860:     } else {
                   3861: 	$res=$symb;
                   3862:     }
                   3863:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3864:     return $times{"$courseid\0$res"};
1.504     albertel 3865: }
                   3866: 
                   3867: sub set_first_access {
                   3868:     my ($type)=@_;
1.790     albertel 3869:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3870:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3871:     if ($type eq 'course') {
                   3872: 	$res='course';
                   3873:     } elsif ($type eq 'map') {
1.588     albertel 3874: 	$res=&symbread($map);
                   3875:     } else {
                   3876: 	$res=$symb;
                   3877:     }
                   3878:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3879:     if (!$firstaccess) {
1.588     albertel 3880: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3881:     }
                   3882:     return 'already_set';
1.504     albertel 3883: }
                   3884: 
1.110     www      3885: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3886: 
                   3887: sub expirespread {
                   3888:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3889:     my $cid=$env{'request.course.id'}; 
1.110     www      3890:     if ($cid) {
                   3891:        my $now=time;
                   3892:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3893:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3894:                             $env{'course.'.$cid.'.num'}.
1.110     www      3895: 	        	    ':nohist_expirationdates:'.
                   3896:                             &escape($key).'='.$now,
1.620     albertel 3897:                             $env{'course.'.$cid.'.home'})
1.110     www      3898:     }
                   3899:     return 'ok';
1.14      www      3900: }
                   3901: 
1.109     www      3902: # ----------------------------------------------------- Devalidate Spreadsheets
                   3903: 
                   3904: sub devalidate {
1.325     www      3905:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3906:     my $cid=$env{'request.course.id'}; 
1.109     www      3907:     if ($cid) {
1.391     matthew  3908:         # delete the stored spreadsheets for
                   3909:         # - the student level sheet of this user in course's homespace
                   3910:         # - the assessment level sheet for this resource 
                   3911:         #   for this user in user's homespace
1.553     albertel 3912: 	# - current conditional state info
1.325     www      3913: 	my $key=$uname.':'.$udom.':';
1.109     www      3914:         my $status=
1.299     matthew  3915: 	    &del('nohist_calculatedsheets',
1.391     matthew  3916: 		 [$key.'studentcalc:'],
1.620     albertel 3917: 		 $env{'course.'.$cid.'.domain'},
                   3918: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3919: 		.' '.
                   3920: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3921: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3922:         unless ($status eq 'ok ok') {
                   3923:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3924:                     $uname.' at '.$udom.' for '.
1.109     www      3925: 		    $symb.': '.$status);
1.133     albertel 3926:         }
1.553     albertel 3927: 	&delenv('user.state.'.$cid);
1.109     www      3928:     }
                   3929: }
                   3930: 
1.265     albertel 3931: sub get_scalar {
                   3932:     my ($string,$end) = @_;
                   3933:     my $value;
                   3934:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3935: 	$value = $1;
                   3936:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3937: 	$value = $1;
                   3938:     }
                   3939:     return &unescape($value);
                   3940: }
                   3941: 
                   3942: sub array2str {
                   3943:   my (@array) = @_;
                   3944:   my $result=&arrayref2str(\@array);
                   3945:   $result=~s/^__ARRAY_REF__//;
                   3946:   $result=~s/__END_ARRAY_REF__$//;
                   3947:   return $result;
                   3948: }
                   3949: 
1.204     albertel 3950: sub arrayref2str {
                   3951:   my ($arrayref) = @_;
1.265     albertel 3952:   my $result='__ARRAY_REF__';
1.204     albertel 3953:   foreach my $elem (@$arrayref) {
1.265     albertel 3954:     if(ref($elem) eq 'ARRAY') {
                   3955:       $result.=&arrayref2str($elem).'&';
                   3956:     } elsif(ref($elem) eq 'HASH') {
                   3957:       $result.=&hashref2str($elem).'&';
                   3958:     } elsif(ref($elem)) {
                   3959:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3960:     } else {
                   3961:       $result.=&escape($elem).'&';
                   3962:     }
                   3963:   }
                   3964:   $result=~s/\&$//;
1.265     albertel 3965:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3966:   return $result;
                   3967: }
                   3968: 
1.168     albertel 3969: sub hash2str {
1.204     albertel 3970:   my (%hash) = @_;
                   3971:   my $result=&hashref2str(\%hash);
1.265     albertel 3972:   $result=~s/^__HASH_REF__//;
                   3973:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3974:   return $result;
                   3975: }
                   3976: 
                   3977: sub hashref2str {
                   3978:   my ($hashref)=@_;
1.265     albertel 3979:   my $result='__HASH_REF__';
1.800     albertel 3980:   foreach my $key (sort(keys(%$hashref))) {
                   3981:     if (ref($key) eq 'ARRAY') {
                   3982:       $result.=&arrayref2str($key).'=';
                   3983:     } elsif (ref($key) eq 'HASH') {
                   3984:       $result.=&hashref2str($key).'=';
                   3985:     } elsif (ref($key)) {
1.265     albertel 3986:       $result.='=';
1.800     albertel 3987:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3988:     } else {
1.800     albertel 3989: 	if ($key) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3990:     }
                   3991: 
1.800     albertel 3992:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3993:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3994:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3995:       $result.=&hashref2str($hashref->{$key}).'&';
                   3996:     } elsif(ref($hashref->{$key})) {
1.265     albertel 3997:        $result.='&';
1.800     albertel 3998:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 3999:     } else {
1.800     albertel 4000:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4001:     }
                   4002:   }
1.168     albertel 4003:   $result=~s/\&$//;
1.265     albertel 4004:   $result .= '__END_HASH_REF__';
1.168     albertel 4005:   return $result;
                   4006: }
                   4007: 
                   4008: sub str2hash {
1.265     albertel 4009:     my ($string)=@_;
                   4010:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4011:     return %$hash;
                   4012: }
                   4013: 
                   4014: sub str2hashref {
1.168     albertel 4015:   my ($string) = @_;
1.265     albertel 4016: 
                   4017:   my %hash;
                   4018: 
                   4019:   if($string !~ /^__HASH_REF__/) {
                   4020:       if (! ($string eq '' || !defined($string))) {
                   4021: 	  $hash{'error'}='Not hash reference';
                   4022:       }
                   4023:       return (\%hash, $string);
                   4024:   }
                   4025: 
                   4026:   $string =~ s/^__HASH_REF__//;
                   4027: 
                   4028:   while($string !~ /^__END_HASH_REF__/) {
                   4029:       #key
                   4030:       my $key='';
                   4031:       if($string =~ /^__HASH_REF__/) {
                   4032:           ($key, $string)=&str2hashref($string);
                   4033:           if(defined($key->{'error'})) {
                   4034:               $hash{'error'}='Bad data';
                   4035:               return (\%hash, $string);
                   4036:           }
                   4037:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4038:           ($key, $string)=&str2arrayref($string);
                   4039:           if($key->[0] eq 'Array reference error') {
                   4040:               $hash{'error'}='Bad data';
                   4041:               return (\%hash, $string);
                   4042:           }
                   4043:       } else {
                   4044:           $string =~ s/^(.*?)=//;
1.267     albertel 4045: 	  $key=&unescape($1);
1.265     albertel 4046:       }
                   4047:       $string =~ s/^=//;
                   4048: 
                   4049:       #value
                   4050:       my $value='';
                   4051:       if($string =~ /^__HASH_REF__/) {
                   4052:           ($value, $string)=&str2hashref($string);
                   4053:           if(defined($value->{'error'})) {
                   4054:               $hash{'error'}='Bad data';
                   4055:               return (\%hash, $string);
                   4056:           }
                   4057:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4058:           ($value, $string)=&str2arrayref($string);
                   4059:           if($value->[0] eq 'Array reference error') {
                   4060:               $hash{'error'}='Bad data';
                   4061:               return (\%hash, $string);
                   4062:           }
                   4063:       } else {
                   4064: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4065:       }
                   4066:       $string =~ s/^&//;
                   4067: 
                   4068:       $hash{$key}=$value;
1.204     albertel 4069:   }
1.265     albertel 4070: 
                   4071:   $string =~ s/^__END_HASH_REF__//;
                   4072: 
                   4073:   return (\%hash, $string);
1.204     albertel 4074: }
                   4075: 
                   4076: sub str2array {
1.265     albertel 4077:     my ($string)=@_;
                   4078:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4079:     return @$array;
                   4080: }
                   4081: 
                   4082: sub str2arrayref {
1.204     albertel 4083:   my ($string) = @_;
1.265     albertel 4084:   my @array;
                   4085: 
                   4086:   if($string !~ /^__ARRAY_REF__/) {
                   4087:       if (! ($string eq '' || !defined($string))) {
                   4088: 	  $array[0]='Array reference error';
                   4089:       }
                   4090:       return (\@array, $string);
                   4091:   }
                   4092: 
                   4093:   $string =~ s/^__ARRAY_REF__//;
                   4094: 
                   4095:   while($string !~ /^__END_ARRAY_REF__/) {
                   4096:       my $value='';
                   4097:       if($string =~ /^__HASH_REF__/) {
                   4098:           ($value, $string)=&str2hashref($string);
                   4099:           if(defined($value->{'error'})) {
                   4100:               $array[0] ='Array reference error';
                   4101:               return (\@array, $string);
                   4102:           }
                   4103:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4104:           ($value, $string)=&str2arrayref($string);
                   4105:           if($value->[0] eq 'Array reference error') {
                   4106:               $array[0] ='Array reference error';
                   4107:               return (\@array, $string);
                   4108:           }
                   4109:       } else {
                   4110: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4111:       }
                   4112:       $string =~ s/^&//;
                   4113: 
                   4114:       push(@array, $value);
1.191     harris41 4115:   }
1.265     albertel 4116: 
                   4117:   $string =~ s/^__END_ARRAY_REF__//;
                   4118: 
                   4119:   return (\@array, $string);
1.168     albertel 4120: }
                   4121: 
1.167     albertel 4122: # -------------------------------------------------------------------Temp Store
                   4123: 
1.168     albertel 4124: sub tmpreset {
                   4125:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4126:   if (!$symb) {
                   4127:     $symb=&symbread();
1.620     albertel 4128:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4129:   }
                   4130:   $symb=escape($symb);
                   4131: 
1.620     albertel 4132:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4133:   $namespace=~s/\//\_/g;
                   4134:   $namespace=~s/\W//g;
                   4135: 
1.620     albertel 4136:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4137:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4138:   if ($domain eq 'public' && $stuname eq 'public') {
                   4139:       $stuname=$ENV{'REMOTE_ADDR'};
                   4140:   }
1.1117    foxr     4141:   my $path=LONCAPA::tempdir();
1.168     albertel 4142:   my %hash;
                   4143:   if (tie(%hash,'GDBM_File',
                   4144: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4145: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4146:     foreach my $key (keys(%hash)) {
1.180     albertel 4147:       if ($key=~ /:$symb/) {
1.168     albertel 4148: 	delete($hash{$key});
                   4149:       }
                   4150:     }
                   4151:   }
                   4152: }
                   4153: 
1.167     albertel 4154: sub tmpstore {
1.168     albertel 4155:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4156: 
                   4157:   if (!$symb) {
                   4158:     $symb=&symbread();
1.620     albertel 4159:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4160:   }
                   4161:   $symb=escape($symb);
                   4162: 
                   4163:   if (!$namespace) {
                   4164:     # I don't think we would ever want to store this for a course.
                   4165:     # it seems this will only be used if we don't have a course.
1.620     albertel 4166:     #$namespace=$env{'request.course.id'};
1.168     albertel 4167:     #if (!$namespace) {
1.620     albertel 4168:       $namespace=$env{'request.state'};
1.168     albertel 4169:     #}
                   4170:   }
                   4171:   $namespace=~s/\//\_/g;
                   4172:   $namespace=~s/\W//g;
1.620     albertel 4173:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4174:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4175:   if ($domain eq 'public' && $stuname eq 'public') {
                   4176:       $stuname=$ENV{'REMOTE_ADDR'};
                   4177:   }
1.168     albertel 4178:   my $now=time;
                   4179:   my %hash;
1.1117    foxr     4180:   my $path=LONCAPA::tempdir();
1.168     albertel 4181:   if (tie(%hash,'GDBM_File',
                   4182: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4183: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4184:     $hash{"version:$symb"}++;
                   4185:     my $version=$hash{"version:$symb"};
                   4186:     my $allkeys=''; 
                   4187:     foreach my $key (keys(%$storehash)) {
                   4188:       $allkeys.=$key.':';
1.591     albertel 4189:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4190:     }
                   4191:     $hash{"$version:$symb:timestamp"}=$now;
                   4192:     $allkeys.='timestamp';
                   4193:     $hash{"$version:keys:$symb"}=$allkeys;
                   4194:     if (untie(%hash)) {
                   4195:       return 'ok';
                   4196:     } else {
                   4197:       return "error:$!";
                   4198:     }
                   4199:   } else {
                   4200:     return "error:$!";
                   4201:   }
                   4202: }
1.167     albertel 4203: 
1.168     albertel 4204: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4205: 
1.168     albertel 4206: sub tmprestore {
                   4207:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4208: 
1.168     albertel 4209:   if (!$symb) {
                   4210:     $symb=&symbread();
1.620     albertel 4211:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4212:   }
                   4213:   $symb=escape($symb);
                   4214: 
1.620     albertel 4215:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4216: 
1.620     albertel 4217:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4218:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4219:   if ($domain eq 'public' && $stuname eq 'public') {
                   4220:       $stuname=$ENV{'REMOTE_ADDR'};
                   4221:   }
1.168     albertel 4222:   my %returnhash;
                   4223:   $namespace=~s/\//\_/g;
                   4224:   $namespace=~s/\W//g;
                   4225:   my %hash;
1.1117    foxr     4226:   my $path=LONCAPA::tempdir();
1.168     albertel 4227:   if (tie(%hash,'GDBM_File',
                   4228: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4229: 	  &GDBM_READER(),0640)) {
1.168     albertel 4230:     my $version=$hash{"version:$symb"};
                   4231:     $returnhash{'version'}=$version;
                   4232:     my $scope;
                   4233:     for ($scope=1;$scope<=$version;$scope++) {
                   4234:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4235:       my @keys=split(/:/,$vkeys);
                   4236:       my $key;
                   4237:       $returnhash{"$scope:keys"}=$vkeys;
                   4238:       foreach $key (@keys) {
1.591     albertel 4239: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4240: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4241:       }
                   4242:     }
1.168     albertel 4243:     if (!(untie(%hash))) {
                   4244:       return "error:$!";
                   4245:     }
                   4246:   } else {
                   4247:     return "error:$!";
                   4248:   }
                   4249:   return %returnhash;
1.167     albertel 4250: }
                   4251: 
1.9       www      4252: # ----------------------------------------------------------------------- Store
                   4253: 
                   4254: sub store {
1.124     www      4255:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4256:     my $home='';
                   4257: 
1.168     albertel 4258:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4259: 
1.213     www      4260:     $symb=&symbclean($symb);
1.122     albertel 4261:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4262: 
1.620     albertel 4263:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4264:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4265: 
                   4266:     &devalidate($symb,$stuname,$domain);
1.109     www      4267: 
                   4268:     $symb=escape($symb);
1.187     www      4269:     if (!$namespace) { 
1.620     albertel 4270:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4271:           return ''; 
                   4272:        } 
                   4273:     }
1.620     albertel 4274:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4275: 
                   4276:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4277:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4278: 
1.12      www      4279:     my $namevalue='';
1.800     albertel 4280:     foreach my $key (keys(%$storehash)) {
                   4281:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4282:     }
1.12      www      4283:     $namevalue=~s/\&$//;
1.187     www      4284:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4285:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4286: }
                   4287: 
1.47      www      4288: # -------------------------------------------------------------- Critical Store
                   4289: 
                   4290: sub cstore {
1.124     www      4291:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4292:     my $home='';
                   4293: 
1.168     albertel 4294:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4295: 
1.213     www      4296:     $symb=&symbclean($symb);
1.122     albertel 4297:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4298: 
1.620     albertel 4299:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4300:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4301: 
                   4302:     &devalidate($symb,$stuname,$domain);
1.109     www      4303: 
                   4304:     $symb=escape($symb);
1.187     www      4305:     if (!$namespace) { 
1.620     albertel 4306:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4307:           return ''; 
                   4308:        } 
                   4309:     }
1.620     albertel 4310:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4311: 
                   4312:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4313:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4314: 
1.47      www      4315:     my $namevalue='';
1.800     albertel 4316:     foreach my $key (keys(%$storehash)) {
                   4317:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4318:     }
1.47      www      4319:     $namevalue=~s/\&$//;
1.187     www      4320:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4321:     return critical
                   4322:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4323: }
                   4324: 
1.9       www      4325: # --------------------------------------------------------------------- Restore
                   4326: 
                   4327: sub restore {
1.124     www      4328:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4329:     my $home='';
                   4330: 
1.168     albertel 4331:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4332: 
1.122     albertel 4333:     if (!$symb) {
                   4334:       unless ($symb=escape(&symbread())) { return ''; }
                   4335:     } else {
1.213     www      4336:       $symb=&escape(&symbclean($symb));
1.122     albertel 4337:     }
1.188     www      4338:     if (!$namespace) { 
1.620     albertel 4339:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4340:           return ''; 
                   4341:        } 
                   4342:     }
1.620     albertel 4343:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4344:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4345:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4346:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4347: 
1.12      www      4348:     my %returnhash=();
1.800     albertel 4349:     foreach my $line (split(/\&/,$answer)) {
                   4350: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4351:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4352:     }
1.75      www      4353:     my $version;
                   4354:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4355:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4356:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4357:        }
1.75      www      4358:     }
1.13      www      4359:     return %returnhash;
1.34      www      4360: }
                   4361: 
                   4362: # ---------------------------------------------------------- Course Description
1.1118    foxr     4363: #
                   4364: #  
1.34      www      4365: 
                   4366: sub coursedescription {
1.731     albertel 4367:     my ($courseid,$args)=@_;
1.34      www      4368:     $courseid=~s/^\///;
1.49      www      4369:     $courseid=~s/\_/\//g;
1.34      www      4370:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4371:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4372:     my $normalid=$cdomain.'_'.$cnum;
                   4373:     # need to always cache even if we get errors otherwise we keep 
                   4374:     # trying and trying and trying to get the course description.
                   4375:     my %envhash=();
                   4376:     my %returnhash=();
1.731     albertel 4377:     
                   4378:     my $expiretime=600;
                   4379:     if ($env{'request.course.id'} eq $normalid) {
                   4380: 	$expiretime=120;
                   4381:     }
                   4382: 
                   4383:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4384:     if (!$args->{'freshen_cache'}
                   4385: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4386: 	foreach my $key (keys(%env)) {
                   4387: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4388: 	    my ($setting) = $1;
                   4389: 	    $returnhash{$setting} = $env{$key};
                   4390: 	}
                   4391: 	return %returnhash;
                   4392:     }
                   4393: 
1.1118    foxr     4394:     # get the data again
                   4395: 
1.731     albertel 4396:     if (!$args->{'one_time'}) {
                   4397: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4398:     }
1.811     albertel 4399: 
1.34      www      4400:     if ($chome ne 'no_host') {
1.302     albertel 4401:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4402:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4403: 	   my $username = $env{'user.name'}; # Defult username
                   4404: 	   if(defined $args->{'user'}) {
                   4405: 	       $username = $args->{'user'};
                   4406: 	   }
1.129     albertel 4407:            $returnhash{'home'}= $chome;
                   4408: 	   $returnhash{'domain'} = $cdomain;
                   4409: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4410:            if (!defined($returnhash{'type'})) {
                   4411:                $returnhash{'type'} = 'Course';
                   4412:            }
1.130     albertel 4413:            while (my ($name,$value) = each %returnhash) {
1.53      www      4414:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4415:            }
1.270     www      4416:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4417:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4418: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4419:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4420:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4421:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4422:        }
                   4423:     }
1.731     albertel 4424:     if (!$args->{'one_time'}) {
1.949     raeburn  4425: 	&appenv(\%envhash);
1.731     albertel 4426:     }
1.302     albertel 4427:     return %returnhash;
1.461     www      4428: }
                   4429: 
1.1080    raeburn  4430: sub update_released_required {
                   4431:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4432:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4433:         $cid = $env{'request.course.id'};
                   4434:         $cdom = $env{'course.'.$cid.'.domain'};
                   4435:         $cnum = $env{'course.'.$cid.'.num'};
                   4436:         $chome = $env{'course.'.$cid.'.home'};
                   4437:     }
                   4438:     if ($needsrelease) {
                   4439:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4440:         my $needsupdate;
                   4441:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4442:             $needsupdate = 1;
                   4443:         } else {
                   4444:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4445:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4446:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4447:                 $needsupdate = 1;
                   4448:             }
                   4449:         }
                   4450:         if ($needsupdate) {
                   4451:             my %needshash = (
                   4452:                              'internal.releaserequired' => $needsrelease,
                   4453:                             );
                   4454:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4455:             if ($putresult eq 'ok') {
                   4456:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4457:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4458:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4459:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4460:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4461:                 }
                   4462:             }
                   4463:         }
                   4464:     }
                   4465:     return;
                   4466: }
                   4467: 
1.461     www      4468: # -------------------------------------------------See if a user is privileged
                   4469: 
                   4470: sub privileged {
                   4471:     my ($username,$domain)=@_;
                   4472:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4473: 			&homeserver($username,$domain));
1.1033    raeburn  4474:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4475:         ($rolesdump =~ /^error:/)) {
                   4476:         return 0;
                   4477:     }
1.461     www      4478:     my $now=time;
                   4479:     if ($rolesdump ne '') {
1.800     albertel 4480:         foreach my $entry (split(/&/,$rolesdump)) {
                   4481: 	    if ($entry!~/^rolesdef_/) {
                   4482: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4483: 		$area=~s/\_\w\w$//;
                   4484: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4485: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4486: 		    my $active=1;
                   4487: 		    if ($tend) {
                   4488: 			if ($tend<$now) { $active=0; }
                   4489: 		    }
                   4490: 		    if ($tstart) {
                   4491: 			if ($tstart>$now) { $active=0; }
                   4492: 		    }
                   4493: 		    if ($active) { return 1; }
                   4494: 		}
                   4495: 	    }
                   4496: 	}
                   4497:     }
                   4498:     return 0;
1.9       www      4499: }
1.1       albertel 4500: 
1.103     harris41 4501: # -------------------------------------------------------- Get user privileges
1.11      www      4502: 
                   4503: sub rolesinit {
                   4504:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4505:     my $now=time;
                   4506:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4507:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4508:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4509:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4510:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4511:         return \%userroles;
                   4512:     }
1.11      www      4513:     my %allroles=();
1.678     raeburn  4514:     my %allgroups=();   
1.11      www      4515: 
                   4516:     if ($rolesdump ne '') {
1.800     albertel 4517:         foreach my $entry (split(/&/,$rolesdump)) {
                   4518: 	  if ($entry!~/^rolesdef_/) {
                   4519:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4520: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4521:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4522: 	    if ($role=~/^cr/) { 
1.807     albertel 4523: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4524: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4525: 		    ($tend,$tstart)=split('_',$trest);
                   4526: 		} else {
                   4527: 		    $trole=$role;
                   4528: 		}
1.678     raeburn  4529:             } elsif ($role =~ m|^gr/|) {
                   4530:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4531:                 next if ($tstart eq '-1');
1.678     raeburn  4532:                 ($trole,$group_privs) = split(/\//,$trole);
                   4533:                 $group_privs = &unescape($group_privs);
1.587     albertel 4534: 	    } else {
                   4535: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4536: 	    }
1.743     albertel 4537: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4538: 					 $username);
                   4539: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4540:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4541:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4542:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4543: 		my $spec=$trole.'.'.$area;
                   4544: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4545: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4546:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4547:                 } elsif ($trole eq 'gr') {
                   4548:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4549: 		} else {
1.567     raeburn  4550:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4551: 		}
1.12      www      4552:             }
1.662     raeburn  4553:           }
1.191     harris41 4554:         }
1.743     albertel 4555:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4556:         $userroles{'user.adv'}    = $adv;
                   4557: 	$userroles{'user.author'} = $author;
1.620     albertel 4558:         $env{'user.adv'}=$adv;
1.11      www      4559:     }
1.743     albertel 4560:     return \%userroles;  
1.11      www      4561: }
                   4562: 
1.567     raeburn  4563: sub set_arearole {
                   4564:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4565: # log the associated role with the area
                   4566:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4567:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4568: }
                   4569: 
                   4570: sub custom_roleprivs {
                   4571:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4572:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4573:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4574:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4575:         my ($rdummy,$roledef)=
                   4576:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4577:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4578:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4579:             if (defined($syspriv)) {
1.1043    raeburn  4580:                 if ($trest =~ /^$match_community$/) {
                   4581:                     $syspriv =~ s/bre\&S//; 
                   4582:                 }
1.567     raeburn  4583:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4584:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4585:             }
                   4586:             if ($tdomain ne '') {
                   4587:                 if (defined($dompriv)) {
                   4588:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4589:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4590:                 }
                   4591:                 if (($trest ne '') && (defined($coursepriv))) {
                   4592:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4593:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4594:                 }
                   4595:             }
                   4596:         }
                   4597:     }
                   4598: }
                   4599: 
1.678     raeburn  4600: sub group_roleprivs {
                   4601:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4602:     my $access = 1;
                   4603:     my $now = time;
                   4604:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4605:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4606:     if ($access) {
1.811     albertel 4607:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4608:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4609:     }
                   4610: }
1.567     raeburn  4611: 
                   4612: sub standard_roleprivs {
                   4613:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4614:     if (defined($pr{$trole.':s'})) {
                   4615:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4616:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4617:     }
                   4618:     if ($tdomain ne '') {
                   4619:         if (defined($pr{$trole.':d'})) {
                   4620:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4621:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4622:         }
                   4623:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4624:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4625:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4626:         }
                   4627:     }
                   4628: }
                   4629: 
                   4630: sub set_userprivs {
1.1064    raeburn  4631:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4632:     my $author=0;
                   4633:     my $adv=0;
1.678     raeburn  4634:     my %grouproles = ();
                   4635:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4636:         my @groupkeys; 
1.1000    raeburn  4637:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4638:             push(@groupkeys,$role);
                   4639:         }
                   4640:         if (ref($groups_roles) eq 'HASH') {
                   4641:             foreach my $key (keys(%{$groups_roles})) {
                   4642:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4643:                     push(@groupkeys,$key);
                   4644:                 }
                   4645:             }
                   4646:         }
                   4647:         if (@groupkeys > 0) {
                   4648:             foreach my $role (@groupkeys) {
                   4649:                 my ($trole,$area,$sec,$extendedarea);
                   4650:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4651:                     $trole = $1;
                   4652:                     $area = $2;
                   4653:                     $sec = $3;
                   4654:                     $extendedarea = $area.$sec;
                   4655:                     if (exists($$allgroups{$area})) {
                   4656:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4657:                             my $spec = $trole.'.'.$extendedarea;
                   4658:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4659:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4660:                         }
1.678     raeburn  4661:                     }
                   4662:                 }
                   4663:             }
                   4664:         }
                   4665:     }
1.800     albertel 4666:     foreach my $group (keys(%grouproles)) {
                   4667:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4668:     }
1.800     albertel 4669:     foreach my $role (keys(%{$allroles})) {
                   4670:         my %thesepriv;
1.941     raeburn  4671:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4672:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4673:             if ($item ne '') {
                   4674:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4675:                 if ($restrictions eq '') {
                   4676:                     $thesepriv{$privilege}='F';
                   4677:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4678:                     $thesepriv{$privilege}.=$restrictions;
                   4679:                 }
                   4680:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4681:             }
                   4682:         }
                   4683:         my $thesestr='';
1.1104    raeburn  4684:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4685: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4686: 	}
                   4687:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4688:     }
                   4689:     return ($author,$adv);
                   4690: }
                   4691: 
1.994     raeburn  4692: sub role_status {
1.1104    raeburn  4693:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4694:     my @pwhere = ();
                   4695:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4696:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4697:         unless (!defined($$role) || $$role eq '') {
                   4698:             $$where=join('.',@pwhere);
                   4699:             $$trolecode=$$role.'.'.$$where;
                   4700:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4701:             $$tstatus='is';
1.1104    raeburn  4702:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4703:                 $$tstatus='future';
1.1034    raeburn  4704:                 if ($$tstart<$now) {
                   4705:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4706:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4707:                             my (%allroles,%allgroups,$group_privs,
                   4708:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4709:                             my %userroles = (
                   4710:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4711:                             );
1.1064    raeburn  4712:                             @rolecodes = ('cm'); 
1.1002    raeburn  4713:                             my $spec=$$role.'.'.$$where;
                   4714:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4715:                             if ($$role =~ /^cr\//) {
                   4716:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4717:                                 push(@rolecodes,'cr');
1.1002    raeburn  4718:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4719:                                 push(@rolecodes,$$role);
1.1002    raeburn  4720:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4721:                                                     $env{'user.name'});
1.1064    raeburn  4722:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4723:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4724:                                 $group_privs = &unescape($group_privs);
                   4725:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4726:                                 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  4727:                                 &get_groups_roles($tdomain,$trest,
                   4728:                                                   \%course_roles,\@rolecodes,
                   4729:                                                   \%groups_roles);
1.1002    raeburn  4730:                             } else {
1.1064    raeburn  4731:                                 push(@rolecodes,$$role);
1.1002    raeburn  4732:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4733:                             }
1.1064    raeburn  4734:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4735:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4736:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4737:                         }
                   4738:                     }
1.1034    raeburn  4739:                     $$tstatus = 'is';
1.1002    raeburn  4740:                 }
1.994     raeburn  4741:             }
                   4742:             if ($$tend) {
1.1104    raeburn  4743:                 if ($$tend<$update) {
1.994     raeburn  4744:                     $$tstatus='expired';
                   4745:                 } elsif ($$tend<$now) {
                   4746:                     $$tstatus='will_not';
                   4747:                 }
                   4748:             }
                   4749:         }
                   4750:     }
                   4751: }
                   4752: 
1.1104    raeburn  4753: sub get_groups_roles {
                   4754:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4755:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4756:                   (ref($rolecodes) eq 'ARRAY') && 
                   4757:                   (ref($groups_roles) eq 'HASH')); 
                   4758:     if (keys(%{$cdom_courseroles}) > 0) {
                   4759:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4760:         if ($cdom ne '' && $cnum ne '') {
                   4761:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4762:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4763:                     my $crsrole = $1;
                   4764:                     my $crssec = $2;
                   4765:                     if ($crsrole =~ /^cr/) {
                   4766:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4767:                             push(@{$rolecodes},'cr');
                   4768:                         }
                   4769:                     } else {
                   4770:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4771:                             push(@{$rolecodes},$crsrole);
                   4772:                         }
                   4773:                     }
                   4774:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4775:                     if ($crssec ne '') {
                   4776:                         $rolekey .= "/$crssec";
                   4777:                     }
                   4778:                     $rolekey .= './';
                   4779:                     $groups_roles->{$rolekey} = $rolecodes;
                   4780:                 }
                   4781:             }
                   4782:         }
                   4783:     }
                   4784:     return;
                   4785: }
                   4786: 
                   4787: sub delete_env_groupprivs {
                   4788:     my ($where,$courseroles,$possroles) = @_;
                   4789:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4790:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4791:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4792:         %{$courseroles->{$udom}} =
                   4793:             &get_my_roles('','','userroles',['active'],
                   4794:                           $possroles,[$udom],1);
                   4795:     }
                   4796:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4797:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4798:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4799:             my $area = '/'.$cdom.'/'.$cnum;
                   4800:             my $privkey = "user.priv.$crsrole.$area";
                   4801:             if ($crssec ne '') {
                   4802:                 $privkey .= '/'.$crssec;
                   4803:             }
                   4804:             $privkey .= ".$area/$group";
                   4805:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4806:         }
                   4807:     }
                   4808:     return;
                   4809: }
                   4810: 
1.994     raeburn  4811: sub check_adhoc_privs {
1.1104    raeburn  4812:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4813:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4814:     if ($env{$cckey}) {
                   4815:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4816:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4817:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4818:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4819:         }
                   4820:     } else {
1.1088    raeburn  4821:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4822:     }
                   4823: }
                   4824: 
                   4825: sub set_adhoc_privileges {
                   4826: # role can be cc or ca
1.1088    raeburn  4827:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4828:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4829:     my $spec = $role.'.'.$area;
                   4830:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4831:                                   $env{'user.name'});
                   4832:     my %ccrole = ();
                   4833:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4834:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4835:     &appenv(\%userroles,[$role,'cm']);
                   4836:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4837:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4838:         &appenv( {'request.role'        => $spec,
                   4839:                   'request.role.domain' => $dcdom,
                   4840:                   'request.course.sec'  => ''
                   4841:                  }
                   4842:                );
                   4843:         my $tadv=0;
                   4844:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4845:         &appenv({'request.role.adv'    => $tadv});
                   4846:     }
1.994     raeburn  4847: }
                   4848: 
1.12      www      4849: # --------------------------------------------------------------- get interface
                   4850: 
                   4851: sub get {
1.131     albertel 4852:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4853:    my $items='';
1.800     albertel 4854:    foreach my $item (@$storearr) {
                   4855:        $items.=&escape($item).'&';
1.191     harris41 4856:    }
1.12      www      4857:    $items=~s/\&$//;
1.620     albertel 4858:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4859:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4860:    my $uhome=&homeserver($uname,$udomain);
                   4861: 
1.133     albertel 4862:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4863:    my @pairs=split(/\&/,$rep);
1.273     albertel 4864:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4865:      return @pairs;
                   4866:    }
1.15      www      4867:    my %returnhash=();
1.42      www      4868:    my $i=0;
1.800     albertel 4869:    foreach my $item (@$storearr) {
                   4870:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4871:       $i++;
1.191     harris41 4872:    }
1.15      www      4873:    return %returnhash;
1.27      www      4874: }
                   4875: 
                   4876: # --------------------------------------------------------------- del interface
                   4877: 
                   4878: sub del {
1.133     albertel 4879:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4880:    my $items='';
1.800     albertel 4881:    foreach my $item (@$storearr) {
                   4882:        $items.=&escape($item).'&';
1.191     harris41 4883:    }
1.984     neumanie 4884: 
1.27      www      4885:    $items=~s/\&$//;
1.620     albertel 4886:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4887:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4888:    my $uhome=&homeserver($uname,$udomain);
                   4889:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4890: }
                   4891: 
                   4892: # -------------------------------------------------------------- dump interface
                   4893: 
                   4894: sub dump {
1.1086    raeburn  4895:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4896:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4897:     if (!$uname) { $uname=$env{'user.name'}; }
                   4898:     my $uhome=&homeserver($uname,$udomain);
                   4899:     if ($regexp) {
                   4900: 	$regexp=&escape($regexp);
                   4901:     } else {
                   4902: 	$regexp='.';
                   4903:     }
1.1086    raeburn  4904:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4905:     my @pairs=split(/\&/,$rep);
                   4906:     my %returnhash=();
1.1098    foxr     4907:     if (!($rep =~ /^error/ )) {
                   4908: 	foreach my $item (@pairs) {
                   4909: 	    my ($key,$value)=split(/=/,$item,2);
                   4910: 	    $key = &unescape($key);
                   4911: 	    next if ($key =~ /^error: 2 /);
                   4912: 	    $returnhash{$key}=&thaw_unescape($value);
                   4913: 	}
1.755     albertel 4914:     }
                   4915:     return %returnhash;
1.407     www      4916: }
                   4917: 
1.1098    foxr     4918: 
1.717     albertel 4919: # --------------------------------------------------------- dumpstore interface
                   4920: 
                   4921: sub dumpstore {
                   4922:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4923:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4924:    if (!$uname) { $uname=$env{'user.name'}; }
                   4925:    my $uhome=&homeserver($uname,$udomain);
                   4926:    if ($regexp) {
                   4927:        $regexp=&escape($regexp);
                   4928:    } else {
                   4929:        $regexp='.';
                   4930:    }
                   4931:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4932:    my @pairs=split(/\&/,$rep);
                   4933:    my %returnhash=();
                   4934:    foreach my $item (@pairs) {
                   4935:        my ($key,$value)=split(/=/,$item,2);
                   4936:        next if ($key =~ /^error: 2 /);
                   4937:        $returnhash{$key}=&thaw_unescape($value);
                   4938:    }
                   4939:    return %returnhash;
1.717     albertel 4940: }
                   4941: 
1.407     www      4942: # -------------------------------------------------------------- keys interface
                   4943: 
                   4944: sub getkeys {
                   4945:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4946:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4947:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4948:    my $uhome=&homeserver($uname,$udomain);
                   4949:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4950:    my @keyarray=();
1.800     albertel 4951:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4952:       next if ($key =~ /^error: 2 /);
1.800     albertel 4953:       push(@keyarray,&unescape($key));
1.407     www      4954:    }
                   4955:    return @keyarray;
1.318     matthew  4956: }
                   4957: 
1.319     matthew  4958: # --------------------------------------------------------------- currentdump
                   4959: sub currentdump {
1.328     matthew  4960:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4961:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4962:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4963:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4964:    my $uhome = &homeserver($sname,$sdom);
                   4965:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4966:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4967:    #
1.318     matthew  4968:    my %returnhash=();
1.319     matthew  4969:    #
                   4970:    if ($rep eq "unknown_cmd") { 
                   4971:        # an old lond will not know currentdump
                   4972:        # Do a dump and make it look like a currentdump
1.822     albertel 4973:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4974:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4975:        my %hash = @tmp;
                   4976:        @tmp=();
1.424     matthew  4977:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4978:    } else {
                   4979:        my @pairs=split(/\&/,$rep);
1.800     albertel 4980:        foreach my $pair (@pairs) {
                   4981:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4982:            my ($symb,$param) = split(/:/,$key);
                   4983:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4984:                                                         &thaw_unescape($value);
1.319     matthew  4985:        }
1.191     harris41 4986:    }
1.12      www      4987:    return %returnhash;
1.424     matthew  4988: }
                   4989: 
                   4990: sub convert_dump_to_currentdump{
                   4991:     my %hash = %{shift()};
                   4992:     my %returnhash;
                   4993:     # Code ripped from lond, essentially.  The only difference
                   4994:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4995:     # we might run in to problems with parameter names =~ /^v\./
                   4996:     while (my ($key,$value) = each(%hash)) {
                   4997:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 4998: 	$symb  = &unescape($symb);
                   4999: 	$param = &unescape($param);
1.424     matthew  5000:         next if ($v eq 'version' || $symb eq 'keys');
                   5001:         next if (exists($returnhash{$symb}) &&
                   5002:                  exists($returnhash{$symb}->{$param}) &&
                   5003:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5004:         $returnhash{$symb}->{$param}=$value;
                   5005:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5006:     }
                   5007:     #
                   5008:     # Remove all of the keys in the hashes which keep track of
                   5009:     # the version of the parameter.
                   5010:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5011:         # use a foreach because we are going to delete from the hash.
                   5012:         foreach my $key (keys(%$param_hash)) {
                   5013:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5014:         }
                   5015:     }
                   5016:     return \%returnhash;
1.12      www      5017: }
                   5018: 
1.627     albertel 5019: # ------------------------------------------------------ critical inc interface
                   5020: 
                   5021: sub cinc {
                   5022:     return &inc(@_,'critical');
                   5023: }
                   5024: 
1.449     matthew  5025: # --------------------------------------------------------------- inc interface
                   5026: 
                   5027: sub inc {
1.627     albertel 5028:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5029:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5030:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5031:     my $uhome=&homeserver($uname,$udomain);
                   5032:     my $items='';
                   5033:     if (! ref($store)) {
                   5034:         # got a single value, so use that instead
                   5035:         $items = &escape($store).'=&';
                   5036:     } elsif (ref($store) eq 'SCALAR') {
                   5037:         $items = &escape($$store).'=&';        
                   5038:     } elsif (ref($store) eq 'ARRAY') {
                   5039:         $items = join('=&',map {&escape($_);} @{$store});
                   5040:     } elsif (ref($store) eq 'HASH') {
                   5041:         while (my($key,$value) = each(%{$store})) {
                   5042:             $items.= &escape($key).'='.&escape($value).'&';
                   5043:         }
                   5044:     }
                   5045:     $items=~s/\&$//;
1.627     albertel 5046:     if ($critical) {
                   5047: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5048:     } else {
                   5049: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5050:     }
1.449     matthew  5051: }
                   5052: 
1.12      www      5053: # --------------------------------------------------------------- put interface
                   5054: 
                   5055: sub put {
1.134     albertel 5056:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5057:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5058:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5059:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5060:    my $items='';
1.800     albertel 5061:    foreach my $item (keys(%$storehash)) {
                   5062:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5063:    }
1.12      www      5064:    $items=~s/\&$//;
1.134     albertel 5065:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5066: }
                   5067: 
1.631     albertel 5068: # ------------------------------------------------------------ newput interface
                   5069: 
                   5070: sub newput {
                   5071:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5072:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5073:    if (!$uname) { $uname=$env{'user.name'}; }
                   5074:    my $uhome=&homeserver($uname,$udomain);
                   5075:    my $items='';
                   5076:    foreach my $key (keys(%$storehash)) {
                   5077:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5078:    }
                   5079:    $items=~s/\&$//;
                   5080:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5081: }
                   5082: 
                   5083: # ---------------------------------------------------------  putstore interface
                   5084: 
1.524     raeburn  5085: sub putstore {
1.715     albertel 5086:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5087:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5088:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5089:    my $uhome=&homeserver($uname,$udomain);
                   5090:    my $items='';
1.715     albertel 5091:    foreach my $key (keys(%$storehash)) {
                   5092:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5093:    }
1.715     albertel 5094:    $items=~s/\&$//;
1.716     albertel 5095:    my $esc_symb=&escape($symb);
                   5096:    my $esc_v=&escape($version);
1.715     albertel 5097:    my $reply =
1.716     albertel 5098:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5099: 	      $uhome);
                   5100:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5101:        # gfall back to way things use to be done
1.715     albertel 5102:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5103: 			    $uname);
1.524     raeburn  5104:    }
1.715     albertel 5105:    return $reply;
                   5106: }
                   5107: 
                   5108: sub old_putstore {
1.716     albertel 5109:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5110:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5111:     if (!$uname) { $uname=$env{'user.name'}; }
                   5112:     my $uhome=&homeserver($uname,$udomain);
                   5113:     my %newstorehash;
1.800     albertel 5114:     foreach my $item (keys(%$storehash)) {
                   5115: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5116: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5117:     }
                   5118:     my $items='';
                   5119:     my %allitems = ();
1.800     albertel 5120:     foreach my $item (keys(%newstorehash)) {
                   5121: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5122: 	    my $key = $1.':keys:'.$2;
                   5123: 	    $allitems{$key} .= $3.':';
                   5124: 	}
1.800     albertel 5125: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5126:     }
1.800     albertel 5127:     foreach my $item (keys(%allitems)) {
                   5128: 	$allitems{$item} =~ s/\:$//;
                   5129: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5130:     }
                   5131:     $items=~s/\&$//;
                   5132:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5133: }
                   5134: 
1.47      www      5135: # ------------------------------------------------------ critical put interface
                   5136: 
                   5137: sub cput {
1.134     albertel 5138:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5139:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5140:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5141:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5142:    my $items='';
1.800     albertel 5143:    foreach my $item (keys(%$storehash)) {
                   5144:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5145:    }
1.47      www      5146:    $items=~s/\&$//;
1.134     albertel 5147:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5148: }
                   5149: 
                   5150: # -------------------------------------------------------------- eget interface
                   5151: 
                   5152: sub eget {
1.133     albertel 5153:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5154:    my $items='';
1.800     albertel 5155:    foreach my $item (@$storearr) {
                   5156:        $items.=&escape($item).'&';
1.191     harris41 5157:    }
1.12      www      5158:    $items=~s/\&$//;
1.620     albertel 5159:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5160:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5161:    my $uhome=&homeserver($uname,$udomain);
                   5162:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5163:    my @pairs=split(/\&/,$rep);
                   5164:    my %returnhash=();
1.42      www      5165:    my $i=0;
1.800     albertel 5166:    foreach my $item (@$storearr) {
                   5167:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5168:       $i++;
1.191     harris41 5169:    }
1.12      www      5170:    return %returnhash;
                   5171: }
                   5172: 
1.667     albertel 5173: # ------------------------------------------------------------ tmpput interface
                   5174: sub tmpput {
1.802     raeburn  5175:     my ($storehash,$server,$context)=@_;
1.667     albertel 5176:     my $items='';
1.800     albertel 5177:     foreach my $item (keys(%$storehash)) {
                   5178: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5179:     }
                   5180:     $items=~s/\&$//;
1.802     raeburn  5181:     if (defined($context)) {
                   5182:         $items .= ':'.&escape($context);
                   5183:     }
1.667     albertel 5184:     return &reply("tmpput:$items",$server);
                   5185: }
                   5186: 
                   5187: # ------------------------------------------------------------ tmpget interface
                   5188: sub tmpget {
1.688     albertel 5189:     my ($token,$server)=@_;
                   5190:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5191:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5192:     my %returnhash;
                   5193:     foreach my $item (split(/\&/,$rep)) {
                   5194: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5195:         next if ($key =~ /^error: 2 /);
1.667     albertel 5196: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5197:     }
                   5198:     return %returnhash;
                   5199: }
                   5200: 
1.1113    raeburn  5201: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5202: sub tmpdel {
                   5203:     my ($token,$server)=@_;
                   5204:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5205:     return &reply("tmpdel:$token",$server);
                   5206: }
                   5207: 
1.765     albertel 5208: # -------------------------------------------------- portfolio access checking
                   5209: 
                   5210: sub portfolio_access {
1.766     albertel 5211:     my ($requrl) = @_;
1.765     albertel 5212:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5213:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5214:     if ($result) {
                   5215:         my %setters;
                   5216:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5217:             my ($startblock,$endblock) =
                   5218:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5219:             if ($startblock && $endblock) {
                   5220:                 return 'B';
                   5221:             }
                   5222:         } else {
                   5223:             my ($startblock,$endblock) =
                   5224:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5225:             if ($startblock && $endblock) {
                   5226:                 return 'B';
                   5227:             }
                   5228:         }
                   5229:     }
1.765     albertel 5230:     if ($result eq 'ok') {
1.766     albertel 5231:        return 'F';
1.765     albertel 5232:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5233:        return 'A';
1.765     albertel 5234:     }
1.766     albertel 5235:     return '';
1.765     albertel 5236: }
                   5237: 
                   5238: sub get_portfolio_access {
1.767     albertel 5239:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5240: 
                   5241:     if (!ref($access_hash)) {
                   5242: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5243: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5244: 						   $file_name);
                   5245: 	$access_hash = $access_controls{$file_name};
                   5246:     }
                   5247: 
1.765     albertel 5248:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5249:     my $now = time;
                   5250:     if (ref($access_hash) eq 'HASH') {
                   5251:         foreach my $key (keys(%{$access_hash})) {
                   5252:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5253:             if ($start > $now) {
                   5254:                 next;
                   5255:             }
                   5256:             if ($end && $end<$now) {
                   5257:                 next;
                   5258:             }
                   5259:             if ($scope eq 'public') {
                   5260:                 $public = $key;
                   5261:                 last;
                   5262:             } elsif ($scope eq 'guest') {
                   5263:                 $guest = $key;
                   5264:             } elsif ($scope eq 'domains') {
                   5265:                 push(@domains,$key);
                   5266:             } elsif ($scope eq 'users') {
                   5267:                 push(@users,$key);
                   5268:             } elsif ($scope eq 'course') {
                   5269:                 push(@courses,$key);
                   5270:             } elsif ($scope eq 'group') {
                   5271:                 push(@groups,$key);
                   5272:             }
                   5273:         }
                   5274:         if ($public) {
                   5275:             return 'ok';
                   5276:         }
                   5277:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5278:             if ($guest) {
                   5279:                 return $guest;
                   5280:             }
                   5281:         } else {
                   5282:             if (@domains > 0) {
                   5283:                 foreach my $domkey (@domains) {
                   5284:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5285:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5286:                             return 'ok';
                   5287:                         }
                   5288:                     }
                   5289:                 }
                   5290:             }
                   5291:             if (@users > 0) {
                   5292:                 foreach my $userkey (@users) {
1.865     raeburn  5293:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5294:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5295:                             if (ref($item) eq 'HASH') {
                   5296:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5297:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5298:                                     return 'ok';
                   5299:                                 }
                   5300:                             }
                   5301:                         }
                   5302:                     } 
1.765     albertel 5303:                 }
                   5304:             }
                   5305:             my %roleshash;
                   5306:             my @courses_and_groups = @courses;
                   5307:             push(@courses_and_groups,@groups); 
                   5308:             if (@courses_and_groups > 0) {
                   5309:                 my (%allgroups,%allroles); 
                   5310:                 my ($start,$end,$role,$sec,$group);
                   5311:                 foreach my $envkey (%env) {
1.1060    raeburn  5312:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5313:                         my $cid = $2.'_'.$3; 
                   5314:                         if ($1 eq 'gr') {
                   5315:                             $group = $4;
                   5316:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5317:                         } else {
                   5318:                             if ($4 eq '') {
                   5319:                                 $sec = 'none';
                   5320:                             } else {
                   5321:                                 $sec = $4;
                   5322:                             }
                   5323:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5324:                         }
1.811     albertel 5325:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5326:                         my $cid = $2.'_'.$3;
                   5327:                         if ($4 eq '') {
                   5328:                             $sec = 'none';
                   5329:                         } else {
                   5330:                             $sec = $4;
                   5331:                         }
                   5332:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5333:                     }
                   5334:                 }
                   5335:                 if (keys(%allroles) == 0) {
                   5336:                     return;
                   5337:                 }
                   5338:                 foreach my $key (@courses_and_groups) {
                   5339:                     my %content = %{$$access_hash{$key}};
                   5340:                     my $cnum = $content{'number'};
                   5341:                     my $cdom = $content{'domain'};
                   5342:                     my $cid = $cdom.'_'.$cnum;
                   5343:                     if (!exists($allroles{$cid})) {
                   5344:                         next;
                   5345:                     }    
                   5346:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5347:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5348:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5349:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5350:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5351:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5352:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5353:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5354:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5355:                                         if (grep/^all$/,@sections) {
                   5356:                                             return 'ok';
                   5357:                                         } else {
                   5358:                                             if (grep/^$sec$/,@sections) {
                   5359:                                                 return 'ok';
                   5360:                                             }
                   5361:                                         }
                   5362:                                     }
                   5363:                                 }
                   5364:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5365:                                     if (grep/^none$/,@groups) {
                   5366:                                         return 'ok';
                   5367:                                     }
                   5368:                                 } else {
                   5369:                                     if (grep/^all$/,@groups) {
                   5370:                                         return 'ok';
                   5371:                                     } 
                   5372:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5373:                                         if (grep/^$group$/,@groups) {
                   5374:                                             return 'ok';
                   5375:                                         }
                   5376:                                     }
                   5377:                                 } 
                   5378:                             }
                   5379:                         }
                   5380:                     }
                   5381:                 }
                   5382:             }
                   5383:             if ($guest) {
                   5384:                 return $guest;
                   5385:             }
                   5386:         }
                   5387:     }
                   5388:     return;
                   5389: }
                   5390: 
                   5391: sub course_group_datechecker {
                   5392:     my ($dates,$now,$status) = @_;
                   5393:     my ($start,$end) = split(/\./,$dates);
                   5394:     if (!$start && !$end) {
                   5395:         return 'ok';
                   5396:     }
                   5397:     if (grep/^active$/,@{$status}) {
                   5398:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5399:             return 'ok';
                   5400:         }
                   5401:     }
                   5402:     if (grep/^previous$/,@{$status}) {
                   5403:         if ($end > $now ) {
                   5404:             return 'ok';
                   5405:         }
                   5406:     }
                   5407:     if (grep/^future$/,@{$status}) {
                   5408:         if ($start > $now) {
                   5409:             return 'ok';
                   5410:         }
                   5411:     }
                   5412:     return; 
                   5413: }
                   5414: 
                   5415: sub parse_portfolio_url {
                   5416:     my ($url) = @_;
                   5417: 
                   5418:     my ($type,$udom,$unum,$group,$file_name);
                   5419:     
1.823     albertel 5420:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5421: 	$type = 1;
                   5422:         $udom = $1;
                   5423:         $unum = $2;
                   5424:         $file_name = $3;
1.823     albertel 5425:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5426: 	$type = 2;
                   5427:         $udom = $1;
                   5428:         $unum = $2;
                   5429:         $group = $3;
                   5430:         $file_name = $3.'/'.$4;
                   5431:     }
                   5432:     if (wantarray) {
                   5433: 	return ($type,$udom,$unum,$file_name,$group);
                   5434:     }
                   5435:     return $type;
                   5436: }
                   5437: 
                   5438: sub is_portfolio_url {
                   5439:     my ($url) = @_;
                   5440:     return scalar(&parse_portfolio_url($url));
                   5441: }
                   5442: 
1.798     raeburn  5443: sub is_portfolio_file {
                   5444:     my ($file) = @_;
1.820     raeburn  5445:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5446:         return 1;
                   5447:     }
                   5448:     return;
                   5449: }
                   5450: 
1.976     raeburn  5451: sub usertools_access {
1.1084    raeburn  5452:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5453:     my ($access,%tools);
                   5454:     if ($context eq '') {
                   5455:         $context = 'tools';
                   5456:     }
                   5457:     if ($context eq 'requestcourses') {
                   5458:         %tools = (
                   5459:                       official   => 1,
                   5460:                       unofficial => 1,
1.1006    raeburn  5461:                       community  => 1,
1.985     raeburn  5462:                  );
                   5463:     } else {
                   5464:         %tools = (
                   5465:                       aboutme   => 1,
                   5466:                       blog      => 1,
                   5467:                       portfolio => 1,
                   5468:                  );
                   5469:     }
1.976     raeburn  5470:     return if (!defined($tools{$tool}));
                   5471: 
                   5472:     if ((!defined($udom)) || (!defined($uname))) {
                   5473:         $udom = $env{'user.domain'};
                   5474:         $uname = $env{'user.name'};
                   5475:     }
                   5476: 
1.978     raeburn  5477:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5478:         if ($action ne 'reload') {
1.985     raeburn  5479:             if ($context eq 'requestcourses') {
                   5480:                 return $env{'environment.canrequest.'.$tool};
                   5481:             } else {
                   5482:                 return $env{'environment.availabletools.'.$tool};
                   5483:             }
                   5484:         }
1.976     raeburn  5485:     }
                   5486: 
                   5487:     my ($toolstatus,$inststatus);
                   5488: 
1.985     raeburn  5489:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5490:          ($action ne 'reload')) {
                   5491:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5492:         $inststatus = $env{'environment.inststatus'};
                   5493:     } else {
1.1084    raeburn  5494:         if (ref($userenvref) eq 'HASH') {
                   5495:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5496:             $inststatus = $userenvref->{'inststatus'};
                   5497:         } else {
                   5498:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5499:             $toolstatus = $userenv{$context.'.'.$tool};
                   5500:             $inststatus = $userenv{'inststatus'};
                   5501:         }
1.976     raeburn  5502:     }
                   5503: 
                   5504:     if ($toolstatus ne '') {
                   5505:         if ($toolstatus) {
                   5506:             $access = 1;
                   5507:         } else {
                   5508:             $access = 0;
                   5509:         }
                   5510:         return $access;
                   5511:     }
                   5512: 
1.1084    raeburn  5513:     my ($is_adv,%domdef);
                   5514:     if (ref($is_advref) eq 'HASH') {
                   5515:         $is_adv = $is_advref->{'is_adv'};
                   5516:     } else {
                   5517:         $is_adv = &is_advanced_user($udom,$uname);
                   5518:     }
                   5519:     if (ref($domdefref) eq 'HASH') {
                   5520:         %domdef = %{$domdefref};
                   5521:     } else {
                   5522:         %domdef = &get_domain_defaults($udom);
                   5523:     }
1.976     raeburn  5524:     if (ref($domdef{$tool}) eq 'HASH') {
                   5525:         if ($is_adv) {
                   5526:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5527:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5528:                     $access = 1;
                   5529:                 } else {
                   5530:                     $access = 0;
                   5531:                 }
                   5532:                 return $access;
                   5533:             }
                   5534:         }
                   5535:         if ($inststatus ne '') {
                   5536:             my ($hasaccess,$hasnoaccess);
                   5537:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5538:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5539:                     if ($domdef{$tool}{$affiliation}) {
                   5540:                         $hasaccess = 1;
                   5541:                     } else {
                   5542:                         $hasnoaccess = 1;
                   5543:                     }
                   5544:                 }
                   5545:             }
                   5546:             if ($hasaccess || $hasnoaccess) {
                   5547:                 if ($hasaccess) {
                   5548:                     $access = 1;
                   5549:                 } elsif ($hasnoaccess) {
                   5550:                     $access = 0; 
                   5551:                 }
                   5552:                 return $access;
                   5553:             }
                   5554:         } else {
                   5555:             if ($domdef{$tool}{'default'} ne '') {
                   5556:                 if ($domdef{$tool}{'default'}) {
                   5557:                     $access = 1;
                   5558:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5559:                     $access = 0;
                   5560:                 }
                   5561:                 return $access;
                   5562:             }
                   5563:         }
                   5564:     } else {
1.985     raeburn  5565:         if ($context eq 'tools') {
                   5566:             $access = 1;
                   5567:         } else {
                   5568:             $access = 0;
                   5569:         }
1.976     raeburn  5570:         return $access;
                   5571:     }
                   5572: }
                   5573: 
1.1050    raeburn  5574: sub is_course_owner {
                   5575:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5576:     if (($udom eq '') || ($uname eq '')) {
                   5577:         $udom = $env{'user.domain'};
                   5578:         $uname = $env{'user.name'};
                   5579:     }
                   5580:     unless (($udom eq '') || ($uname eq '')) {
                   5581:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5582:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5583:                 return 1;
                   5584:             } else {
                   5585:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5586:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5587:                     return 1;
                   5588:                 }
                   5589:             }
                   5590:         }
                   5591:     }
                   5592:     return;
                   5593: }
                   5594: 
1.976     raeburn  5595: sub is_advanced_user {
                   5596:     my ($udom,$uname) = @_;
1.1085    raeburn  5597:     if ($udom ne '' && $uname ne '') {
                   5598:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5599:             if (wantarray) {
                   5600:                 return ($env{'user.adv'},$env{'user.author'});
                   5601:             } else {
                   5602:                 return $env{'user.adv'};
                   5603:             }
1.1085    raeburn  5604:         }
                   5605:     }
1.976     raeburn  5606:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5607:     my %allroles;
1.1128    raeburn  5608:     my ($is_adv,$is_author);
1.976     raeburn  5609:     foreach my $role (keys(%roleshash)) {
                   5610:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5611:         my $area = '/'.$tdomain.'/'.$trest;
                   5612:         if ($sec ne '') {
                   5613:             $area .= '/'.$sec;
                   5614:         }
                   5615:         if (($area ne '') && ($trole ne '')) {
                   5616:             my $spec=$trole.'.'.$area;
                   5617:             if ($trole =~ /^cr\//) {
                   5618:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5619:             } elsif ($trole ne 'gr') {
                   5620:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5621:             }
1.1128    raeburn  5622:             if ($trole eq 'au') {
                   5623:                 $is_author = 1;
                   5624:             }
1.976     raeburn  5625:         }
                   5626:     }
                   5627:     foreach my $role (keys(%allroles)) {
                   5628:         last if ($is_adv);
                   5629:         foreach my $item (split(/:/,$allroles{$role})) {
                   5630:             if ($item ne '') {
                   5631:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5632:                 if ($privilege eq 'adv') {
                   5633:                     $is_adv = 1;
                   5634:                     last;
                   5635:                 }
                   5636:             }
                   5637:         }
                   5638:     }
1.1128    raeburn  5639:     if (wantarray) {
                   5640:         return ($is_adv,$is_author);
                   5641:     }
1.976     raeburn  5642:     return $is_adv;
                   5643: }
1.798     raeburn  5644: 
1.1035    raeburn  5645: sub check_can_request {
1.1036    raeburn  5646:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5647:     my $canreq = 0;
                   5648:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5649:     my @options = ('approval','validate','autolimit');
                   5650:     my $optregex = join('|',@options);
                   5651:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5652:         foreach my $type (@{$types}) {
                   5653:             if (&usertools_access($env{'user.name'},
                   5654:                                   $env{'user.domain'},
                   5655:                                   $type,undef,'requestcourses')) {
                   5656:                 $canreq ++;
1.1036    raeburn  5657:                 if (ref($request_domains) eq 'HASH') {
                   5658:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5659:                 }
1.1035    raeburn  5660:                 if ($dom eq $env{'user.domain'}) {
                   5661:                     $can_request->{$type} = 1;
                   5662:                 }
                   5663:             }
                   5664:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5665:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5666:                 if (@curr > 0) {
1.1036    raeburn  5667:                     foreach my $item (@curr) {
                   5668:                         if (ref($request_domains) eq 'HASH') {
                   5669:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5670:                             if ($otherdom ne '') {
                   5671:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5672:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5673:                                         push(@{$request_domains->{$type}},$otherdom);
                   5674:                                     }
                   5675:                                 } else {
                   5676:                                     push(@{$request_domains->{$type}},$otherdom);
                   5677:                                 }
                   5678:                             }
                   5679:                         }
                   5680:                     }
                   5681:                     unless($dom eq $env{'user.domain'}) {
                   5682:                         $canreq ++;
1.1035    raeburn  5683:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5684:                             $can_request->{$type} = 1;
                   5685:                         }
                   5686:                     }
                   5687:                 }
                   5688:             }
                   5689:         }
                   5690:     }
                   5691:     return $canreq;
                   5692: }
                   5693: 
1.341     www      5694: # ---------------------------------------------- Custom access rule evaluation
                   5695: 
                   5696: sub customaccess {
                   5697:     my ($priv,$uri)=@_;
1.807     albertel 5698:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5699:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5700:     $udom = &LONCAPA::clean_domain($udom);
                   5701:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5702:     my $access=0;
1.800     albertel 5703:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5704: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5705: 	if ($type eq 'user') {
                   5706: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5707: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5708: 		if ($tdom) {
                   5709: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5710: 		}
1.896     albertel 5711: 		if ($tuname) {
                   5712: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5713: 		}
                   5714: 		$access=($effect eq 'allow');
                   5715: 		last;
                   5716: 	    }
                   5717: 	} else {
                   5718: 	    if ($role) {
                   5719: 		if ($role ne $urole) { next; }
                   5720: 	    }
                   5721: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5722: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5723: 		if ($tdom) {
                   5724: 		    if ($tdom ne $udom) { next; }
                   5725: 		}
                   5726: 		if ($tcrs) {
                   5727: 		    if ($tcrs ne $ucrs) { next; }
                   5728: 		}
                   5729: 		if ($tsec) {
                   5730: 		    if ($tsec ne $usec) { next; }
                   5731: 		}
                   5732: 		$access=($effect eq 'allow');
                   5733: 		last;
                   5734: 	    }
                   5735: 	    if ($realm eq '' && $role eq '') {
                   5736: 		$access=($effect eq 'allow');
                   5737: 	    }
1.402     bowersj2 5738: 	}
1.341     www      5739:     }
                   5740:     return $access;
                   5741: }
                   5742: 
1.103     harris41 5743: # ------------------------------------------------- Check for a user privilege
1.12      www      5744: 
                   5745: sub allowed {
1.810     raeburn  5746:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5747:     my $ver_orguri=$uri;
1.439     www      5748:     $uri=&deversion($uri);
1.152     www      5749:     my $orguri=$uri;
1.52      www      5750:     $uri=&declutter($uri);
1.809     raeburn  5751: 
1.810     raeburn  5752:     if ($priv eq 'evb') {
                   5753: # Evade communication block restrictions for specified role in a course
                   5754:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5755:             return $1;
                   5756:         } else {
                   5757:             return;
                   5758:         }
                   5759:     }
                   5760: 
1.620     albertel 5761:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5762: # Free bre access to adm and meta resources
1.775     albertel 5763:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5764: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5765: 	&& ($priv eq 'bre')) {
1.14      www      5766: 	return 'F';
1.159     www      5767:     }
                   5768: 
1.545     banghart 5769: # Free bre access to user's own portfolio contents
1.714     raeburn  5770:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5771:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5772: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5773:         my %setters;
                   5774:         my ($startblock,$endblock) = 
                   5775:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5776:         if ($startblock && $endblock) {
                   5777:             return 'B';
                   5778:         } else {
                   5779:             return 'F';
                   5780:         }
1.545     banghart 5781:     }
                   5782: 
1.762     raeburn  5783: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5784:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5785:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5786:         if (exists($env{'request.course.id'})) {
                   5787:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5788:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5789:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5790:                 my $courseprivid=$env{'request.course.id'};
                   5791:                 $courseprivid=~s/\_/\//;
                   5792:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5793:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5794:                     return $1; 
1.762     raeburn  5795:                 } else {
                   5796:                     if ($env{'request.course.sec'}) {
                   5797:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5798:                     }
                   5799:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5800:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5801:                         return $2;
                   5802:                     }
1.714     raeburn  5803:                 }
                   5804:             }
                   5805:         }
                   5806:     }
                   5807: 
1.159     www      5808: # Free bre to public access
                   5809: 
                   5810:     if ($priv eq 'bre') {
1.238     www      5811:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5812: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5813:            return 'F'; 
                   5814:         }
1.238     www      5815:         if ($copyright eq 'priv') {
                   5816:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5817: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5818: 		return '';
                   5819:             }
                   5820:         }
                   5821:         if ($copyright eq 'domain') {
                   5822:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5823: 	    unless (($env{'user.domain'} eq $1) ||
                   5824:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5825: 		return '';
                   5826:             }
1.262     matthew  5827:         }
1.620     albertel 5828:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5829:             # Library role, so allow browsing of resources in this domain.
                   5830:             return 'F';
1.238     www      5831:         }
1.341     www      5832:         if ($copyright eq 'custom') {
                   5833: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5834:         }
1.14      www      5835:     }
1.264     matthew  5836:     # Domain coordinator is trying to create a course
1.620     albertel 5837:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5838:         # uri is the requested domain in this case.
                   5839:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5840:         # a role of dc for the domain in question.
1.620     albertel 5841:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5842:     }
1.29      www      5843: 
1.52      www      5844:     my $thisallowed='';
                   5845:     my $statecond=0;
                   5846:     my $courseprivid='';
                   5847: 
1.1039    raeburn  5848:     my $ownaccess;
1.1043    raeburn  5849:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5850:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5851:         if ($uri eq '') {
                   5852:             $ownaccess = 1;
                   5853:         } else {
                   5854:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5855:                 my $udom = $env{'user.domain'};
                   5856:                 my $uname = $env{'user.name'};
                   5857:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5858:                     $ownaccess = 1;
1.1040    raeburn  5859:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5860:                     unless ($uri =~ m{\.\./}) {
                   5861:                         $ownaccess = 1;
                   5862:                     }
                   5863:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5864:                     my $now = time;
                   5865:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5866:                         my $adom = $1;
                   5867:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5868:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5869:                                 my ($start,$end) = split('.',$env{$key});
                   5870:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5871:                                     $ownaccess = 1;
                   5872:                                     last;
                   5873:                                 }
                   5874:                             }
                   5875:                         }
                   5876:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5877:                         my $adom = $1;
                   5878:                         my $aname = $2;
1.1042    raeburn  5879:                         foreach my $role ('ca','aa') { 
                   5880:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5881:                                 my ($start,$end) =
                   5882:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5883:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5884:                                     $ownaccess = 1;
                   5885:                                     last;
                   5886:                                 }
1.1039    raeburn  5887:                             }
                   5888:                         }
                   5889:                     }
                   5890:                 }
                   5891:             }
                   5892:         }
                   5893:     }
                   5894: 
1.52      www      5895: # Course
                   5896: 
1.620     albertel 5897:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5898:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5899:             $thisallowed.=$1;
                   5900:         }
1.52      www      5901:     }
1.29      www      5902: 
1.52      www      5903: # Domain
                   5904: 
1.620     albertel 5905:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5906:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5907:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5908:             $thisallowed.=$1;
                   5909:         }
1.12      www      5910:     }
1.52      www      5911: 
                   5912: # Course: uri itself is a course
1.66      www      5913:     my $courseuri=$uri;
                   5914:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5915:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5916: 
1.620     albertel 5917:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5918:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5919:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5920:             $thisallowed.=$1;
                   5921:         }
1.12      www      5922:     }
1.29      www      5923: 
1.665     albertel 5924: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5925: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5926:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5927: 	$thisallowed='';
1.671     raeburn  5928:         my ($match)=&is_on_map($uri);
                   5929:         if ($match) {
                   5930:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5931:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5932:                 $thisallowed.=$1;
                   5933:             }
                   5934:         } else {
1.705     albertel 5935:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5936:             if ($refuri) {
                   5937:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5938:                     $thisallowed='F';
1.671     raeburn  5939:                 } else {
                   5940:                     $refuri=&declutter($refuri);
                   5941:                     my ($match) = &is_on_map($refuri);
                   5942:                     if ($match) {
                   5943:                         $thisallowed='F';
                   5944:                     }
1.669     raeburn  5945:                 }
1.671     raeburn  5946:             }
                   5947:         }
1.314     www      5948:     }
1.492     albertel 5949: 
1.766     albertel 5950:     if ($priv eq 'bre'
                   5951: 	&& $thisallowed ne 'F' 
                   5952: 	&& $thisallowed ne '2'
                   5953: 	&& &is_portfolio_url($uri)) {
                   5954: 	$thisallowed = &portfolio_access($uri);
                   5955:     }
                   5956:     
1.52      www      5957: # Full access at system, domain or course-wide level? Exit.
1.29      www      5958:     if ($thisallowed=~/F/) {
                   5959: 	return 'F';
                   5960:     }
                   5961: 
1.52      www      5962: # If this is generating or modifying users, exit with special codes
1.29      www      5963: 
1.643     www      5964:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5965: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5966: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5967: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5968: 	    unless ($auname) { return $thisallowed; }
                   5969: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5970: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5971: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5972: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5973: 	}
1.52      www      5974: 	return $thisallowed;
                   5975:     }
                   5976: #
1.103     harris41 5977: # Gathered so far: system, domain and course wide privileges
1.52      www      5978: #
                   5979: # Course: See if uri or referer is an individual resource that is part of 
                   5980: # the course
                   5981: 
1.620     albertel 5982:     if ($env{'request.course.id'}) {
1.232     www      5983: 
1.620     albertel 5984:        $courseprivid=$env{'request.course.id'};
                   5985:        if ($env{'request.course.sec'}) {
                   5986:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5987:        }
                   5988:        $courseprivid=~s/\_/\//;
                   5989:        my $checkreferer=1;
1.232     www      5990:        my ($match,$cond)=&is_on_map($uri);
                   5991:        if ($match) {
                   5992:            $statecond=$cond;
1.620     albertel 5993:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 5994:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      5995:                $thisallowed.=$1;
                   5996:                $checkreferer=0;
                   5997:            }
1.29      www      5998:        }
1.83      www      5999:        
1.148     www      6000:        if ($checkreferer) {
1.620     albertel 6001: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6002:             unless ($refuri) {
1.800     albertel 6003:                 foreach my $key (keys(%env)) {
                   6004: 		    if ($key=~/^httpref\..*\*/) {
                   6005: 			my $pattern=$key;
1.156     www      6006:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6007:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6008:                         $pattern=~s/\//\\\//g;
1.152     www      6009:                         if ($orguri=~/$pattern/) {
1.800     albertel 6010: 			    $refuri=$env{$key};
1.148     www      6011:                         }
                   6012:                     }
1.191     harris41 6013:                 }
1.148     www      6014:             }
1.232     www      6015: 
1.148     www      6016:          if ($refuri) { 
1.152     www      6017: 	  $refuri=&declutter($refuri);
1.232     www      6018:           my ($match,$cond)=&is_on_map($refuri);
                   6019:             if ($match) {
                   6020:               my $refstatecond=$cond;
1.620     albertel 6021:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6022:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      6023:                   $thisallowed.=$1;
1.53      www      6024:                   $uri=$refuri;
                   6025:                   $statecond=$refstatecond;
1.52      www      6026:               }
                   6027:           }
1.148     www      6028:         }
1.29      www      6029:        }
1.52      www      6030:    }
1.29      www      6031: 
1.52      www      6032: #
1.103     harris41 6033: # Gathered now: all privileges that could apply, and condition number
1.52      www      6034: # 
                   6035: #
                   6036: # Full or no access?
                   6037: #
1.29      www      6038: 
1.52      www      6039:     if ($thisallowed=~/F/) {
                   6040: 	return 'F';
                   6041:     }
1.29      www      6042: 
1.52      www      6043:     unless ($thisallowed) {
                   6044:         return '';
                   6045:     }
1.29      www      6046: 
1.52      www      6047: # Restrictions exist, deal with them
                   6048: #
                   6049: #   C:according to course preferences
                   6050: #   R:according to resource settings
                   6051: #   L:unless locked
                   6052: #   X:according to user session state
                   6053: #
                   6054: 
                   6055: # Possibly locked functionality, check all courses
1.54      www      6056: # Locks might take effect only after 10 minutes cache expiration for other
                   6057: # courses, and 2 minutes for current course
1.52      www      6058: 
                   6059:     my $envkey;
                   6060:     if ($thisallowed=~/L/) {
1.1000    raeburn  6061:         foreach $envkey (keys(%env)) {
1.54      www      6062:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6063:                my $courseid=$2;
                   6064:                my $roleid=$1.'.'.$2;
1.92      www      6065:                $courseid=~s/^\///;
1.54      www      6066:                my $expiretime=600;
1.620     albertel 6067:                if ($env{'request.role'} eq $roleid) {
1.54      www      6068: 		  $expiretime=120;
                   6069:                }
                   6070: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6071:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6072:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6073: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6074:                }
1.620     albertel 6075:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6076:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6077: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6078:                        &log($env{'user.domain'},$env{'user.name'},
                   6079:                             $env{'user.home'},
1.57      www      6080:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6081:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6082:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6083: 		       return '';
                   6084:                    }
                   6085:                }
1.620     albertel 6086:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6087:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6088: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6089:                        &log($env{'user.domain'},$env{'user.name'},
                   6090:                             $env{'user.home'},
1.57      www      6091:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6092:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6093:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6094: 		       return '';
                   6095:                    }
                   6096:                }
                   6097: 	   }
1.29      www      6098:        }
1.52      www      6099:     }
                   6100:    
                   6101: #
                   6102: # Rest of the restrictions depend on selected course
                   6103: #
                   6104: 
1.620     albertel 6105:     unless ($env{'request.course.id'}) {
1.766     albertel 6106: 	if ($thisallowed eq 'A') {
                   6107: 	    return 'A';
1.814     raeburn  6108:         } elsif ($thisallowed eq 'B') {
                   6109:             return 'B';
1.766     albertel 6110: 	} else {
                   6111: 	    return '1';
                   6112: 	}
1.52      www      6113:     }
1.29      www      6114: 
1.52      www      6115: #
                   6116: # Now user is definitely in a course
                   6117: #
1.53      www      6118: 
                   6119: 
                   6120: # Course preferences
                   6121: 
                   6122:    if ($thisallowed=~/C/) {
1.620     albertel 6123:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6124:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6125:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6126: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6127: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6128: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6129: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6130: 			$env{'request.course.id'});
                   6131: 	   }
1.237     www      6132:            return '';
                   6133:        }
                   6134: 
1.620     albertel 6135:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6136: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6137: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6138: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6139: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6140: 			$env{'request.course.id'});
                   6141: 	   }
1.54      www      6142:            return '';
                   6143:        }
1.53      www      6144:    }
                   6145: 
                   6146: # Resource preferences
                   6147: 
                   6148:    if ($thisallowed=~/R/) {
1.620     albertel 6149:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6150:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6151: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6152: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6153: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6154: 	   }
                   6155: 	   return '';
1.54      www      6156:        }
1.53      www      6157:    }
1.30      www      6158: 
1.246     www      6159: # Restricted by state or randomout?
1.30      www      6160: 
1.52      www      6161:    if ($thisallowed=~/X/) {
1.620     albertel 6162:       if ($env{'acc.randomout'}) {
1.579     albertel 6163: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6164:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6165:             return ''; 
                   6166:          }
1.247     www      6167:       }
                   6168:       if (&condval($statecond)) {
1.52      www      6169: 	 return '2';
                   6170:       } else {
                   6171:          return '';
                   6172:       }
                   6173:    }
1.30      www      6174: 
1.766     albertel 6175:     if ($thisallowed eq 'A') {
                   6176: 	return 'A';
1.814     raeburn  6177:     } elsif ($thisallowed eq 'B') {
                   6178:         return 'B';
1.766     albertel 6179:     }
1.52      www      6180:    return 'F';
1.232     www      6181: }
                   6182: 
1.710     albertel 6183: sub split_uri_for_cond {
                   6184:     my $uri=&deversion(&declutter(shift));
                   6185:     my @uriparts=split(/\//,$uri);
                   6186:     my $filename=pop(@uriparts);
                   6187:     my $pathname=join('/',@uriparts);
                   6188:     return ($pathname,$filename);
                   6189: }
1.232     www      6190: # --------------------------------------------------- Is a resource on the map?
                   6191: 
                   6192: sub is_on_map {
1.710     albertel 6193:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6194:     #Trying to find the conditional for the file
1.620     albertel 6195:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6196: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6197:     if ($match) {
1.289     bowersj2 6198: 	return (1,$1);
                   6199:     } else {
1.434     www      6200: 	return (0,0);
1.289     bowersj2 6201:     }
1.12      www      6202: }
                   6203: 
1.427     www      6204: # --------------------------------------------------------- Get symb from alias
                   6205: 
                   6206: sub get_symb_from_alias {
                   6207:     my $symb=shift;
                   6208:     my ($map,$resid,$url)=&decode_symb($symb);
                   6209: # Already is a symb
                   6210:     if ($url) { return $symb; }
                   6211: # Must be an alias
                   6212:     my $aliassymb='';
                   6213:     my %bighash;
1.620     albertel 6214:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6215:                             &GDBM_READER(),0640)) {
                   6216:         my $rid=$bighash{'mapalias_'.$symb};
                   6217: 	if ($rid) {
                   6218: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6219: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6220: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6221: 	}
                   6222:         untie %bighash;
                   6223:     }
                   6224:     return $aliassymb;
                   6225: }
                   6226: 
1.12      www      6227: # ----------------------------------------------------------------- Define Role
                   6228: 
                   6229: sub definerole {
                   6230:   if (allowed('mcr','/')) {
                   6231:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6232:     foreach my $role (split(':',$sysrole)) {
                   6233: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6234:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6235:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6236: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6237:                return "refused:s:$crole&$cqual"; 
                   6238:             }
                   6239:         }
1.191     harris41 6240:     }
1.800     albertel 6241:     foreach my $role (split(':',$domrole)) {
                   6242: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6243:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6244:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6245: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6246:                return "refused:d:$crole&$cqual"; 
                   6247:             }
                   6248:         }
1.191     harris41 6249:     }
1.800     albertel 6250:     foreach my $role (split(':',$courole)) {
                   6251: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6252:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6253:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6254: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6255:                return "refused:c:$crole&$cqual"; 
                   6256:             }
                   6257:         }
1.191     harris41 6258:     }
1.620     albertel 6259:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6260:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6261: 	        "rolesdef_$rolename=".
                   6262:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6263:     return reply($command,$env{'user.home'});
1.12      www      6264:   } else {
                   6265:     return 'refused';
                   6266:   }
1.105     harris41 6267: }
                   6268: 
                   6269: # ---------------- Make a metadata query against the network of library servers
                   6270: 
                   6271: sub metadata_query {
1.244     matthew  6272:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6273:     my %rhash;
1.845     albertel 6274:     my %libserv = &all_library();
1.244     matthew  6275:     my @server_list = (defined($server_array) ? @$server_array
                   6276:                                               : keys(%libserv) );
                   6277:     for my $server (@server_list) {
1.118     harris41 6278: 	unless ($custom or $customshow) {
                   6279: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6280: 	    $rhash{$server}=$reply;
                   6281: 	}
                   6282: 	else {
                   6283: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6284: 			     &escape($custom).':'.&escape($customshow),
                   6285: 			     $server);
                   6286: 	    $rhash{$server}=$reply;
                   6287: 	}
1.112     harris41 6288:     }
1.118     harris41 6289:     return \%rhash;
1.240     www      6290: }
                   6291: 
                   6292: # ----------------------------------------- Send log queries and wait for reply
                   6293: 
                   6294: sub log_query {
                   6295:     my ($uname,$udom,$query,%filters)=@_;
                   6296:     my $uhome=&homeserver($uname,$udom);
                   6297:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6298:     my $uhost=&hostname($uhome);
1.800     albertel 6299:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6300:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6301:                        $uhome);
1.479     albertel 6302:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6303:     return get_query_reply($queryid);
                   6304: }
                   6305: 
1.818     raeburn  6306: # -------------------------- Update MySQL table for portfolio file
                   6307: 
                   6308: sub update_portfolio_table {
1.821     raeburn  6309:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6310:     if ($group ne '') {
                   6311:         $file_name =~s /^\Q$group\E//;
                   6312:     }
1.818     raeburn  6313:     my $homeserver = &homeserver($uname,$udom);
                   6314:     my $queryid=
1.821     raeburn  6315:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6316:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6317:     my $reply = &get_query_reply($queryid);
                   6318:     return $reply;
                   6319: }
                   6320: 
1.899     raeburn  6321: # -------------------------- Update MySQL allusers table
                   6322: 
                   6323: sub update_allusers_table {
                   6324:     my ($uname,$udom,$names) = @_;
                   6325:     my $homeserver = &homeserver($uname,$udom);
                   6326:     my $queryid=
                   6327:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6328:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6329:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6330:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6331:                'generation='.&escape($names->{'generation'}).'%%'.
                   6332:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6333:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6334:     return;
1.899     raeburn  6335: }
                   6336: 
1.508     raeburn  6337: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6338: 
                   6339: sub fetch_enrollment_query {
1.511     raeburn  6340:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6341:     my $homeserver;
1.547     raeburn  6342:     my $maxtries = 1;
1.508     raeburn  6343:     if ($context eq 'automated') {
                   6344:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6345:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6346:     } else {
                   6347:         $homeserver = &homeserver($cnum,$dom);
                   6348:     }
1.838     albertel 6349:     my $host=&hostname($homeserver);
1.506     raeburn  6350:     my $cmd = '';
1.1000    raeburn  6351:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6352:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6353:     }
                   6354:     $cmd =~ s/%%$//;
                   6355:     $cmd = &escape($cmd);
                   6356:     my $query = 'fetchenrollment';
1.620     albertel 6357:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6358:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6359:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6360:         return 'error: '.$queryid;
                   6361:     }
1.506     raeburn  6362:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6363:     my $tries = 1;
                   6364:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6365:         $reply = &get_query_reply($queryid);
                   6366:         $tries ++;
                   6367:     }
1.526     raeburn  6368:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6369:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6370:     } else {
1.901     albertel 6371:         my @responses = split(/:/,$reply);
1.515     raeburn  6372:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6373:             foreach my $line (@responses) {
                   6374:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6375:                 $$replyref{$key} = $value;
                   6376:             }
                   6377:         } else {
1.1117    foxr     6378:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6379:             foreach my $line (@responses) {
                   6380:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6381:                 $$replyref{$key} = $value;
                   6382:                 if ($value > 0) {
1.800     albertel 6383:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6384:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6385:                         my $destname = $pathname.'/'.$filename;
                   6386:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6387:                         if ($xml_classlist =~ /^error/) {
                   6388:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6389:                         } else {
1.506     raeburn  6390:                             if ( open(FILE,">$destname") ) {
                   6391:                                 print FILE &unescape($xml_classlist);
                   6392:                                 close(FILE);
1.526     raeburn  6393:                             } else {
                   6394:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6395:                             }
                   6396:                         }
                   6397:                     }
                   6398:                 }
                   6399:             }
                   6400:         }
                   6401:         return 'ok';
                   6402:     }
                   6403:     return 'error';
                   6404: }
                   6405: 
1.242     www      6406: sub get_query_reply {
                   6407:     my $queryid=shift;
1.1117    foxr     6408:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6409:     my $reply='';
                   6410:     for (1..100) {
                   6411: 	sleep 2;
                   6412:         if (-e $replyfile.'.end') {
1.448     albertel 6413: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6414: 		$reply = join('',<$fh>);
                   6415: 		close($fh);
1.240     www      6416: 	   } else { return 'error: reply_file_error'; }
1.242     www      6417:            return &unescape($reply);
                   6418: 	}
1.240     www      6419:     }
1.242     www      6420:     return 'timeout:'.$queryid;
1.240     www      6421: }
                   6422: 
                   6423: sub courselog_query {
1.241     www      6424: #
                   6425: # possible filters:
                   6426: # url: url or symb
                   6427: # username
                   6428: # domain
                   6429: # action: view, submit, grade
                   6430: # start: timestamp
                   6431: # end: timestamp
                   6432: #
1.240     www      6433:     my (%filters)=@_;
1.620     albertel 6434:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6435:     if ($filters{'url'}) {
                   6436: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6437:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6438:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6439:     }
1.620     albertel 6440:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6441:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6442:     return &log_query($cname,$cdom,'courselog',%filters);
                   6443: }
                   6444: 
                   6445: sub userlog_query {
1.858     raeburn  6446: #
                   6447: # possible filters:
                   6448: # action: log check role
                   6449: # start: timestamp
                   6450: # end: timestamp
                   6451: #
1.240     www      6452:     my ($uname,$udom,%filters)=@_;
                   6453:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6454: }
                   6455: 
1.506     raeburn  6456: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6457: 
                   6458: sub auto_run {
1.508     raeburn  6459:     my ($cnum,$cdom) = @_;
1.876     raeburn  6460:     my $response = 0;
                   6461:     my $settings;
                   6462:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6463:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6464:         $settings = $domconfig{'autoenroll'};
                   6465:         if ($settings->{'run'} eq '1') {
                   6466:             $response = 1;
                   6467:         }
                   6468:     } else {
1.934     raeburn  6469:         my $homeserver;
                   6470:         if (&is_course($cdom,$cnum)) {
                   6471:             $homeserver = &homeserver($cnum,$cdom);
                   6472:         } else {
                   6473:             $homeserver = &domain($cdom,'primary');
                   6474:         }
                   6475:         if ($homeserver ne 'no_host') {
                   6476:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6477:         }
1.876     raeburn  6478:     }
1.506     raeburn  6479:     return $response;
                   6480: }
1.776     albertel 6481: 
1.506     raeburn  6482: sub auto_get_sections {
1.508     raeburn  6483:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6484:     my $homeserver;
                   6485:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6486:         $homeserver = &homeserver($cnum,$cdom);
                   6487:     }
                   6488:     if (!defined($homeserver)) { 
                   6489:         if ($cdom =~ /^$match_domain$/) {
                   6490:             $homeserver = &domain($cdom,'primary');
                   6491:         }
                   6492:     }
                   6493:     my @secs;
                   6494:     if (defined($homeserver)) {
                   6495:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6496:         unless ($response eq 'refused') {
                   6497:             @secs = split(/:/,$response);
                   6498:         }
1.506     raeburn  6499:     }
                   6500:     return @secs;
                   6501: }
1.776     albertel 6502: 
1.506     raeburn  6503: sub auto_new_course {
1.1099    raeburn  6504:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6505:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6506:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6507:     return $response;
                   6508: }
1.776     albertel 6509: 
1.506     raeburn  6510: sub auto_validate_courseID {
1.508     raeburn  6511:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6512:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6513:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6514:     return $response;
                   6515: }
1.776     albertel 6516: 
1.1007    raeburn  6517: sub auto_validate_instcode {
1.1020    raeburn  6518:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6519:     my ($homeserver,$response);
                   6520:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6521:         $homeserver = &homeserver($cnum,$cdom);
                   6522:     }
                   6523:     if (!defined($homeserver)) {
                   6524:         if ($cdom =~ /^$match_domain$/) {
                   6525:             $homeserver = &domain($cdom,'primary');
                   6526:         }
                   6527:     }
1.1065    raeburn  6528:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6529:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6530:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6531:     return ($outcome,$description);
1.1007    raeburn  6532: }
                   6533: 
1.506     raeburn  6534: sub auto_create_password {
1.873     raeburn  6535:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6536:     my ($homeserver,$response);
1.506     raeburn  6537:     my $create_passwd = 0;
                   6538:     my $authchk = '';
1.873     raeburn  6539:     if ($udom =~ /^$match_domain$/) {
                   6540:         $homeserver = &domain($udom,'primary');
                   6541:     }
                   6542:     if ($homeserver eq '') {
                   6543:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6544:             $homeserver = &homeserver($cnum,$cdom);
                   6545:         }
                   6546:     }
                   6547:     if ($homeserver eq '') {
                   6548:         $authchk = 'nodomain';
1.506     raeburn  6549:     } else {
1.873     raeburn  6550:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6551:         if ($response eq 'refused') {
                   6552:             $authchk = 'refused';
                   6553:         } else {
1.901     albertel 6554:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6555:         }
1.506     raeburn  6556:     }
                   6557:     return ($authparam,$create_passwd,$authchk);
                   6558: }
                   6559: 
1.706     raeburn  6560: sub auto_photo_permission {
                   6561:     my ($cnum,$cdom,$students) = @_;
                   6562:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6563:     my ($outcome,$perm_reqd,$conditions) = 
                   6564: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6565:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6566: 	return (undef,undef);
                   6567:     }
1.706     raeburn  6568:     return ($outcome,$perm_reqd,$conditions);
                   6569: }
                   6570: 
                   6571: sub auto_checkphotos {
                   6572:     my ($uname,$udom,$pid) = @_;
                   6573:     my $homeserver = &homeserver($uname,$udom);
                   6574:     my ($result,$resulttype);
                   6575:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6576: 				   &escape($uname).':'.&escape($pid),
                   6577: 				   $homeserver));
1.709     albertel 6578:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6579: 	return (undef,undef);
                   6580:     }
1.706     raeburn  6581:     if ($outcome) {
                   6582:         ($result,$resulttype) = split(/:/,$outcome);
                   6583:     } 
                   6584:     return ($result,$resulttype);
                   6585: }
                   6586: 
                   6587: sub auto_photochoice {
                   6588:     my ($cnum,$cdom) = @_;
                   6589:     my $homeserver = &homeserver($cnum,$cdom);
                   6590:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6591: 						       &escape($cdom),
                   6592: 						       $homeserver)));
1.709     albertel 6593:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6594: 	return (undef,undef);
                   6595:     }
1.706     raeburn  6596:     return ($update,$comment);
                   6597: }
                   6598: 
                   6599: sub auto_photoupdate {
                   6600:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6601:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6602:     my $host=&hostname($homeserver);
1.706     raeburn  6603:     my $cmd = '';
                   6604:     my $maxtries = 1;
1.800     albertel 6605:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6606:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6607:     }
                   6608:     $cmd =~ s/%%$//;
                   6609:     $cmd = &escape($cmd);
                   6610:     my $query = 'institutionalphotos';
                   6611:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6612:     unless ($queryid=~/^\Q$host\E\_/) {
                   6613:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6614:         return 'error: '.$queryid;
                   6615:     }
                   6616:     my $reply = &get_query_reply($queryid);
                   6617:     my $tries = 1;
                   6618:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6619:         $reply = &get_query_reply($queryid);
                   6620:         $tries ++;
                   6621:     }
                   6622:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6623:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6624:     } else {
                   6625:         my @responses = split(/:/,$reply);
                   6626:         my $outcome = shift(@responses); 
                   6627:         foreach my $item (@responses) {
                   6628:             my ($key,$value) = split(/=/,$item);
                   6629:             $$photo{$key} = $value;
                   6630:         }
                   6631:         return $outcome;
                   6632:     }
                   6633:     return 'error';
                   6634: }
                   6635: 
1.521     raeburn  6636: sub auto_instcode_format {
1.793     albertel 6637:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6638: 	$cat_order) = @_;
1.521     raeburn  6639:     my $courses = '';
1.772     raeburn  6640:     my @homeservers;
1.521     raeburn  6641:     if ($caller eq 'global') {
1.841     albertel 6642: 	my %servers = &get_servers($codedom,'library');
                   6643: 	foreach my $tryserver (keys(%servers)) {
                   6644: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6645: 		push(@homeservers,$tryserver);
                   6646: 	    }
1.584     raeburn  6647:         }
1.1022    raeburn  6648:     } elsif ($caller eq 'requests') {
                   6649:         if ($codedom =~ /^$match_domain$/) {
                   6650:             my $chome = &domain($codedom,'primary');
                   6651:             unless ($chome eq 'no_host') {
                   6652:                 push(@homeservers,$chome);
                   6653:             }
                   6654:         }
1.521     raeburn  6655:     } else {
1.772     raeburn  6656:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6657:     }
1.793     albertel 6658:     foreach my $code (keys(%{$instcodes})) {
                   6659:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6660:     }
                   6661:     chop($courses);
1.772     raeburn  6662:     my $ok_response = 0;
                   6663:     my $response;
                   6664:     while (@homeservers > 0 && $ok_response == 0) {
                   6665:         my $server = shift(@homeservers); 
                   6666:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6667:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6668:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6669: 		split(/:/,$response);
1.772     raeburn  6670:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6671:             push(@{$codetitles},&str2array($codetitles_str));
                   6672:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6673:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6674:             $ok_response = 1;
                   6675:         }
                   6676:     }
                   6677:     if ($ok_response) {
1.521     raeburn  6678:         return 'ok';
1.772     raeburn  6679:     } else {
                   6680:         return $response;
1.521     raeburn  6681:     }
                   6682: }
                   6683: 
1.792     raeburn  6684: sub auto_instcode_defaults {
                   6685:     my ($domain,$returnhash,$code_order) = @_;
                   6686:     my @homeservers;
1.841     albertel 6687: 
                   6688:     my %servers = &get_servers($domain,'library');
                   6689:     foreach my $tryserver (keys(%servers)) {
                   6690: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6691: 	    push(@homeservers,$tryserver);
                   6692: 	}
1.792     raeburn  6693:     }
1.841     albertel 6694: 
1.792     raeburn  6695:     my $response;
1.841     albertel 6696:     foreach my $server (@homeservers) {
1.792     raeburn  6697:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6698:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6699: 	
                   6700: 	foreach my $pair (split(/\&/,$response)) {
                   6701: 	    my ($name,$value)=split(/\=/,$pair);
                   6702: 	    if ($name eq 'code_order') {
                   6703: 		@{$code_order} = split(/\&/,&unescape($value));
                   6704: 	    } else {
                   6705: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6706: 	    }
                   6707: 	}
                   6708: 	return 'ok';
1.792     raeburn  6709:     }
1.841     albertel 6710: 
                   6711:     return $response;
1.1003    raeburn  6712: }
                   6713: 
                   6714: sub auto_possible_instcodes {
1.1007    raeburn  6715:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6716:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6717:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6718:         return;
                   6719:     }
1.1003    raeburn  6720:     my (@homeservers,$uhome);
                   6721:     if (defined(&domain($domain,'primary'))) {
                   6722:         $uhome=&domain($domain,'primary');
                   6723:         push(@homeservers,&domain($domain,'primary'));
                   6724:     } else {
                   6725:         my %servers = &get_servers($domain,'library');
                   6726:         foreach my $tryserver (keys(%servers)) {
                   6727:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6728:                 push(@homeservers,$tryserver);
                   6729:             }
                   6730:         }
                   6731:     }
                   6732:     my $response;
                   6733:     foreach my $server (@homeservers) {
                   6734:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6735:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6736:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6737:             split(':',$response);
                   6738:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6739:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6740:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6741:             my ($name,$value)=split('=',$item);
                   6742:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6743:         }
                   6744:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6745:             my ($name,$value)=split('=',$item);
                   6746:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6747:         }
                   6748:         return 'ok';
                   6749:     }
                   6750:     return $response;
                   6751: }
1.792     raeburn  6752: 
1.1010    raeburn  6753: sub auto_courserequest_checks {
                   6754:     my ($dom) = @_;
1.1020    raeburn  6755:     my ($homeserver,%validations);
                   6756:     if ($dom =~ /^$match_domain$/) {
                   6757:         $homeserver = &domain($dom,'primary');
                   6758:     }
                   6759:     unless ($homeserver eq 'no_host') {
                   6760:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6761:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6762:             my @items = split(/&/,$response);
                   6763:             foreach my $item (@items) {
                   6764:                 my ($key,$value) = split('=',$item);
                   6765:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6766:             }
                   6767:         }
                   6768:     }
1.1010    raeburn  6769:     return %validations; 
                   6770: }
                   6771: 
1.1020    raeburn  6772: sub auto_courserequest_validation {
                   6773:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6774:     my ($homeserver,$response);
                   6775:     if ($dom =~ /^$match_domain$/) {
                   6776:         $homeserver = &domain($dom,'primary');
                   6777:     }
                   6778:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6779:           
1.1020    raeburn  6780:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6781:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6782:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6783:                                     $homeserver));
                   6784:     }
                   6785:     return $response;
                   6786: }
                   6787: 
1.777     albertel 6788: sub auto_validate_class_sec {
1.918     raeburn  6789:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6790:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6791:     my $ownerlist;
                   6792:     if (ref($owners) eq 'ARRAY') {
                   6793:         $ownerlist = join(',',@{$owners});
                   6794:     } else {
                   6795:         $ownerlist = $owners;
                   6796:     }
1.773     raeburn  6797:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6798:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6799:     return $response;
                   6800: }
                   6801: 
1.679     raeburn  6802: # ------------------------------------------------------- Course Group routines
                   6803: 
                   6804: sub get_coursegroups {
1.809     raeburn  6805:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6806:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6807: }
                   6808: 
1.679     raeburn  6809: sub modify_coursegroup {
                   6810:     my ($cdom,$cnum,$groupsettings) = @_;
                   6811:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6812: }
                   6813: 
1.809     raeburn  6814: sub toggle_coursegroup_status {
                   6815:     my ($cdom,$cnum,$group,$action) = @_;
                   6816:     my ($from_namespace,$to_namespace);
                   6817:     if ($action eq 'delete') {
                   6818:         $from_namespace = 'coursegroups';
                   6819:         $to_namespace = 'deleted_groups';
                   6820:     } else {
                   6821:         $from_namespace = 'deleted_groups';
                   6822:         $to_namespace = 'coursegroups';
                   6823:     }
                   6824:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6825:     if (my $tmp = &error(%curr_group)) {
                   6826:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6827:         return ('read error',$tmp);
                   6828:     } else {
                   6829:         my %savedsettings = %curr_group; 
1.809     raeburn  6830:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6831:         my $deloutcome;
                   6832:         if ($result eq 'ok') {
1.809     raeburn  6833:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6834:         } else {
                   6835:             return ('write error',$result);
                   6836:         }
                   6837:         if ($deloutcome eq 'ok') {
                   6838:             return 'ok';
                   6839:         } else {
                   6840:             return ('delete error',$deloutcome);
                   6841:         }
                   6842:     }
                   6843: }
                   6844: 
1.679     raeburn  6845: sub modify_group_roles {
1.957     raeburn  6846:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6847:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6848:     my $role = 'gr/'.&escape($userprivs);
                   6849:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6850:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6851:     if ($result eq 'ok') {
                   6852:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6853:     }
1.679     raeburn  6854:     return $result;
                   6855: }
                   6856: 
                   6857: sub modify_coursegroup_membership {
                   6858:     my ($cdom,$cnum,$membership) = @_;
                   6859:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6860:     return $result;
                   6861: }
                   6862: 
1.682     raeburn  6863: sub get_active_groups {
                   6864:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6865:     my $now = time;
                   6866:     my %groups = ();
                   6867:     foreach my $key (keys(%env)) {
1.811     albertel 6868:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6869:             my ($start,$end) = split(/\./,$env{$key});
                   6870:             if (($end!=0) && ($end<$now)) { next; }
                   6871:             if (($start!=0) && ($start>$now)) { next; }
                   6872:             if ($1 eq $cdom && $2 eq $cnum) {
                   6873:                 $groups{$3} = $env{$key} ;
                   6874:             }
                   6875:         }
                   6876:     }
                   6877:     return %groups;
                   6878: }
                   6879: 
1.683     raeburn  6880: sub get_group_membership {
                   6881:     my ($cdom,$cnum,$group) = @_;
                   6882:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6883: }
                   6884: 
                   6885: sub get_users_groups {
                   6886:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6887:     my @usersgroups;
1.683     raeburn  6888:     my $cachetime=1800;
                   6889: 
                   6890:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6891:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6892:     if (defined($cached)) {
1.734     albertel 6893:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6894:     } else {  
                   6895:         $grouplist = '';
1.816     raeburn  6896:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6897:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6898:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6899:         my $access_end = $env{'course.'.$courseid.
                   6900:                               '.default_enrollment_end_date'};
                   6901:         my $now = time;
                   6902:         foreach my $key (keys(%roleshash)) {
                   6903:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6904:                 my $group = $1;
                   6905:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6906:                     my $start = $2;
                   6907:                     my $end = $1;
                   6908:                     if ($start == -1) { next; } # deleted from group
                   6909:                     if (($start!=0) && ($start>$now)) { next; }
                   6910:                     if (($end!=0) && ($end<$now)) {
                   6911:                         if ($access_end && $access_end < $now) {
                   6912:                             if ($access_end - $end < 86400) {
                   6913:                                 push(@usersgroups,$group);
1.733     raeburn  6914:                             }
                   6915:                         }
1.817     raeburn  6916:                         next;
1.733     raeburn  6917:                     }
1.817     raeburn  6918:                     push(@usersgroups,$group);
1.683     raeburn  6919:                 }
                   6920:             }
                   6921:         }
1.817     raeburn  6922:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6923:         $grouplist = join(':',@usersgroups);
                   6924:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6925:     }
1.733     raeburn  6926:     return @usersgroups;
1.683     raeburn  6927: }
                   6928: 
                   6929: sub devalidate_getgroups_cache {
                   6930:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6931:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6932: 
1.683     raeburn  6933:     my $hashid="$udom:$uname:$courseid";
                   6934:     &devalidate_cache_new('getgroups',$hashid);
                   6935: }
                   6936: 
1.12      www      6937: # ------------------------------------------------------------------ Plain Text
                   6938: 
                   6939: sub plaintext {
1.988     raeburn  6940:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6941:     if ($short =~ m{^cr/}) {
1.758     albertel 6942: 	return (split('/',$short))[-1];
                   6943:     }
1.742     raeburn  6944:     if (!defined($cid)) {
                   6945:         $cid = $env{'request.course.id'};
                   6946:     }
                   6947:     my %rolenames = (
1.1008    raeburn  6948:                       Course    => 'std',
                   6949:                       Community => 'alt1',
1.742     raeburn  6950:                     );
1.1037    raeburn  6951:     if ($cid ne '') {
                   6952:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6953:             unless ($forcedefault) {
                   6954:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6955:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6956:                 return &Apache::lonlocal::mt($roletext);
                   6957:             }
                   6958:         }
                   6959:     }
                   6960:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6961:         (defined($rolenames{$type})) && 
                   6962:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6963:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6964:     } elsif ($cid ne '') {
                   6965:         my $crstype = $env{'course.'.$cid.'.type'};
                   6966:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6967:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   6968:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   6969:         }
1.742     raeburn  6970:     }
1.1037    raeburn  6971:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      6972: }
                   6973: 
                   6974: # ----------------------------------------------------------------- Assign Role
                   6975: 
                   6976: sub assignrole {
1.957     raeburn  6977:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   6978:         $context)=@_;
1.21      www      6979:     my $mrole;
                   6980:     if ($role =~ /^cr\//) {
1.393     www      6981:         my $cwosec=$url;
1.811     albertel 6982:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      6983: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  6984:            my $refused = 1;
                   6985:            if ($context eq 'requestcourses') {
                   6986:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   6987:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   6988:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   6989:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   6990:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   6991:                            if ($crsenv{'internal.courseowner'} eq
                   6992:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   6993:                                $refused = '';
                   6994:                            }
                   6995:                        }
                   6996:                    }
                   6997:                }
                   6998:            }
                   6999:            if ($refused) {
                   7000:                &logthis('Refused custom assignrole: '.
                   7001:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7002:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7003:                return 'refused';
                   7004:            }
1.104     www      7005:         }
1.21      www      7006:         $mrole='cr';
1.678     raeburn  7007:     } elsif ($role =~ /^gr\//) {
                   7008:         my $cwogrp=$url;
1.811     albertel 7009:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7010:         unless (&allowed('mdg',$cwogrp)) {
                   7011:             &logthis('Refused group assignrole: '.
                   7012:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7013:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7014:             return 'refused';
                   7015:         }
                   7016:         $mrole='gr';
1.21      www      7017:     } else {
1.82      www      7018:         my $cwosec=$url;
1.811     albertel 7019:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7020:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7021:             my $refused;
                   7022:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7023:                 if (!(&allowed('c'.$role,$url))) {
                   7024:                     $refused = 1;
                   7025:                 }
                   7026:             } else {
                   7027:                 $refused = 1;
                   7028:             }
1.947     raeburn  7029:             if ($refused) {
1.1045    raeburn  7030:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7031:                 if (!$selfenroll && $context eq 'course') {
                   7032:                     my %crsenv;
                   7033:                     if ($role eq 'cc' || $role eq 'co') {
                   7034:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7035:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7036:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7037:                                 if ($crsenv{'internal.courseowner'} eq 
                   7038:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7039:                                     $refused = '';
                   7040:                                 }
                   7041:                             }
                   7042:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7043:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7044:                                 if ($crsenv{'internal.courseowner'} eq 
                   7045:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7046:                                     $refused = '';
                   7047:                                 }
                   7048:                             }
                   7049:                         }
                   7050:                     }
                   7051:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7052:                     $refused = '';
1.1017    raeburn  7053:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7054:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7055:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7056:                         my $wrongcc;
                   7057:                         if ($cnum =~ /^$match_community$/) {
                   7058:                             $wrongcc = 1 if ($role eq 'cc');
                   7059:                         } else {
                   7060:                             $wrongcc = 1 if ($role eq 'co');
                   7061:                         }
                   7062:                         unless ($wrongcc) {
                   7063:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7064:                             if ($crsenv{'internal.courseowner'} eq 
                   7065:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7066:                                 $refused = '';
                   7067:                             }
1.1017    raeburn  7068:                         }
                   7069:                     }
                   7070:                 }
                   7071:                 if ($refused) {
1.947     raeburn  7072:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7073:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7074: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7075:                     return 'refused';
                   7076:                 }
1.932     raeburn  7077:             }
1.1131  ! raeburn  7078:         } elsif ($role eq 'au') {
        !          7079:             if ($url ne '/'.$udom.'/') {
        !          7080:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
        !          7081:                          ' to assign author role for '.$uname.':'.$udom.
        !          7082:                          ' in domain: '.$url.' refused (wrong domain).');
        !          7083:                 return 'refused';
        !          7084:             }
1.104     www      7085:         }
1.21      www      7086:         $mrole=$role;
                   7087:     }
1.620     albertel 7088:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7089:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7090:     if ($end) { $command.='_'.$end; }
1.21      www      7091:     if ($start) {
                   7092: 	if ($end) { 
1.81      www      7093:            $command.='_'.$start; 
1.21      www      7094:         } else {
1.81      www      7095:            $command.='_0_'.$start;
1.21      www      7096:         }
                   7097:     }
1.739     raeburn  7098:     my $origstart = $start;
                   7099:     my $origend = $end;
1.957     raeburn  7100:     my $delflag;
1.357     www      7101: # actually delete
                   7102:     if ($deleteflag) {
1.373     www      7103: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7104: # modify command to delete the role
1.620     albertel 7105:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7106:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7107: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7108: # set start and finish to negative values for userrolelog
                   7109:            $start=-1;
                   7110:            $end=-1;
1.957     raeburn  7111:            $delflag = 1;
1.357     www      7112:         }
                   7113:     }
                   7114: # send command
1.349     www      7115:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7116: # log new user role if status is ok
1.349     www      7117:     if ($answer eq 'ok') {
1.663     raeburn  7118: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7119: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7120:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7121:         unless ($role =~ /^gr/) {
                   7122:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7123:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7124:         }
1.1053    raeburn  7125:         if ($role eq 'cc') {
                   7126:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7127:         }
1.349     www      7128:     }
                   7129:     return $answer;
1.169     harris41 7130: }
                   7131: 
1.1053    raeburn  7132: sub autoupdate_coowners {
                   7133:     my ($url,$end,$start,$uname,$udom) = @_;
                   7134:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7135:     if (($cdom ne '') && ($cnum ne '')) {
                   7136:         my $now = time;
                   7137:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7138:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7139:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7140:             my $instcode = $coursehash{'internal.coursecode'};
                   7141:             if ($instcode ne '') {
1.1056    raeburn  7142:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7143:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7144:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7145:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7146:                         if ($result eq 'valid') {
                   7147:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7148:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7149:                                     push(@newcoowners,$coowner);
                   7150:                                 }
                   7151:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7152:                                     push(@newcoowners,$uname.':'.$udom);
                   7153:                                 }
                   7154:                                 @newcoowners = sort(@newcoowners);
                   7155:                             } else {
                   7156:                                 push(@newcoowners,$uname.':'.$udom);
                   7157:                             }
                   7158:                         } else {
                   7159:                             if ($coursehash{'internal.co-owners'}) {
                   7160:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7161:                                     unless ($coowner eq $uname.':'.$udom) {
                   7162:                                         push(@newcoowners,$coowner);
                   7163:                                     }
                   7164:                                 }
                   7165:                                 unless (@newcoowners > 0) {
                   7166:                                     $delcoowners = 1;
                   7167:                                     $coowners = '';
                   7168:                                 }
                   7169:                             }
                   7170:                         }
                   7171:                         if (@newcoowners || $delcoowners) {
                   7172:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7173:                                             $delcoowners,@newcoowners);
                   7174:                         }
                   7175:                     }
                   7176:                 }
                   7177:             }
                   7178:         }
                   7179:     }
                   7180: }
                   7181: 
                   7182: sub store_coowners {
                   7183:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7184:     my $cid = $cdom.'_'.$cnum;
                   7185:     my ($coowners,$delresult,$putresult);
                   7186:     if (@newcoowners) {
                   7187:         $coowners = join(',',@newcoowners);
                   7188:         my %coownershash = (
                   7189:                             'internal.co-owners' => $coowners,
                   7190:                            );
                   7191:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7192:         if ($putresult eq 'ok') {
                   7193:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7194:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7195:             }
                   7196:         }
                   7197:     }
                   7198:     if ($delcoowners) {
                   7199:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7200:         if ($delresult eq 'ok') {
                   7201:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7202:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7203:             }
                   7204:         }
                   7205:     }
                   7206:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7207:         my %crsinfo =
                   7208:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7209:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7210:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7211:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7212:         }
                   7213:     }
                   7214: }
                   7215: 
1.169     harris41 7216: # -------------------------------------------------- Modify user authentication
1.197     www      7217: # Overrides without validation
                   7218: 
1.169     harris41 7219: sub modifyuserauth {
                   7220:     my ($udom,$uname,$umode,$upass)=@_;
                   7221:     my $uhome=&homeserver($uname,$udom);
1.197     www      7222:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7223:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7224:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7225:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7226:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7227: 		     &escape($upass),$uhome);
1.620     albertel 7228:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7229:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7230:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7231:     &log($udom,,$uname,$uhome,
1.620     albertel 7232:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7233:                                      $env{'user.name'}.', '.$umode.
1.197     www      7234:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7235:     unless ($reply eq 'ok') {
1.197     www      7236:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7237: 	return 'error: '.$reply;
                   7238:     }   
1.170     harris41 7239:     return 'ok';
1.80      www      7240: }
                   7241: 
1.81      www      7242: # --------------------------------------------------------------- Modify a user
1.80      www      7243: 
1.81      www      7244: sub modifyuser {
1.206     matthew  7245:     my ($udom,    $uname, $uid,
                   7246:         $umode,   $upass, $first,
                   7247:         $middle,  $last,  $gene,
1.1058    raeburn  7248:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7249:     $udom= &LONCAPA::clean_domain($udom);
                   7250:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7251:     my $showcandelete = 'none';
                   7252:     if (ref($candelete) eq 'ARRAY') {
                   7253:         if (@{$candelete} > 0) {
                   7254:             $showcandelete = join(', ',@{$candelete});
                   7255:         }
                   7256:     }
1.81      www      7257:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7258:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7259: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7260:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7261:                                      ' desiredhome not specified'). 
1.620     albertel 7262:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7263:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7264:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7265:     my $newuser;
                   7266:     if ($uhome eq 'no_host') {
                   7267:         $newuser = 1;
                   7268:     }
1.80      www      7269: # ----------------------------------------------------------------- Create User
1.406     albertel 7270:     if (($uhome eq 'no_host') && 
                   7271: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7272:         my $unhome='';
1.844     albertel 7273:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7274:             $unhome = $desiredhome;
1.620     albertel 7275: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7276: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7277:         } else { # load balancing routine for determining $unhome
1.81      www      7278:             my $loadm=10000000;
1.841     albertel 7279: 	    my %servers = &get_servers($udom,'library');
                   7280: 	    foreach my $tryserver (keys(%servers)) {
                   7281: 		my $answer=reply('load',$tryserver);
                   7282: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7283: 		    $loadm=$answer;
                   7284: 		    $unhome=$tryserver;
                   7285: 		}
1.80      www      7286: 	    }
                   7287:         }
                   7288:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7289: 	    return 'error: unable to find a home server for '.$uname.
                   7290:                    ' in domain '.$udom;
1.80      www      7291:         }
                   7292:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7293:                          &escape($upass),$unhome);
                   7294: 	unless ($reply eq 'ok') {
                   7295:             return 'error: '.$reply;
                   7296:         }   
1.230     stredwic 7297:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7298:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7299: 	    return 'error: unable verify users home machine.';
1.80      www      7300:         }
1.209     matthew  7301:     }   # End of creation of new user
1.80      www      7302: # ---------------------------------------------------------------------- Add ID
                   7303:     if ($uid) {
                   7304:        $uid=~tr/A-Z/a-z/;
                   7305:        my %uidhash=&idrget($udom,$uname);
1.196     www      7306:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7307:          && (!$forceid)) {
1.80      www      7308: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7309: 	      return 'error: user id "'.$uid.'" does not match '.
                   7310:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7311:           }
                   7312:        } else {
                   7313: 	  &idput($udom,($uname => $uid));
                   7314:        }
                   7315:     }
                   7316: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7317:     my @tmp=&get('environment',
1.899     raeburn  7318: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7319:                     'permanentemail','inststatus'],
1.134     albertel 7320: 		   $udom,$uname);
1.1075    raeburn  7321:     my (%names,%oldnames);
1.313     matthew  7322:     if ($tmp[0] =~ m/^error:.*/) { 
                   7323:         %names=(); 
                   7324:     } else {
                   7325:         %names = @tmp;
1.1075    raeburn  7326:         %oldnames = %names;
1.313     matthew  7327:     }
1.388     www      7328: #
1.1058    raeburn  7329: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7330: # of users did not contain them), do not overwrite existing values
                   7331: # unless field is in $candelete array ref.  
                   7332: #
                   7333: 
                   7334:     my @fields = ('firstname','middlename','lastname','generation',
                   7335:                   'permanentemail','id');
                   7336:     my %newvalues;
                   7337:     if (ref($candelete) eq 'ARRAY') {
                   7338:         foreach my $field (@fields) {
                   7339:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7340:                 if ($field eq 'firstname') {
                   7341:                     $names{$field} = $first;
                   7342:                 } elsif ($field eq 'middlename') {
                   7343:                     $names{$field} = $middle;
                   7344:                 } elsif ($field eq 'lastname') {
                   7345:                     $names{$field} = $last;
                   7346:                 } elsif ($field eq 'generation') { 
                   7347:                     $names{$field} = $gene;
                   7348:                 } elsif ($field eq 'permanentemail') {
                   7349:                     $names{$field} = $email;
                   7350:                 } elsif ($field eq 'id') {
                   7351:                     $names{$field}  = $uid;
                   7352:                 }
                   7353:             }
                   7354:         }
                   7355:     }
1.388     www      7356:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7357:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7358:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7359:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7360:     if ($email) {
                   7361:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7362:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7363:     }
1.899     raeburn  7364:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7365:     if (defined($inststatus)) {
                   7366:         $names{'inststatus'} = '';
                   7367:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7368:         if (ref($usertypes) eq 'HASH') {
                   7369:             my @okstatuses; 
                   7370:             foreach my $item (split(/:/,$inststatus)) {
                   7371:                 if (defined($usertypes->{$item})) {
                   7372:                     push(@okstatuses,$item);  
                   7373:                 }
                   7374:             }
                   7375:             if (@okstatuses) {
                   7376:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7377:             }
                   7378:         }
                   7379:     }
1.1075    raeburn  7380:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7381:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7382:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7383:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7384:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7385:     } else {
                   7386:         $logmsg .= ' during self creation';
                   7387:     }
1.1075    raeburn  7388:     my $changed;
                   7389:     if ($newuser) {
                   7390:         $changed = 1;
                   7391:     } else {
                   7392:         foreach my $field (@fields) {
                   7393:             if ($names{$field} ne $oldnames{$field}) {
                   7394:                 $changed = 1;
                   7395:                 last;
                   7396:             }
                   7397:         }
                   7398:     }
                   7399:     unless ($changed) {
                   7400:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7401:         &logthis($logmsg);
                   7402:         return 'ok';
                   7403:     }
                   7404:     my $reply = &put('environment', \%names, $udom,$uname);
                   7405:     if ($reply ne 'ok') { 
                   7406:         return 'error: '.$reply;
                   7407:     }
1.1087    raeburn  7408:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7409:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7410:     }
1.1075    raeburn  7411:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7412:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7413:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7414:     &logthis($logmsg);
1.134     albertel 7415:     return 'ok';
1.80      www      7416: }
                   7417: 
1.81      www      7418: # -------------------------------------------------------------- Modify student
1.80      www      7419: 
1.81      www      7420: sub modifystudent {
                   7421:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7422:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7423:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7424:     if (!$cid) {
1.620     albertel 7425: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7426: 	    return 'not_in_class';
                   7427: 	}
1.80      www      7428:     }
                   7429: # --------------------------------------------------------------- Make the user
1.81      www      7430:     my $reply=&modifyuser
1.209     matthew  7431: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7432:          $desiredhome,$email,$inststatus);
1.80      www      7433:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7434:     # This will cause &modify_student_enrollment to get the uid from the
                   7435:     # students environment
                   7436:     $uid = undef if (!$forceid);
1.455     albertel 7437:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7438: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7439:     return $reply;
                   7440: }
                   7441: 
                   7442: sub modify_student_enrollment {
1.957     raeburn  7443:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7444:     my ($cdom,$cnum,$chome);
                   7445:     if (!$cid) {
1.620     albertel 7446: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7447: 	    return 'not_in_class';
                   7448: 	}
1.620     albertel 7449: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7450: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7451:     } else {
                   7452: 	($cdom,$cnum)=split(/_/,$cid);
                   7453:     }
1.620     albertel 7454:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7455:     if (!$chome) {
1.457     raeburn  7456: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7457:     }
1.455     albertel 7458:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7459:     # Make sure the user exists
1.81      www      7460:     my $uhome=&homeserver($uname,$udom);
                   7461:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7462: 	return 'error: no such user';
                   7463:     }
1.297     matthew  7464:     # Get student data if we were not given enough information
                   7465:     if (!defined($first)  || $first  eq '' || 
                   7466:         !defined($last)   || $last   eq '' || 
                   7467:         !defined($uid)    || $uid    eq '' || 
                   7468:         !defined($middle) || $middle eq '' || 
                   7469:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7470:         # They did not supply us with enough data to enroll the student, so
                   7471:         # we need to pick up more information.
1.297     matthew  7472:         my %tmp = &get('environment',
1.294     matthew  7473:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7474:                        ,$udom,$uname);
                   7475: 
1.800     albertel 7476:         #foreach my $key (keys(%tmp)) {
                   7477:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7478:         #}
1.294     matthew  7479:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7480:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7481:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7482:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7483:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7484:     }
1.556     albertel 7485:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7486:     my $reply=cput('classlist',
                   7487: 		   {"$uname:$udom" => 
1.515     raeburn  7488: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7489: 		   $cdom,$cnum);
1.81      www      7490:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7491: 	return 'error: '.$reply;
1.652     albertel 7492:     } else {
                   7493: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7494:     }
1.297     matthew  7495:     # Add student role to user
1.83      www      7496:     my $uurl='/'.$cid;
1.81      www      7497:     $uurl=~s/\_/\//g;
                   7498:     if ($usec) {
                   7499: 	$uurl.='/'.$usec;
                   7500:     }
1.957     raeburn  7501:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7502: }
                   7503: 
1.556     albertel 7504: sub format_name {
                   7505:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7506:     my $name;
                   7507:     if ($first ne 'lastname') {
                   7508: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7509:     } else {
                   7510: 	if ($lastname=~/\S/) {
                   7511: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7512: 	    $name=~s/\s+,/,/;
                   7513: 	} else {
                   7514: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7515: 	}
                   7516:     }
                   7517:     $name=~s/^\s+//;
                   7518:     $name=~s/\s+$//;
                   7519:     $name=~s/\s+/ /g;
                   7520:     return $name;
                   7521: }
                   7522: 
1.84      www      7523: # ------------------------------------------------- Write to course preferences
                   7524: 
                   7525: sub writecoursepref {
                   7526:     my ($courseid,%prefs)=@_;
                   7527:     $courseid=~s/^\///;
                   7528:     $courseid=~s/\_/\//g;
                   7529:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7530:     my $chome=homeserver($cnum,$cdomain);
                   7531:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7532: 	return 'error: no such course';
                   7533:     }
                   7534:     my $cstring='';
1.800     albertel 7535:     foreach my $pref (keys(%prefs)) {
                   7536: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7537:     }
1.84      www      7538:     $cstring=~s/\&$//;
                   7539:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7540: }
                   7541: 
                   7542: # ---------------------------------------------------------- Make/modify course
                   7543: 
                   7544: sub createcourse {
1.741     raeburn  7545:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7546:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7547:     $url=&declutter($url);
                   7548:     my $cid='';
1.1028    raeburn  7549:     if ($context eq 'requestcourses') {
                   7550:         my $can_create = 0;
                   7551:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7552:         if ($udom eq $ownerdom) {
                   7553:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7554:                                   $context)) {
                   7555:                 $can_create = 1;
                   7556:             }
                   7557:         } else {
                   7558:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7559:                                            $category);
                   7560:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7561:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7562:                 if (@curr > 0) {
                   7563:                     my @options = qw(approval validate autolimit);
                   7564:                     my $optregex = join('|',@options);
                   7565:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7566:                         $can_create = 1;
                   7567:                     }
                   7568:                 }
                   7569:             }
                   7570:         }
                   7571:         if ($can_create) {
                   7572:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7573:                 unless (&allowed('ccc',$udom)) {
                   7574:                     return 'refused'; 
                   7575:                 }
1.1017    raeburn  7576:             }
                   7577:         } else {
                   7578:             return 'refused';
                   7579:         }
1.1028    raeburn  7580:     } elsif (!&allowed('ccc',$udom)) {
                   7581:         return 'refused';
1.84      www      7582:     }
1.1011    raeburn  7583: # --------------------------------------------------------------- Get Unique ID
                   7584:     my $uname;
                   7585:     if ($cnum =~ /^$match_courseid$/) {
                   7586:         my $chome=&homeserver($cnum,$udom,'true');
                   7587:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7588:             $uname = $cnum;
                   7589:         } else {
1.1038    raeburn  7590:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7591:         }
                   7592:     } else {
1.1038    raeburn  7593:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7594:     }
                   7595:     return $uname if ($uname =~ /^error/);
                   7596: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7597:     if (!defined($course_server)) {
                   7598:         if (defined(&domain($udom,'primary'))) {
                   7599:             $course_server = &domain($udom,'primary');
                   7600:         } else {
                   7601:             $course_server = $env{'user.home'}; 
                   7602:         }
                   7603:     }
                   7604:     my %host_servers =
                   7605:         &Apache::lonnet::get_servers($udom,'library');
                   7606:     unless ($host_servers{$course_server}) {
                   7607:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7608:     }
1.84      www      7609: # ------------------------------------------------------------- Make the course
                   7610:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7611:                       $course_server);
1.84      www      7612:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7613:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7614:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7615: 	return 'error: no such course';
                   7616:     }
1.271     www      7617: # ----------------------------------------------------------------- Course made
1.516     raeburn  7618: # log existence
1.1029    raeburn  7619:     my $now = time;
1.918     raeburn  7620:     my $newcourse = {
                   7621:                     $udom.'_'.$uname => {
1.921     raeburn  7622:                                      description => $description,
                   7623:                                      inst_code   => $inst_code,
                   7624:                                      owner       => $course_owner,
                   7625:                                      type        => $crstype,
1.1029    raeburn  7626:                                      creator     => $env{'user.name'}.':'.
                   7627:                                                     $env{'user.domain'},
                   7628:                                      created     => $now,
                   7629:                                      context     => $context,
1.918     raeburn  7630:                                                 },
                   7631:                     };
1.921     raeburn  7632:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7633: # set toplevel url
1.271     www      7634:     my $topurl=$url;
                   7635:     unless ($nonstandard) {
                   7636: # ------------------------------------------ For standard courses, make top url
                   7637:         my $mapurl=&clutter($url);
1.278     www      7638:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7639:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7640: <map>
                   7641: <resource id="1" type="start"></resource>
                   7642: <resource id="2" src="$mapurl"></resource>
                   7643: <resource id="3" type="finish"></resource>
                   7644: <link index="1" from="1" to="2"></link>
                   7645: <link index="2" from="2" to="3"></link>
                   7646: </map>
                   7647: ENDINITMAP
                   7648:         $topurl=&declutter(
1.638     albertel 7649:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7650:                           );
                   7651:     }
                   7652: # ----------------------------------------------------------- Write preferences
1.84      www      7653:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7654:                      ('description'              => $description,
                   7655:                       'url'                      => $topurl,
                   7656:                       'internal.creator'         => $env{'user.name'}.':'.
                   7657:                                                     $env{'user.domain'},
                   7658:                       'internal.created'         => $now,
                   7659:                       'internal.creationcontext' => $context)
                   7660:                     );
1.84      www      7661:     return '/'.$udom.'/'.$uname;
                   7662: }
                   7663: 
1.1011    raeburn  7664: # ------------------------------------------------------------------- Create ID
                   7665: sub generate_coursenum {
1.1038    raeburn  7666:     my ($udom,$crstype) = @_;
1.1011    raeburn  7667:     my $domdesc = &domain($udom);
                   7668:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7669:     my $first;
                   7670:     if ($crstype eq 'Community') {
                   7671:         $first = '0';
                   7672:     } else {
                   7673:         $first = int(1+rand(9)); 
                   7674:     } 
                   7675:     my $uname=$first.
1.1011    raeburn  7676:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7677:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7678:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7679: # ----------------------------------------------- Make sure that does not exist
                   7680:     my $uhome=&homeserver($uname,$udom,'true');
                   7681:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7682:         if ($crstype eq 'Community') {
                   7683:             $first = '0';
                   7684:         } else {
                   7685:             $first = int(1+rand(9));
                   7686:         }
                   7687:         $uname=$first.
1.1011    raeburn  7688:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7689:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7690:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7691:         $uhome=&homeserver($uname,$udom,'true');
                   7692:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7693:             return 'error: unable to generate unique course-ID';
                   7694:         }
                   7695:     }
                   7696:     return $uname;
                   7697: }
                   7698: 
1.813     albertel 7699: sub is_course {
                   7700:     my ($cdom,$cnum) = @_;
                   7701:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7702: 				undef,'.');
1.813     albertel 7703:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7704:         return 1;
                   7705:     }
                   7706:     return 0;
                   7707: }
                   7708: 
1.1015    raeburn  7709: sub store_userdata {
                   7710:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7711:     my $result;
1.1016    raeburn  7712:     if ($datakey ne '') {
1.1013    raeburn  7713:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7714:             if ($udom eq '' || $uname eq '') {
                   7715:                 $udom = $env{'user.domain'};
                   7716:                 $uname = $env{'user.name'};
                   7717:             }
                   7718:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7719:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7720:                 $result = 'error: no_host';
                   7721:             } else {
                   7722:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7723:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7724: 
                   7725:                 my $namevalue='';
                   7726:                 foreach my $key (keys(%{$storehash})) {
                   7727:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7728:                 }
                   7729:                 $namevalue=~s/\&$//;
1.1105    raeburn  7730:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7731:                                   $namevalue,$uhome);
1.1013    raeburn  7732:             }
                   7733:         } else {
                   7734:             $result = 'error: data to store was not a hash reference'; 
                   7735:         }
                   7736:     } else {
                   7737:         $result= 'error: invalid requestkey'; 
                   7738:     }
                   7739:     return $result;
                   7740: }
                   7741: 
1.21      www      7742: # ---------------------------------------------------------- Assign Custom Role
                   7743: 
                   7744: sub assigncustomrole {
1.957     raeburn  7745:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7746:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7747:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7748: }
                   7749: 
                   7750: # ----------------------------------------------------------------- Revoke Role
                   7751: 
                   7752: sub revokerole {
1.957     raeburn  7753:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7754:     my $now=time;
1.965     raeburn  7755:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7756: }
                   7757: 
                   7758: # ---------------------------------------------------------- Revoke Custom Role
                   7759: 
                   7760: sub revokecustomrole {
1.957     raeburn  7761:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7762:     my $now=time;
1.357     www      7763:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7764:            $deleteflag,$selfenroll,$context);
1.17      www      7765: }
                   7766: 
1.533     banghart 7767: # ------------------------------------------------------------ Disk usage
1.535     albertel 7768: sub diskusage {
1.955     raeburn  7769:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7770:     $directorypath =~ s/\/$//;
                   7771:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7772:                        .&escape($getpropath).':'.&escape($uname).':'
                   7773:                        .&escape($udom),homeserver($uname,$udom));
                   7774:     if ($listing eq 'unknown_cmd') {
                   7775:         if ($getpropath) {
                   7776:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7777:         }
                   7778:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7779:     }
1.514     albertel 7780:     return $listing;
1.512     banghart 7781: }
                   7782: 
1.566     banghart 7783: sub is_locked {
1.1096    raeburn  7784:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7785:     my @check;
                   7786:     my $is_locked;
1.1093    raeburn  7787:     push (@check,$file_name);
1.613     albertel 7788:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7789: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7790:     my ($tmp)=keys(%locked);
                   7791:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7792:     
1.566     banghart 7793:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7794:         $is_locked = 'false';
                   7795:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7796:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7797:                $is_locked = 'true';
1.1096    raeburn  7798:                if (ref($which) eq 'ARRAY') {
                   7799:                    push(@{$which},$entry);
                   7800:                } else {
                   7801:                    last;
                   7802:                }
1.745     raeburn  7803:            }
                   7804:        }
1.566     banghart 7805:     } else {
                   7806:         $is_locked = 'false';
                   7807:     }
1.1093    raeburn  7808:     return $is_locked;
1.566     banghart 7809: }
                   7810: 
1.759     albertel 7811: sub declutter_portfile {
                   7812:     my ($file) = @_;
1.833     albertel 7813:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7814:     return $file;
                   7815: }
                   7816: 
1.559     banghart 7817: # ------------------------------------------------------------- Mark as Read Only
                   7818: 
                   7819: sub mark_as_readonly {
                   7820:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7821:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7822:     my ($tmp)=keys(%current_permissions);
                   7823:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7824:     foreach my $file (@{$files}) {
1.759     albertel 7825: 	$file = &declutter_portfile($file);
1.561     banghart 7826:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7827:     }
1.613     albertel 7828:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7829:     return;
                   7830: }
                   7831: 
1.572     banghart 7832: # ------------------------------------------------------------Save Selected Files
                   7833: 
                   7834: sub save_selected_files {
                   7835:     my ($user, $path, @files) = @_;
                   7836:     my $filename = $user."savedfiles";
1.573     banghart 7837:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7838:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7839:     foreach my $file (@files) {
1.620     albertel 7840:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7841:     }
                   7842:     foreach my $file (@other_files) {
1.574     banghart 7843:         print (OUT $file."\n");
1.572     banghart 7844:     }
1.574     banghart 7845:     close (OUT);
1.572     banghart 7846:     return 'ok';
                   7847: }
                   7848: 
1.574     banghart 7849: sub clear_selected_files {
                   7850:     my ($user) = @_;
                   7851:     my $filename = $user."savedfiles";
1.1117    foxr     7852:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7853:     print (OUT undef);
                   7854:     close (OUT);
                   7855:     return ("ok");    
                   7856: }
                   7857: 
1.572     banghart 7858: sub files_in_path {
                   7859:     my ($user, $path) = @_;
                   7860:     my $filename = $user."savedfiles";
                   7861:     my %return_files;
1.1117    foxr     7862:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7863:     while (my $line_in = <IN>) {
1.574     banghart 7864:         chomp ($line_in);
                   7865:         my @paths_and_file = split (m!/!, $line_in);
                   7866:         my $file_part = pop (@paths_and_file);
                   7867:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7868:         $path_part.='/';
                   7869:         my $path_and_file = $path_part.$file_part;
                   7870:         if ($path_part eq $path) {
                   7871:             $return_files{$file_part}= 'selected';
                   7872:         }
                   7873:     }
1.574     banghart 7874:     close (IN);
                   7875:     return (\%return_files);
1.572     banghart 7876: }
                   7877: 
                   7878: # called in portfolio select mode, to show files selected NOT in current directory
                   7879: sub files_not_in_path {
                   7880:     my ($user, $path) = @_;
                   7881:     my $filename = $user."savedfiles";
                   7882:     my @return_files;
                   7883:     my $path_part;
1.1117    foxr     7884:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7885:     while (my $line = <IN>) {
1.572     banghart 7886:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7887:         my @paths_and_file = split(m|/|, $line);
                   7888:         my $file_part = pop(@paths_and_file);
                   7889:         chomp($file_part);
                   7890:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7891:         $path_part .= '/';
                   7892:         my $path_and_file = $path_part.$file_part;
                   7893:         if ($path_part ne $path) {
1.800     albertel 7894:             push(@return_files, ($path_and_file));
1.572     banghart 7895:         }
                   7896:     }
1.800     albertel 7897:     close(OUT);
1.574     banghart 7898:     return (@return_files);
1.572     banghart 7899: }
                   7900: 
1.745     raeburn  7901: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7902: 
1.745     raeburn  7903: sub get_portfile_permissions {
                   7904:     my ($domain,$user) = @_;
1.613     albertel 7905:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7906:     my ($tmp)=keys(%current_permissions);
                   7907:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7908:     return \%current_permissions;
                   7909: }
                   7910: 
                   7911: #---------------------------------------------Get portfolio file access controls
                   7912: 
1.749     raeburn  7913: sub get_access_controls {
1.745     raeburn  7914:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7915:     my %access;
                   7916:     my $real_file = $file;
                   7917:     $file =~ s/\.meta$//;
1.745     raeburn  7918:     if (defined($file)) {
1.749     raeburn  7919:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7920:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7921:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7922:             }
                   7923:         }
1.745     raeburn  7924:     } else {
1.749     raeburn  7925:         foreach my $key (keys(%{$current_permissions})) {
                   7926:             if ($key =~ /\0accesscontrol$/) {
                   7927:                 if (defined($group)) {
                   7928:                     if ($key !~ m-^\Q$group\E/-) {
                   7929:                         next;
                   7930:                     }
                   7931:                 }
                   7932:                 my ($fullpath) = split(/\0/,$key);
                   7933:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7934:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7935:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7936:                     }
                   7937:                 }
                   7938:             }
                   7939:         }
                   7940:     }
                   7941:     return %access;
                   7942: }
                   7943: 
                   7944: sub modify_access_controls {
                   7945:     my ($file_name,$changes,$domain,$user)=@_;
                   7946:     my ($outcome,$deloutcome);
                   7947:     my %store_permissions;
                   7948:     my %new_values;
                   7949:     my %new_control;
                   7950:     my %translation;
                   7951:     my @deletions = ();
                   7952:     my $now = time;
                   7953:     if (exists($$changes{'activate'})) {
                   7954:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7955:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7956:             my $numnew = scalar(@newitems);
                   7957:             for (my $i=0; $i<$numnew; $i++) {
                   7958:                 my $newkey = $newitems[$i];
                   7959:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7960:                 if ($newkey =~ /^\d+:/) { 
                   7961:                     $newkey =~ s/^(\d+)/$newid/;
                   7962:                     $translation{$1} = $newid;
                   7963:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7964:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7965:                     $translation{$1} = $newid;
                   7966:                 }
1.749     raeburn  7967:                 $new_values{$file_name."\0".$newkey} = 
                   7968:                                           $$changes{'activate'}{$newitems[$i]};
                   7969:                 $new_control{$newkey} = $now;
                   7970:             }
                   7971:         }
                   7972:     }
                   7973:     my %todelete;
                   7974:     my %changed_items;
                   7975:     foreach my $action ('delete','update') {
                   7976:         if (exists($$changes{$action})) {
                   7977:             if (ref($$changes{$action}) eq 'HASH') {
                   7978:                 foreach my $key (keys(%{$$changes{$action}})) {
                   7979:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   7980:                     if ($action eq 'delete') { 
                   7981:                         $todelete{$itemnum} = 1;
                   7982:                     } else {
                   7983:                         $changed_items{$itemnum} = $key;
                   7984:                     }
                   7985:                 }
1.745     raeburn  7986:             }
                   7987:         }
1.749     raeburn  7988:     }
                   7989:     # get lock on access controls for file.
                   7990:     my $lockhash = {
                   7991:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   7992:                                                        ':'.$env{'user.domain'},
                   7993:                    }; 
                   7994:     my $tries = 0;
                   7995:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   7996:    
                   7997:     while (($gotlock ne 'ok') && $tries <3) {
                   7998:         $tries ++;
                   7999:         sleep 1;
                   8000:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8001:     }
                   8002:     if ($gotlock eq 'ok') {
                   8003:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8004:         my ($tmp)=keys(%curr_permissions);
                   8005:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8006:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8007:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8008:             if (ref($curr_controls) eq 'HASH') {
                   8009:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8010:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8011:                     if (defined($todelete{$itemnum})) {
                   8012:                         push(@deletions,$file_name."\0".$control_item);
                   8013:                     } else {
                   8014:                         if (defined($changed_items{$itemnum})) {
                   8015:                             $new_control{$changed_items{$itemnum}} = $now;
                   8016:                             push(@deletions,$file_name."\0".$control_item);
                   8017:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8018:                         } else {
                   8019:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8020:                         }
                   8021:                     }
1.745     raeburn  8022:                 }
                   8023:             }
                   8024:         }
1.970     raeburn  8025:         my ($group);
                   8026:         if (&is_course($domain,$user)) {
                   8027:             ($group,my $file) = split(/\//,$file_name,2);
                   8028:         }
1.749     raeburn  8029:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8030:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8031:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8032:         #  remove lock
                   8033:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8034:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8035:         my $sqlresult =
1.970     raeburn  8036:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8037:                                     $group);
1.749     raeburn  8038:     } else {
                   8039:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8040:     }
1.749     raeburn  8041:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8042: }
                   8043: 
1.827     raeburn  8044: sub make_public_indefinitely {
                   8045:     my ($requrl) = @_;
                   8046:     my $now = time;
                   8047:     my $action = 'activate';
                   8048:     my $aclnum = 0;
                   8049:     if (&is_portfolio_url($requrl)) {
                   8050:         my (undef,$udom,$unum,$file_name,$group) =
                   8051:             &parse_portfolio_url($requrl);
                   8052:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8053:         my %access_controls = &get_access_controls($current_perms,
                   8054:                                                    $group,$file_name);
                   8055:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8056:             my ($num,$scope,$end,$start) = 
                   8057:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8058:             if ($scope eq 'public') {
                   8059:                 if ($start <= $now && $end == 0) {
                   8060:                     $action = 'none';
                   8061:                 } else {
                   8062:                     $action = 'update';
                   8063:                     $aclnum = $num;
                   8064:                 }
                   8065:                 last;
                   8066:             }
                   8067:         }
                   8068:         if ($action eq 'none') {
                   8069:              return 'ok';
                   8070:         } else {
                   8071:             my %changes;
                   8072:             my $newend = 0;
                   8073:             my $newstart = $now;
                   8074:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8075:             $changes{$action}{$newkey} = {
                   8076:                 type => 'public',
                   8077:                 time => {
                   8078:                     start => $newstart,
                   8079:                     end   => $newend,
                   8080:                 },
                   8081:             };
                   8082:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8083:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8084:             return $outcome;
                   8085:         }
                   8086:     } else {
                   8087:         return 'invalid';
                   8088:     }
                   8089: }
                   8090: 
1.745     raeburn  8091: #------------------------------------------------------Get Marked as Read Only
                   8092: 
                   8093: sub get_marked_as_readonly {
                   8094:     my ($domain,$user,$what,$group) = @_;
                   8095:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8096:     my @readonly_files;
1.629     banghart 8097:     my $cmp1=$what;
                   8098:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8099:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8100:         if (defined($group)) {
                   8101:             if ($file_name !~ m-^\Q$group\E/-) {
                   8102:                 next;
                   8103:             }
                   8104:         }
1.561     banghart 8105:         if (ref($value) eq "ARRAY"){
                   8106:             foreach my $stored_what (@{$value}) {
1.629     banghart 8107:                 my $cmp2=$stored_what;
1.759     albertel 8108:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8109:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8110:                 }
1.629     banghart 8111:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8112:                     push(@readonly_files, $file_name);
1.745     raeburn  8113:                     last;
1.563     banghart 8114:                 } elsif (!defined($what)) {
                   8115:                     push(@readonly_files, $file_name);
1.745     raeburn  8116:                     last;
1.561     banghart 8117:                 }
                   8118:             }
1.745     raeburn  8119:         }
1.561     banghart 8120:     }
                   8121:     return @readonly_files;
                   8122: }
1.577     banghart 8123: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8124: 
1.577     banghart 8125: sub get_marked_as_readonly_hash {
1.745     raeburn  8126:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8127:     my %readonly_files;
1.745     raeburn  8128:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8129:         if (defined($group)) {
                   8130:             if ($file_name !~ m-^\Q$group\E/-) {
                   8131:                 next;
                   8132:             }
                   8133:         }
1.577     banghart 8134:         if (ref($value) eq "ARRAY"){
                   8135:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8136:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8137:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8138:                         if ($lock_descriptor eq 'graded') {
                   8139:                             $readonly_files{$file_name} = 'graded';
                   8140:                         } elsif ($lock_descriptor eq 'handback') {
                   8141:                             $readonly_files{$file_name} = 'handback';
                   8142:                         } else {
                   8143:                             if (!exists($readonly_files{$file_name})) {
                   8144:                                 $readonly_files{$file_name} = 'locked';
                   8145:                             }
                   8146:                         }
1.745     raeburn  8147:                     }
1.750     banghart 8148:                 } 
1.577     banghart 8149:             }
                   8150:         } 
                   8151:     }
                   8152:     return %readonly_files;
                   8153: }
1.559     banghart 8154: # ------------------------------------------------------------ Unmark as Read Only
                   8155: 
                   8156: sub unmark_as_readonly {
1.629     banghart 8157:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8158:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8159:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8160:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8161:     my $symb_crs = $what;
                   8162:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8163:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8164:     my ($tmp)=keys(%current_permissions);
                   8165:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8166:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8167:     foreach my $file (@readonly_files) {
1.759     albertel 8168: 	my $clean_file = &declutter_portfile($file);
                   8169: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8170: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8171:         my @new_locks;
                   8172:         my @del_keys;
                   8173:         if (ref($current_locks) eq "ARRAY"){
                   8174:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8175:                 my $compare=$locker;
1.749     raeburn  8176:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8177:                     $compare=join('',@{$locker});
1.746     raeburn  8178:                     if ($compare ne $symb_crs) {
                   8179:                         push(@new_locks, $locker);
                   8180:                     }
1.563     banghart 8181:                 }
                   8182:             }
1.650     albertel 8183:             if (scalar(@new_locks) > 0) {
1.563     banghart 8184:                 $current_permissions{$file} = \@new_locks;
                   8185:             } else {
                   8186:                 push(@del_keys, $file);
1.613     albertel 8187:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8188:                 delete($current_permissions{$file});
1.563     banghart 8189:             }
                   8190:         }
1.561     banghart 8191:     }
1.613     albertel 8192:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8193:     return;
                   8194: }
1.512     banghart 8195: 
1.17      www      8196: # ------------------------------------------------------------ Directory lister
                   8197: 
                   8198: sub dirlist {
1.955     raeburn  8199:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8200:     $uri=~s/^\///;
                   8201:     $uri=~s/\/$//;
1.253     stredwic 8202:     my ($udom, $uname);
1.955     raeburn  8203:     if ($getuserdir) {
1.253     stredwic 8204:         $udom = $userdomain;
                   8205:         $uname = $username;
1.955     raeburn  8206:     } else {
                   8207:         (undef,$udom,$uname)=split(/\//,$uri);
                   8208:         if(defined($userdomain)) {
                   8209:             $udom = $userdomain;
                   8210:         }
                   8211:         if(defined($username)) {
                   8212:             $uname = $username;
                   8213:         }
1.253     stredwic 8214:     }
1.955     raeburn  8215:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8216: 
1.955     raeburn  8217:     $dirRoot = $perlvar{'lonDocRoot'};
                   8218:     if (defined($getpropath)) {
                   8219:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8220:         $dirRoot =~ s/\/$//;
1.955     raeburn  8221:     } elsif (defined($getuserdir)) {
                   8222:         my $subdir=$uname.'__';
                   8223:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8224:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8225:                    ."/$udom/$subdir/$uname";
                   8226:     } elsif (defined($alternateRoot)) {
                   8227:         $dirRoot = $alternateRoot;
1.751     banghart 8228:     }
1.253     stredwic 8229: 
                   8230:     if($udom) {
                   8231:         if($uname) {
1.955     raeburn  8232:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8233:                               .$getuserdir.':'.&escape($dirRoot)
1.955     raeburn  8234:                               .':'.&escape($uname).':'.&escape($udom),
                   8235:                               &homeserver($uname,$udom));
                   8236:             if ($listing eq 'unknown_cmd') {
                   8237:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
                   8238:                                   &homeserver($uname,$udom));
                   8239:             } else {
                   8240:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8241:             }
1.605     matthew  8242:             if ($listing eq 'unknown_cmd') {
1.800     albertel 8243:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,
                   8244: 				  &homeserver($uname,$udom));
1.605     matthew  8245:                 @listing_results = split(/:/,$listing);
                   8246:             } else {
                   8247:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8248:             }
                   8249:             return @listing_results;
1.955     raeburn  8250:         } elsif(!$alternateRoot) {
1.800     albertel 8251:             my %allusers;
1.841     albertel 8252: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8253:  	    foreach my $tryserver (keys(%servers)) {
                   8254:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8255:                                   &escape($udom),$tryserver);
                   8256:                 if ($listing eq 'unknown_cmd') {
                   8257: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8258: 				      $udom, $tryserver);
                   8259:                 } else {
                   8260:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8261:                 }
1.841     albertel 8262: 		if ($listing eq 'unknown_cmd') {
                   8263: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8264: 				      $udom, $tryserver);
                   8265: 		    @listing_results = split(/:/,$listing);
                   8266: 		} else {
                   8267: 		    @listing_results =
                   8268: 			map { &unescape($_); } split(/:/,$listing);
                   8269: 		}
                   8270: 		if ($listing_results[0] ne 'no_such_dir' && 
                   8271: 		    $listing_results[0] ne 'empty'       &&
                   8272: 		    $listing_results[0] ne 'con_lost') {
                   8273: 		    foreach my $line (@listing_results) {
                   8274: 			my ($entry) = split(/&/,$line,2);
                   8275: 			$allusers{$entry} = 1;
                   8276: 		    }
                   8277: 		}
1.253     stredwic 8278:             }
                   8279:             my $alluserstr='';
1.800     albertel 8280:             foreach my $user (sort(keys(%allusers))) {
                   8281:                 $alluserstr.=$user.'&user:';
1.253     stredwic 8282:             }
                   8283:             $alluserstr=~s/:$//;
                   8284:             return split(/:/,$alluserstr);
                   8285:         } else {
1.800     albertel 8286:             return ('missing user name');
1.253     stredwic 8287:         }
1.955     raeburn  8288:     } elsif(!defined($getpropath)) {
1.841     albertel 8289:         my @all_domains = sort(&all_domains());
1.955     raeburn  8290:         foreach my $domain (@all_domains) {
                   8291:             $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
                   8292:         }
                   8293:         return @all_domains;
                   8294:     } else {
1.800     albertel 8295:         return ('missing domain');
1.275     stredwic 8296:     }
                   8297: }
                   8298: 
                   8299: # --------------------------------------------- GetFileTimestamp
                   8300: # This function utilizes dirlist and returns the date stamp for
                   8301: # when it was last modified.  It will also return an error of -1
                   8302: # if an error occurs
                   8303: 
                   8304: sub GetFileTimestamp {
1.955     raeburn  8305:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8306:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8307:     $studentName   = &LONCAPA::clean_username($studentName);
1.955     raeburn  8308:     my ($fileStat) = 
                   8309:         &Apache::lonnet::dirlist($filename,$studentDomain,$studentName, 
                   8310:                                  undef,$getuserdir);
1.275     stredwic 8311:     my @stats = split('&', $fileStat);
                   8312:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375     matthew  8313:         # @stats contains first the filename, then the stat output
                   8314:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8315:     } else {
                   8316:         return -1;
1.253     stredwic 8317:     }
1.26      www      8318: }
                   8319: 
1.712     albertel 8320: sub stat_file {
                   8321:     my ($uri) = @_;
1.787     albertel 8322:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8323: 
1.955     raeburn  8324:     my ($udom,$uname,$file);
1.712     albertel 8325:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8326: 	($udom,$uname,$file) =
1.811     albertel 8327: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8328: 	$file = 'userfiles/'.$file;
                   8329:     }
                   8330:     if ($uri =~ m-^/res/-) {
                   8331: 	($udom,$uname) = 
1.807     albertel 8332: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8333: 	$file = $uri;
                   8334:     }
                   8335: 
                   8336:     if (!$udom || !$uname || !$file) {
                   8337: 	# unable to handle the uri
                   8338: 	return ();
                   8339:     }
1.956     raeburn  8340:     my $getpropath;
                   8341:     if ($file =~ /^userfiles\//) {
                   8342:         $getpropath = 1;
                   8343:     }
1.955     raeburn  8344:     my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712     albertel 8345:     my @stats = split('&', $result);
1.721     banghart 8346:     
1.712     albertel 8347:     if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
                   8348: 	shift(@stats); #filename is first
                   8349: 	return @stats;
                   8350:     }
                   8351:     return ();
                   8352: }
                   8353: 
1.26      www      8354: # -------------------------------------------------------- Value of a Condition
                   8355: 
1.713     albertel 8356: # gets the value of a specific preevaluated condition
                   8357: #    stored in the string  $env{user.state.<cid>}
                   8358: # or looks up a condition reference in the bighash and if if hasn't
                   8359: # already been evaluated recurses into docondval to get the value of
                   8360: # the condition, then memoizing it to 
                   8361: #   $env{user.state.<cid>.<condition>}
1.40      www      8362: sub directcondval {
                   8363:     my $number=shift;
1.620     albertel 8364:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8365: 	&Apache::lonuserstate::evalstate();
                   8366:     }
1.713     albertel 8367:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8368: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8369:     } elsif ($number =~ /^_/) {
                   8370: 	my $sub_condition;
                   8371: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8372: 		&GDBM_READER(),0640)) {
                   8373: 	    $sub_condition=$bighash{'conditions'.$number};
                   8374: 	    untie(%bighash);
                   8375: 	}
                   8376: 	my $value = &docondval($sub_condition);
1.949     raeburn  8377: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8378: 	return $value;
                   8379:     }
1.620     albertel 8380:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8381:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8382:     } else {
                   8383:        return 2;
                   8384:     }
                   8385: }
                   8386: 
1.713     albertel 8387: # get the collection of conditions for this resource
1.26      www      8388: sub condval {
                   8389:     my $condidx=shift;
1.54      www      8390:     my $allpathcond='';
1.713     albertel 8391:     foreach my $cond (split(/\|/,$condidx)) {
                   8392: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8393: 	    $allpathcond.=
                   8394: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8395: 	}
1.191     harris41 8396:     }
1.54      www      8397:     $allpathcond=~s/\|$//;
1.713     albertel 8398:     return &docondval($allpathcond);
                   8399: }
                   8400: 
                   8401: #evaluates an expression of conditions
                   8402: sub docondval {
                   8403:     my ($allpathcond) = @_;
                   8404:     my $result=0;
                   8405:     if ($env{'request.course.id'}
                   8406: 	&& defined($allpathcond)) {
                   8407: 	my $operand='|';
                   8408: 	my @stack;
                   8409: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8410: 	    if ($chunk eq '(') {
                   8411: 		push @stack,($operand,$result);
                   8412: 	    } elsif ($chunk eq ')') {
                   8413: 		my $before=pop @stack;
                   8414: 		if (pop @stack eq '&') {
                   8415: 		    $result=$result>$before?$before:$result;
                   8416: 		} else {
                   8417: 		    $result=$result>$before?$result:$before;
                   8418: 		}
                   8419: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8420: 		$operand=$chunk;
                   8421: 	    } else {
                   8422: 		my $new=directcondval($chunk);
                   8423: 		if ($operand eq '&') {
                   8424: 		    $result=$result>$new?$new:$result;
                   8425: 		} else {
                   8426: 		    $result=$result>$new?$result:$new;
                   8427: 		}
                   8428: 	    }
                   8429: 	}
1.26      www      8430:     }
                   8431:     return $result;
1.421     albertel 8432: }
                   8433: 
                   8434: # ---------------------------------------------------- Devalidate courseresdata
                   8435: 
                   8436: sub devalidatecourseresdata {
                   8437:     my ($coursenum,$coursedomain)=@_;
                   8438:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8439:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8440: }
                   8441: 
1.763     www      8442: 
1.200     www      8443: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8444: #
                   8445: #  Parameters:
                   8446: #      $coursenum    - Number of the course.
                   8447: #      $coursedomain - Domain at which the course was created.
                   8448: #  Returns:
                   8449: #     A hash of the course parameters along (I think) with timestamps
                   8450: #     and version info.
1.877     foxr     8451: 
1.624     albertel 8452: sub get_courseresdata {
                   8453:     my ($coursenum,$coursedomain)=@_;
1.200     www      8454:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8455:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8456:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8457:     my %dumpreply;
1.417     albertel 8458:     unless (defined($cached)) {
1.624     albertel 8459: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8460: 	$result=\%dumpreply;
1.251     albertel 8461: 	my ($tmp) = keys(%dumpreply);
                   8462: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8463: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8464: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8465: 	    return $tmp;
1.416     albertel 8466: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8467: 	    $result=undef;
1.599     albertel 8468: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8469: 	}
                   8470:     }
1.624     albertel 8471:     return $result;
                   8472: }
                   8473: 
1.633     albertel 8474: sub devalidateuserresdata {
                   8475:     my ($uname,$udom)=@_;
                   8476:     my $hashid="$udom:$uname";
                   8477:     &devalidate_cache_new('userres',$hashid);
                   8478: }
                   8479: 
1.624     albertel 8480: sub get_userresdata {
                   8481:     my ($uname,$udom)=@_;
                   8482:     #most student don\'t have any data set, check if there is some data
                   8483:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8484: 
                   8485:     my $hashid="$udom:$uname";
                   8486:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8487:     if (!defined($cached)) {
                   8488: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8489: 	$result=\%resourcedata;
                   8490: 	&do_cache_new('userres',$hashid,$result,600);
                   8491:     }
                   8492:     my ($tmp)=keys(%$result);
                   8493:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8494: 	return $result;
                   8495:     }
                   8496:     #error 2 occurs when the .db doesn't exist
                   8497:     if ($tmp!~/error: 2 /) {
1.672     albertel 8498: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8499: 		 " Trying to get resource data for ".
                   8500: 		 $uname." at ".$udom.": ".
                   8501: 		 $tmp."</font>");
                   8502:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8503: 	#&EXT_cache_set($udom,$uname);
                   8504: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8505: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8506:     }
                   8507:     return $tmp;
                   8508: }
1.879     foxr     8509: #----------------------------------------------- resdata - return resource data
                   8510: #  Purpose:
                   8511: #    Return resource data for either users or for a course.
                   8512: #  Parameters:
                   8513: #     $name      - Course/user name.
                   8514: #     $domain    - Name of the domain the user/course is registered on.
                   8515: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8516: #     @which     - Array of names of resources desired.
                   8517: #  Returns:
                   8518: #     The value of the first reasource in @which that is found in the
                   8519: #     resource hash.
                   8520: #  Exceptional Conditions:
                   8521: #     If the $type passed in is not valid (not the string 'course' or 
                   8522: #     'user', an undefined  reference is returned.
                   8523: #     If none of the resources are found, an undef is returned
1.624     albertel 8524: sub resdata {
                   8525:     my ($name,$domain,$type,@which)=@_;
                   8526:     my $result;
                   8527:     if ($type eq 'course') {
                   8528: 	$result=&get_courseresdata($name,$domain);
                   8529:     } elsif ($type eq 'user') {
                   8530: 	$result=&get_userresdata($name,$domain);
                   8531:     }
                   8532:     if (!ref($result)) { return $result; }    
1.251     albertel 8533:     foreach my $item (@which) {
1.927     albertel 8534: 	if (defined($result->{$item->[0]})) {
                   8535: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8536: 	}
1.250     albertel 8537:     }
1.291     albertel 8538:     return undef;
1.200     www      8539: }
                   8540: 
1.379     matthew  8541: #
                   8542: # EXT resource caching routines
                   8543: #
                   8544: 
                   8545: sub clear_EXT_cache_status {
1.383     albertel 8546:     &delenv('cache.EXT.');
1.379     matthew  8547: }
                   8548: 
                   8549: sub EXT_cache_status {
                   8550:     my ($target_domain,$target_user) = @_;
1.383     albertel 8551:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8552:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8553:         # We know already the user has no data
                   8554:         return 1;
                   8555:     } else {
                   8556:         return 0;
                   8557:     }
                   8558: }
                   8559: 
                   8560: sub EXT_cache_set {
                   8561:     my ($target_domain,$target_user) = @_;
1.383     albertel 8562:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8563:     #&appenv({$cachename => time});
1.379     matthew  8564: }
                   8565: 
1.28      www      8566: # --------------------------------------------------------- Value of a Variable
1.58      www      8567: sub EXT {
1.715     albertel 8568: 
1.395     albertel 8569:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8570:     unless ($varname) { return ''; }
1.218     albertel 8571:     #get real user name/domain, courseid and symb
                   8572:     my $courseid;
1.359     albertel 8573:     my $publicuser;
1.427     www      8574:     if ($symbparm) {
                   8575: 	$symbparm=&get_symb_from_alias($symbparm);
                   8576:     }
1.218     albertel 8577:     if (!($uname && $udom)) {
1.790     albertel 8578:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8579:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8580:     } else {
1.620     albertel 8581: 	$courseid=$env{'request.course.id'};
1.218     albertel 8582:     }
1.48      www      8583:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8584:     my $rest;
1.320     albertel 8585:     if (defined($therest[0])) {
1.48      www      8586:        $rest=join('.',@therest);
                   8587:     } else {
                   8588:        $rest='';
                   8589:     }
1.320     albertel 8590: 
1.57      www      8591:     my $qualifierrest=$qualifier;
                   8592:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8593:     my $spacequalifierrest=$space;
                   8594:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8595:     if ($realm eq 'user') {
1.48      www      8596: # --------------------------------------------------------------- user.resource
                   8597: 	if ($space eq 'resource') {
1.651     albertel 8598: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8599: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8600: 		 &&
1.744     albertel 8601: 		 ($symbparm eq &symbread()) ) {	
                   8602: 		# if we are in the middle of processing the resource the
                   8603: 		# get the value we are planning on committing
                   8604:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8605:                     return $Apache::lonhomework::results{$qualifierrest};
                   8606:                 } else {
                   8607:                     return $Apache::lonhomework::history{$qualifierrest};
                   8608:                 }
1.335     albertel 8609: 	    } else {
1.359     albertel 8610: 		my %restored;
1.620     albertel 8611: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8612: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8613: 		} else {
                   8614: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8615: 		}
1.335     albertel 8616: 		return $restored{$qualifierrest};
                   8617: 	    }
1.48      www      8618: # ----------------------------------------------------------------- user.access
                   8619:         } elsif ($space eq 'access') {
1.218     albertel 8620: 	    # FIXME - not supporting calls for a specific user
1.48      www      8621:             return &allowed($qualifier,$rest);
                   8622: # ------------------------------------------ user.preferences, user.environment
                   8623:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8624: 	    if (($uname eq $env{'user.name'}) &&
                   8625: 		($udom eq $env{'user.domain'})) {
                   8626: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8627: 	    } else {
1.359     albertel 8628: 		my %returnhash;
                   8629: 		if (!$publicuser) {
                   8630: 		    %returnhash=&userenvironment($udom,$uname,
                   8631: 						 $qualifierrest);
                   8632: 		}
1.218     albertel 8633: 		return $returnhash{$qualifierrest};
                   8634: 	    }
1.48      www      8635: # ----------------------------------------------------------------- user.course
                   8636:         } elsif ($space eq 'course') {
1.218     albertel 8637: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8638:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8639: # ------------------------------------------------------------------- user.role
                   8640:         } elsif ($space eq 'role') {
1.218     albertel 8641: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8642:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8643:             if ($qualifier eq 'value') {
                   8644: 		return $role;
                   8645:             } elsif ($qualifier eq 'extent') {
                   8646:                 return $where;
                   8647:             }
                   8648: # ----------------------------------------------------------------- user.domain
                   8649:         } elsif ($space eq 'domain') {
1.218     albertel 8650:             return $udom;
1.48      www      8651: # ------------------------------------------------------------------- user.name
                   8652:         } elsif ($space eq 'name') {
1.218     albertel 8653:             return $uname;
1.48      www      8654: # ---------------------------------------------------- Any other user namespace
1.29      www      8655:         } else {
1.359     albertel 8656: 	    my %reply;
                   8657: 	    if (!$publicuser) {
                   8658: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8659: 	    }
                   8660: 	    return $reply{$qualifierrest};
1.48      www      8661:         }
1.236     www      8662:     } elsif ($realm eq 'query') {
                   8663: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8664:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8665: 						[$spacequalifierrest]);
1.620     albertel 8666: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8667:    } elsif ($realm eq 'request') {
1.48      www      8668: # ------------------------------------------------------------- request.browser
                   8669:         if ($space eq 'browser') {
1.430     www      8670: 	    if ($qualifier eq 'textremote') {
1.676     albertel 8671: 		if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430     www      8672: 		    return 1;
                   8673: 		} else {
                   8674: 		    return 0;
                   8675: 		}
                   8676: 	    } else {
1.620     albertel 8677: 		return $env{'browser.'.$qualifier};
1.430     www      8678: 	    }
1.57      www      8679: # ------------------------------------------------------------ request.filename
                   8680:         } else {
1.620     albertel 8681:             return $env{'request.'.$spacequalifierrest};
1.29      www      8682:         }
1.28      www      8683:     } elsif ($realm eq 'course') {
1.48      www      8684: # ---------------------------------------------------------- course.description
1.620     albertel 8685:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8686:     } elsif ($realm eq 'resource') {
1.165     www      8687: 
1.620     albertel 8688: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8689: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8690: 	}
1.693     albertel 8691: 
                   8692: 	if ($space eq 'title') {
                   8693: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8694: 	    return &gettitle($symbparm);
                   8695: 	}
                   8696: 	
                   8697: 	if ($space eq 'map') {
                   8698: 	    my ($map) = &decode_symb($symbparm);
                   8699: 	    return &symbread($map);
                   8700: 	}
1.905     albertel 8701: 	if ($space eq 'filename') {
                   8702: 	    if ($symbparm) {
                   8703: 		return &clutter((&decode_symb($symbparm))[2]);
                   8704: 	    }
                   8705: 	    return &hreflocation('',$env{'request.filename'});
                   8706: 	}
1.693     albertel 8707: 
                   8708: 	my ($section, $group, @groups);
1.593     albertel 8709: 	my ($courselevelm,$courselevel);
1.539     albertel 8710: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8711: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8712: 
1.218     albertel 8713: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8714: 
1.60      www      8715: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8716: 	    my $symbp=$symbparm;
1.735     albertel 8717: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8718: 
                   8719: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8720: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8721: 
1.620     albertel 8722: 	    if (($env{'user.name'} eq $uname) &&
                   8723: 		($env{'user.domain'} eq $udom)) {
                   8724: 		$section=$env{'request.course.sec'};
1.733     raeburn  8725:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8726:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8727: 	    } else {
1.539     albertel 8728: 		if (! defined($usection)) {
1.551     albertel 8729: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8730: 		} else {
                   8731: 		    $section = $usection;
                   8732: 		}
1.733     raeburn  8733:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8734: 	    }
                   8735: 
                   8736: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8737: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8738: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8739: 
1.593     albertel 8740: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8741: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8742: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8743: 
1.60      www      8744: # ----------------------------------------------------------- first, check user
1.624     albertel 8745: 
                   8746: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8747: 				       ([$courselevelr,'resource'],
                   8748: 					[$courselevelm,'map'     ],
                   8749: 					[$courselevel, 'course'  ]));
1.931     albertel 8750: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8751: 
1.594     albertel 8752: # ------------------------------------------------ second, check some of course
1.684     raeburn  8753:             my $coursereply;
1.691     raeburn  8754:             if (@groups > 0) {
                   8755:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8756:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8757:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8758:             }
1.96      www      8759: 
1.684     raeburn  8760: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8761: 				  $env{'course.'.$courseid.'.domain'},
                   8762: 				  'course',
                   8763: 				  ([$seclevelr,   'resource'],
                   8764: 				   [$seclevelm,   'map'     ],
                   8765: 				   [$seclevel,    'course'  ],
                   8766: 				   [$courselevelr,'resource']));
                   8767: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8768: 
1.60      www      8769: # ------------------------------------------------------ third, check map parms
1.218     albertel 8770: 	    my %parmhash=();
                   8771: 	    my $thisparm='';
                   8772: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8773: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8774: 		    &GDBM_READER(),0640)) {
1.218     albertel 8775: 		$thisparm=$parmhash{$symbparm};
                   8776: 		untie(%parmhash);
                   8777: 	    }
1.927     albertel 8778: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8779: 	}
1.594     albertel 8780: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8781: 
1.218     albertel 8782: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8783: 	my $filename;
                   8784: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8785: 	if ($symbparm) {
1.409     www      8786: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8787: 	} else {
1.620     albertel 8788: 	    $filename=$env{'request.filename'};
1.282     albertel 8789: 	}
                   8790: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8791: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8792: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8793: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8794: 
1.927     albertel 8795: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8796: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8797: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8798: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8799: 				     $env{'course.'.$courseid.'.domain'},
                   8800: 				     'course',
1.927     albertel 8801: 				     ([$courselevelm,'map'   ],
                   8802: 				      [$courselevel, 'course']));
                   8803: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8804: 	}
1.145     www      8805: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8806: 	unless ($space eq '0') {
1.336     albertel 8807: 	    my @parts=split(/_/,$space);
                   8808: 	    my $id=pop(@parts);
                   8809: 	    my $part=join('_',@parts);
                   8810: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8811: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8812: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8813: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8814: 	}
1.395     albertel 8815: 	if ($recurse) { return undef; }
                   8816: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8817: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8818: # ---------------------------------------------------- Any other user namespace
                   8819:     } elsif ($realm eq 'environment') {
                   8820: # ----------------------------------------------------------------- environment
1.620     albertel 8821: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8822: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8823: 	} else {
1.770     albertel 8824: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8825: 		return '';
                   8826: 	    }
1.219     albertel 8827: 	    my %returnhash=&userenvironment($udom,$uname,
                   8828: 					    $spacequalifierrest);
                   8829: 	    return $returnhash{$spacequalifierrest};
                   8830: 	}
1.28      www      8831:     } elsif ($realm eq 'system') {
1.48      www      8832: # ----------------------------------------------------------------- system.time
                   8833: 	if ($space eq 'time') {
                   8834: 	    return time;
                   8835:         }
1.696     albertel 8836:     } elsif ($realm eq 'server') {
                   8837: # ----------------------------------------------------------------- system.time
                   8838: 	if ($space eq 'name') {
                   8839: 	    return $ENV{'SERVER_NAME'};
                   8840:         }
1.28      www      8841:     }
1.48      www      8842:     return '';
1.61      www      8843: }
                   8844: 
1.927     albertel 8845: sub get_reply {
                   8846:     my ($reply_value) = @_;
1.940     raeburn  8847:     if (ref($reply_value) eq 'ARRAY') {
                   8848:         if (wantarray) {
                   8849: 	    return @$reply_value;
                   8850:         }
                   8851:         return $reply_value->[0];
                   8852:     } else {
                   8853:         return $reply_value;
1.927     albertel 8854:     }
                   8855: }
                   8856: 
1.691     raeburn  8857: sub check_group_parms {
                   8858:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8859:     my @groupitems = ();
                   8860:     my $resultitem;
1.927     albertel 8861:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8862:     foreach my $group (@{$groups}) {
                   8863:         foreach my $level (@levels) {
1.927     albertel 8864:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8865:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8866:         }
                   8867:     }
                   8868:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8869:                             $env{'course.'.$courseid.'.domain'},
                   8870:                                      'course',@groupitems);
                   8871:     return $coursereply;
                   8872: }
                   8873: 
                   8874: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8875:     my ($courseid,@groups) = @_;
                   8876:     @groups = sort(@groups);
1.691     raeburn  8877:     return @groups;
                   8878: }
                   8879: 
1.395     albertel 8880: sub packages_tab_default {
                   8881:     my ($uri,$varname)=@_;
                   8882:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8883: 
                   8884:     my (@extension,@specifics,$do_default);
                   8885:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8886: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8887: 	if ($pack_type eq 'default') {
                   8888: 	    $do_default=1;
                   8889: 	} elsif ($pack_type eq 'extension') {
                   8890: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8891: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8892: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8893: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8894: 	}
                   8895:     }
                   8896:     # first look for a package that matches the requested part id
                   8897:     foreach my $package (@specifics) {
                   8898: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8899: 	next if ($pack_part ne $part);
                   8900: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8901: 	    return $packagetab{"$pack_type&$name&default"};
                   8902: 	}
                   8903:     }
                   8904:     # look for any possible matching non extension_ package
                   8905:     foreach my $package (@specifics) {
                   8906: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8907: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8908: 	    return $packagetab{"$pack_type&$name&default"};
                   8909: 	}
1.585     albertel 8910: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8911: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8912: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8913: 	}
                   8914:     }
1.738     albertel 8915:     # look for any posible extension_ match
                   8916:     foreach my $package (@extension) {
                   8917: 	my ($package,$pack_type)=@{$package};
                   8918: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8919: 	    return $packagetab{"$pack_type&$name&default"};
                   8920: 	}
                   8921: 	if (defined($packagetab{$package."&$name&default"})) {
                   8922: 	    return $packagetab{$package."&$name&default"};
                   8923: 	}
                   8924:     }
                   8925:     # look for a global default setting
                   8926:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8927: 	return $packagetab{"default&$name&default"};
                   8928:     }
1.395     albertel 8929:     return undef;
                   8930: }
                   8931: 
1.334     albertel 8932: sub add_prefix_and_part {
                   8933:     my ($prefix,$part)=@_;
                   8934:     my $keyroot;
                   8935:     if (defined($prefix) && $prefix !~ /^__/) {
                   8936: 	# prefix that has a part already
                   8937: 	$keyroot=$prefix;
                   8938:     } elsif (defined($prefix)) {
                   8939: 	# prefix that is missing a part
                   8940: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8941:     } else {
                   8942: 	# no prefix at all
                   8943: 	if (defined($part)) { $keyroot='_'.$part; }
                   8944:     }
                   8945:     return $keyroot;
                   8946: }
                   8947: 
1.71      www      8948: # ---------------------------------------------------------------- Get metadata
                   8949: 
1.599     albertel 8950: my %metaentry;
1.1070    www      8951: my %importedpartids;
1.71      www      8952: sub metadata {
1.176     www      8953:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8954:     $uri=&declutter($uri);
1.288     albertel 8955:     # if it is a non metadata possible uri return quickly
1.529     albertel 8956:     if (($uri eq '') || 
                   8957: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8958: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8959:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8960: 	return undef;
                   8961:     }
                   8962:     if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) 
                   8963: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8964: 	return undef;
1.288     albertel 8965:     }
1.73      www      8966:     my $filename=$uri;
                   8967:     $uri=~s/\.meta$//;
1.172     www      8968: #
                   8969: # Is the metadata already cached?
1.177     www      8970: # Look at timestamp of caching
1.172     www      8971: # Everything is cached by the main uri, libraries are never directly cached
                   8972: #
1.428     albertel 8973:     if (!defined($liburi)) {
1.599     albertel 8974: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 8975: 	if (defined($cached)) { return $result->{':'.$what}; }
                   8976:     }
                   8977:     {
1.1069    www      8978: # Imported parts would go here
1.1070    www      8979:         my %importedids=();
                   8980:         my @origfileimportpartids=();
1.1069    www      8981:         my $importedparts=0;
1.172     www      8982: #
                   8983: # Is this a recursive call for a library?
                   8984: #
1.599     albertel 8985: #	if (! exists($metacache{$uri})) {
                   8986: #	    $metacache{$uri}={};
                   8987: #	}
1.924     albertel 8988: 	my $cachetime = 60*60;
1.171     www      8989:         if ($liburi) {
                   8990: 	    $liburi=&declutter($liburi);
                   8991:             $filename=$liburi;
1.401     bowersj2 8992:         } else {
1.599     albertel 8993: 	    &devalidate_cache_new('meta',$uri);
                   8994: 	    undef(%metaentry);
1.401     bowersj2 8995: 	}
1.140     www      8996:         my %metathesekeys=();
1.73      www      8997:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 8998: 	my $metastring;
1.924     albertel 8999: 	if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929     albertel 9000: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9001: 	    $metastring = 
1.929     albertel 9002: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9003: 					  ('grade_target' => 'meta'));
                   9004: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9005: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9006:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9007: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9008: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9009: 	    $metastring=&getfile($file);
1.489     albertel 9010: 	}
1.208     albertel 9011:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9012:         my $token;
1.140     www      9013:         undef %metathesekeys;
1.71      www      9014:         while ($token=$parser->get_token) {
1.339     albertel 9015: 	    if ($token->[0] eq 'S') {
                   9016: 		if (defined($token->[2]->{'package'})) {
1.172     www      9017: #
                   9018: # This is a package - get package info
                   9019: #
1.339     albertel 9020: 		    my $package=$token->[2]->{'package'};
                   9021: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9022: 		    if (defined($token->[2]->{'id'})) { 
                   9023: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9024: 		    }
1.599     albertel 9025: 		    if ($metaentry{':packages'}) {
                   9026: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9027: 		    } else {
1.599     albertel 9028: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9029: 		    }
1.736     albertel 9030: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9031: 			my $part=$keyroot;
                   9032: 			$part=~s/^\_//;
1.736     albertel 9033: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9034: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9035: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9036: 			    # ignore package.tab specified default values
                   9037:                             # here &package_tab_default() will fetch those
                   9038: 			    if ($subp eq 'default') { next; }
1.736     albertel 9039: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9040: 			    my $unikey;
                   9041: 			    if ($pack =~ /_0$/) {
                   9042: 				$unikey='parameter_0_'.$name;
                   9043: 				$part=0;
                   9044: 			    } else {
                   9045: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9046: 			    }
1.339     albertel 9047: 			    if ($subp eq 'display') {
                   9048: 				$value.=' [Part: '.$part.']';
                   9049: 			    }
1.599     albertel 9050: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9051: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9052: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9053: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9054: 			    }
1.599     albertel 9055: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9056: 				$metaentry{':'.$unikey}=
                   9057: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9058: 			    }
1.339     albertel 9059: 			}
                   9060: 		    }
                   9061: 		} else {
1.172     www      9062: #
                   9063: # This is not a package - some other kind of start tag
1.339     albertel 9064: #
                   9065: 		    my $entry=$token->[1];
1.1068    www      9066: 		    my $unikey='';
1.175     www      9067: 
1.339     albertel 9068: 		    if ($entry eq 'import') {
1.175     www      9069: #
                   9070: # Importing a library here
1.339     albertel 9071: #
1.1067    www      9072:                         my $location=$parser->get_text('/import');
                   9073:                         my $dir=$filename;
                   9074:                         $dir=~s|[^/]*$||;
                   9075:                         $location=&filelocation($dir,$location);
1.1069    www      9076:                        
1.1068    www      9077:                         my $importmode=$token->[2]->{'importmode'};
                   9078:                         if ($importmode eq 'problem') {
1.1069    www      9079: # Import as problem/response
1.1068    www      9080:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9081:                         } elsif ($importmode eq 'part') {
                   9082: # Import as part(s)
1.1069    www      9083:                            $importedparts=1;
                   9084: # We need to get the original file and the imported file to get the part order correct
                   9085: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9086: # Load and inspect original file
1.1070    www      9087:                            if ($#origfileimportpartids<0) {
                   9088:                               undef(%importedpartids);
                   9089:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9090:                               my $origfile=&getfile($origfilelocation);
                   9091:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9092:                            }
                   9093: 
1.1069    www      9094: # Load and inspect imported file
                   9095:                            my $impfile=&getfile($location);
                   9096:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9097:                            if ($#impfilepartids>=0) {
                   9098: # This problem had parts
1.1070    www      9099:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9100:                            } else {
                   9101: # Importing by turning a single problem into a problem part
                   9102: # It gets the import-tags ID as part-ID
                   9103:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9104:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9105:                            }
1.1068    www      9106:                         } else {
                   9107: # Normal import
                   9108:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9109:                            if (defined($token->[2]->{'id'})) {
                   9110:                               $unikey.='_'.$token->[2]->{'id'};
                   9111:                            }
1.1067    www      9112:                         }
                   9113: 
1.339     albertel 9114: 			if ($depthcount<20) {
1.736     albertel 9115: 			    my $metadata = 
                   9116: 				&metadata($uri,'keys', $location,$unikey,
                   9117: 					  $depthcount+1);
                   9118: 			    foreach my $meta (split(',',$metadata)) {
                   9119: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9120: 				$metathesekeys{$meta}=1;
1.339     albertel 9121: 			    }
1.1068    www      9122: 			
                   9123:                         }
1.1067    www      9124: 		    } else {
                   9125: #
                   9126: # Not importing, some other kind of non-package, non-library start tag
                   9127: # 
                   9128:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9129:                         if (defined($token->[2]->{'id'})) {
                   9130:                             $unikey.='_'.$token->[2]->{'id'};
                   9131:                         }
1.339     albertel 9132: 			if (defined($token->[2]->{'name'})) { 
                   9133: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9134: 			}
                   9135: 			$metathesekeys{$unikey}=1;
1.736     albertel 9136: 			foreach my $param (@{$token->[3]}) {
                   9137: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9138: 				$token->[2]->{$param};
1.339     albertel 9139: 			}
                   9140: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9141: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9142: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9143: 		 # only ws inside the tag, and not in default, so use default
                   9144: 		 # as value
1.599     albertel 9145: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9146: 			} elsif ( $internaltext =~ /\S/ ) {
                   9147: 		  # something interesting inside the tag
                   9148: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9149: 			} else {
1.908     albertel 9150: 		  # no interesting values, don't set a default
1.339     albertel 9151: 			}
1.172     www      9152: # end of not-a-package not-a-library import
1.339     albertel 9153: 		    }
1.172     www      9154: # end of not-a-package start tag
1.339     albertel 9155: 		}
1.172     www      9156: # the next is the end of "start tag"
1.339     albertel 9157: 	    }
                   9158: 	}
1.483     albertel 9159: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9160: 	$extension = lc($extension);
                   9161: 	if ($extension eq 'htm') { $extension='html'; }
                   9162: 
1.737     albertel 9163: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9164: 	    #no specific packages #how's our extension
                   9165: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9166: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9167: 					 \%metathesekeys);
                   9168: 	}
1.883     albertel 9169: 
                   9170: 	if (!exists($metaentry{':packages'})
                   9171: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9172: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9173: 		#no specific packages well let's get default then
                   9174: 		if ($key!~/^default&/) { next; }
1.488     albertel 9175: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9176: 					     \%metathesekeys);
                   9177: 	    }
                   9178: 	}
1.338     www      9179: # are there custom rights to evaluate
1.599     albertel 9180: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9181: 
1.338     www      9182:     #
                   9183:     # Importing a rights file here
1.339     albertel 9184:     #
                   9185: 	    unless ($depthcount) {
1.599     albertel 9186: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9187: 		my $dir=$filename;
                   9188: 		$dir=~s|[^/]*$||;
                   9189: 		$location=&filelocation($dir,$location);
1.736     albertel 9190: 		my $rights_metadata =
                   9191: 		    &metadata($uri,'keys',$location,'_rights',
                   9192: 			      $depthcount+1);
                   9193: 		foreach my $rights (split(',',$rights_metadata)) {
                   9194: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9195: 		    $metathesekeys{$rights}=1;
1.339     albertel 9196: 		}
                   9197: 	    }
                   9198: 	}
1.737     albertel 9199: 	# uniqifiy package listing
                   9200: 	my %seen;
                   9201: 	my @uniq_packages =
                   9202: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9203: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9204: 
1.1070    www      9205:         if ($importedparts) {
                   9206: # We had imported parts and need to rebuild partorder
                   9207:            $metaentry{':partorder'}='';
                   9208:            $metathesekeys{'partorder'}=1;
                   9209:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9210:                if ($origfileimportpartids[$index] eq 'part') {
                   9211: # original part, part of the problem
                   9212:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9213:                } else {
                   9214: # we have imported parts at this position
                   9215:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9216:                }
                   9217:            }
                   9218:            $metaentry{':partorder'}=~s/^\,//;
                   9219:         }
                   9220: 
1.737     albertel 9221: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9222: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9223: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9224: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9225: # this is the end of "was not already recently cached
1.71      www      9226:     }
1.599     albertel 9227:     return $metaentry{':'.$what};
1.261     albertel 9228: }
                   9229: 
1.488     albertel 9230: sub metadata_create_package_def {
1.483     albertel 9231:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9232:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9233:     if ($subp eq 'default') { next; }
                   9234:     
1.599     albertel 9235:     if (defined($metaentry{':packages'})) {
                   9236: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9237:     } else {
1.599     albertel 9238: 	$metaentry{':packages'}=$package;
1.483     albertel 9239:     }
                   9240:     my $value=$packagetab{$key};
                   9241:     my $unikey;
                   9242:     $unikey='parameter_0_'.$name;
1.599     albertel 9243:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9244:     $$metathesekeys{$unikey}=1;
1.599     albertel 9245:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9246: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9247:     }
1.599     albertel 9248:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9249: 	$metaentry{':'.$unikey}=
                   9250: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9251:     }
                   9252: }
                   9253: 
1.261     albertel 9254: sub metadata_generate_part0 {
                   9255:     my ($metadata,$metacache,$uri) = @_;
                   9256:     my %allnames;
1.737     albertel 9257:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9258: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9259: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9260: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9261: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9262: 	    $allnames{$name}=$part;
                   9263: 	  }
                   9264: 	}
                   9265:     }
                   9266:     foreach my $name (keys(%allnames)) {
                   9267:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9268:       my $key=":parameter_0_$name";
1.261     albertel 9269:       $$metacache{"$key.part"}='0';
                   9270:       $$metacache{"$key.name"}=$name;
1.428     albertel 9271:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9272: 					   $allnames{$name}.'_'.$name.
                   9273: 					   '.type'};
1.428     albertel 9274:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9275: 			     '.display'};
1.644     www      9276:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9277:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9278:       $$metacache{"$key.display"}=$olddis;
                   9279:     }
1.71      www      9280: }
                   9281: 
1.764     albertel 9282: # ------------------------------------------------------ Devalidate title cache
                   9283: 
                   9284: sub devalidate_title_cache {
                   9285:     my ($url)=@_;
                   9286:     if (!$env{'request.course.id'}) { return; }
                   9287:     my $symb=&symbread($url);
                   9288:     if (!$symb) { return; }
                   9289:     my $key=$env{'request.course.id'}."\0".$symb;
                   9290:     &devalidate_cache_new('title',$key);
                   9291: }
                   9292: 
1.1014    droeschl 9293: # ------------------------------------------------- Get the title of a course
                   9294: 
                   9295: sub current_course_title {
                   9296:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9297: }
1.301     www      9298: # ------------------------------------------------- Get the title of a resource
                   9299: 
                   9300: sub gettitle {
                   9301:     my $urlsymb=shift;
                   9302:     my $symb=&symbread($urlsymb);
1.534     albertel 9303:     if ($symb) {
1.620     albertel 9304: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9305: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9306: 	if (defined($cached)) { 
                   9307: 	    return $result;
                   9308: 	}
1.534     albertel 9309: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9310: 	my $title='';
1.907     albertel 9311: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9312: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9313: 	} else {
                   9314: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9315: 		    &GDBM_READER(),0640)) {
                   9316: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9317: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9318: 		untie(%bighash);
                   9319: 	    }
1.534     albertel 9320: 	}
                   9321: 	$title=~s/\&colon\;/\:/gs;
                   9322: 	if ($title) {
1.599     albertel 9323: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9324: 	}
                   9325: 	$urlsymb=$url;
                   9326:     }
                   9327:     my $title=&metadata($urlsymb,'title');
                   9328:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9329:     return $title;
1.301     www      9330: }
1.613     albertel 9331: 
1.614     albertel 9332: sub get_slot {
                   9333:     my ($which,$cnum,$cdom)=@_;
                   9334:     if (!$cnum || !$cdom) {
1.790     albertel 9335: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9336: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9337: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9338:     }
1.703     albertel 9339:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9340:     my %slotinfo;
                   9341:     if (exists($remembered{$key})) {
                   9342: 	$slotinfo{$which} = $remembered{$key};
                   9343:     } else {
                   9344: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9345: 	&Apache::lonhomework::showhash(%slotinfo);
                   9346: 	my ($tmp)=keys(%slotinfo);
                   9347: 	if ($tmp=~/^error:/) { return (); }
                   9348: 	$remembered{$key} = $slotinfo{$which};
                   9349:     }
1.616     albertel 9350:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9351: 	return %{$slotinfo{$which}};
                   9352:     }
                   9353:     return $slotinfo{$which};
1.614     albertel 9354: }
1.31      www      9355: # ------------------------------------------------- Update symbolic store links
                   9356: 
                   9357: sub symblist {
                   9358:     my ($mapname,%newhash)=@_;
1.438     www      9359:     $mapname=&deversion(&declutter($mapname));
1.31      www      9360:     my %hash;
1.620     albertel 9361:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9362:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9363:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9364: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9365: 		next if ($url eq 'last_known'
                   9366: 			 && $env{'form.no_update_last_known'});
                   9367: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9368: 						    $newhash{$url}->[1],
                   9369: 						    $newhash{$url}->[0]);
1.191     harris41 9370:             }
1.31      www      9371:             if (untie(%hash)) {
                   9372: 		return 'ok';
                   9373:             }
                   9374:         }
                   9375:     }
                   9376:     return 'error';
1.212     www      9377: }
                   9378: 
                   9379: # --------------------------------------------------------------- Verify a symb
                   9380: 
                   9381: sub symbverify {
1.510     www      9382:     my ($symb,$thisurl)=@_;
                   9383:     my $thisfn=$thisurl;
1.439     www      9384:     $thisfn=&declutter($thisfn);
1.215     www      9385: # direct jump to resource in page or to a sequence - will construct own symbs
                   9386:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9387: # check URL part
1.409     www      9388:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9389: 
1.431     www      9390:     unless ($url eq $thisfn) { return 0; }
1.213     www      9391: 
1.216     www      9392:     $symb=&symbclean($symb);
1.510     www      9393:     $thisurl=&deversion($thisurl);
1.439     www      9394:     $thisfn=&deversion($thisfn);
1.213     www      9395: 
                   9396:     my %bighash;
                   9397:     my $okay=0;
1.431     www      9398: 
1.620     albertel 9399:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9400:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9401:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9402:             $thisurl =~ s/\?.+$//;
                   9403:         }
1.510     www      9404:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9405:         unless ($ids) {
                   9406:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9407:             $ids=$bighash{$idkey};
1.216     www      9408:         }
                   9409:         if ($ids) {
                   9410: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9411: 	    foreach my $id (split(/\,/,$ids)) {
                   9412: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9413:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9414:                    $symb =~ s/\?.+$//;
                   9415:                }
1.216     www      9416:                if (
                   9417:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9418:    eq $symb) { 
1.620     albertel 9419: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9420: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9421:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9422: 		       $okay=1; 
                   9423: 		   }
                   9424: 	       }
1.216     www      9425: 	   }
                   9426:         }
1.213     www      9427: 	untie(%bighash);
                   9428:     }
                   9429:     return $okay;
1.31      www      9430: }
                   9431: 
1.210     www      9432: # --------------------------------------------------------------- Clean-up symb
                   9433: 
                   9434: sub symbclean {
                   9435:     my $symb=shift;
1.568     albertel 9436:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9437: # remove version from map
                   9438:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9439: 
1.210     www      9440: # remove version from URL
                   9441:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9442: 
1.507     www      9443: # remove wrapper
                   9444: 
1.510     www      9445:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9446:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9447:     return $symb;
1.409     www      9448: }
                   9449: 
                   9450: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9451: 
                   9452: sub encode_symb {
                   9453:     my ($map,$resid,$url)=@_;
                   9454:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9455: }
1.409     www      9456: 
                   9457: sub decode_symb {
1.568     albertel 9458:     my $symb=shift;
                   9459:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9460:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9461:     return (&fixversion($map),$resid,&fixversion($url));
                   9462: }
                   9463: 
                   9464: sub fixversion {
                   9465:     my $fn=shift;
1.609     banghart 9466:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9467:     my %bighash;
                   9468:     my $uri=&clutter($fn);
1.620     albertel 9469:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9470: # is this cached?
1.599     albertel 9471:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9472:     if (defined($cached)) { return $result; }
                   9473: # unfortunately not cached, or expired
1.620     albertel 9474:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9475: 	    &GDBM_READER(),0640)) {
                   9476:  	if ($bighash{'version_'.$uri}) {
                   9477:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9478:  	    unless (($version eq 'mostrecent') || 
                   9479: 		    ($version==&getversion($uri))) {
1.440     www      9480:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9481:  	    }
                   9482:  	}
                   9483:  	untie %bighash;
1.413     www      9484:     }
1.599     albertel 9485:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9486: }
                   9487: 
                   9488: sub deversion {
                   9489:     my $url=shift;
                   9490:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9491:     return $url;
1.210     www      9492: }
                   9493: 
1.31      www      9494: # ------------------------------------------------------ Return symb list entry
                   9495: 
                   9496: sub symbread {
1.249     www      9497:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9498:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9499:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9500: # no filename provided? try from environment
1.44      www      9501:     unless ($thisfn) {
1.620     albertel 9502:         if ($env{'request.symb'}) {
                   9503: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9504: 	}
1.620     albertel 9505: 	$thisfn=$env{'request.filename'};
1.44      www      9506:     }
1.569     albertel 9507:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9508: # is that filename actually a symb? Verify, clean, and return
                   9509:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9510: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9511: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9512: 	}
1.242     www      9513:     }
1.44      www      9514:     $thisfn=declutter($thisfn);
1.31      www      9515:     my %hash;
1.37      www      9516:     my %bighash;
                   9517:     my $syval='';
1.620     albertel 9518:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9519:         my $targetfn = $thisfn;
1.609     banghart 9520:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9521:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9522:         }
1.687     albertel 9523: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9524: 	    $targetfn=$1;
                   9525: 	}
1.620     albertel 9526:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9527:                       &GDBM_READER(),0640)) {
1.481     raeburn  9528: 	    $syval=$hash{$targetfn};
1.37      www      9529:             untie(%hash);
                   9530:         }
                   9531: # ---------------------------------------------------------- There was an entry
                   9532:         if ($syval) {
1.601     albertel 9533: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9534: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9535: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9536: 		    #return $env{$cache_str}='';
1.601     albertel 9537: 		#}    
                   9538: 		#$syval.=$1;
                   9539: 	    #}
1.37      www      9540:         } else {
                   9541: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9542:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9543:                             &GDBM_READER(),0640)) {
1.37      www      9544: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9545:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9546:               unless ($ids) { 
                   9547:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9548:               }
                   9549:               unless ($ids) {
                   9550: # alias?
                   9551: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9552:               }
1.37      www      9553:               if ($ids) {
                   9554: # ------------------------------------------------------------------- Has ID(s)
                   9555:                  my @possibilities=split(/\,/,$ids);
1.39      www      9556:                  if ($#possibilities==0) {
                   9557: # ----------------------------------------------- There is only one possibility
1.37      www      9558: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9559: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9560: 						    $resid,$thisfn);
1.249     www      9561:                  } elsif (!$donotrecurse) {
1.39      www      9562: # ------------------------------------------ There is more than one possibility
                   9563:                      my $realpossible=0;
1.800     albertel 9564:                      foreach my $id (@possibilities) {
                   9565: 			 my $file=$bighash{'src_'.$id};
1.39      www      9566:                          if (&allowed('bre',$file)) {
1.800     albertel 9567:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9568:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9569: 				$realpossible++;
1.626     albertel 9570:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9571: 						    $resid,$thisfn);
1.39      www      9572:                             }
                   9573: 			 }
1.191     harris41 9574:                      }
1.39      www      9575: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9576:                  } else {
                   9577:                      $syval='';
1.37      www      9578:                  }
                   9579: 	      }
                   9580:               untie(%bighash)
1.481     raeburn  9581:            }
1.31      www      9582:         }
1.62      www      9583:         if ($syval) {
1.620     albertel 9584: 	    return $env{$cache_str}=$syval;
1.62      www      9585:         }
1.31      www      9586:     }
1.949     raeburn  9587:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9588:     return $env{$cache_str}='';
1.31      www      9589: }
                   9590: 
                   9591: # ---------------------------------------------------------- Return random seed
                   9592: 
1.32      www      9593: sub numval {
                   9594:     my $txt=shift;
                   9595:     $txt=~tr/A-J/0-9/;
                   9596:     $txt=~tr/a-j/0-9/;
                   9597:     $txt=~tr/K-T/0-9/;
                   9598:     $txt=~tr/k-t/0-9/;
                   9599:     $txt=~tr/U-Z/0-5/;
                   9600:     $txt=~tr/u-z/0-5/;
                   9601:     $txt=~s/\D//g;
1.564     albertel 9602:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9603:     return int($txt);
1.368     albertel 9604: }
                   9605: 
1.484     albertel 9606: sub numval2 {
                   9607:     my $txt=shift;
                   9608:     $txt=~tr/A-J/0-9/;
                   9609:     $txt=~tr/a-j/0-9/;
                   9610:     $txt=~tr/K-T/0-9/;
                   9611:     $txt=~tr/k-t/0-9/;
                   9612:     $txt=~tr/U-Z/0-5/;
                   9613:     $txt=~tr/u-z/0-5/;
                   9614:     $txt=~s/\D//g;
                   9615:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9616:     my $total;
                   9617:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9618:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9619:     return int($total);
                   9620: }
                   9621: 
1.575     albertel 9622: sub numval3 {
                   9623:     use integer;
                   9624:     my $txt=shift;
                   9625:     $txt=~tr/A-J/0-9/;
                   9626:     $txt=~tr/a-j/0-9/;
                   9627:     $txt=~tr/K-T/0-9/;
                   9628:     $txt=~tr/k-t/0-9/;
                   9629:     $txt=~tr/U-Z/0-5/;
                   9630:     $txt=~tr/u-z/0-5/;
                   9631:     $txt=~s/\D//g;
                   9632:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9633:     my $total;
                   9634:     foreach my $val (@txts) { $total+=$val; }
                   9635:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9636:     return $total;
                   9637: }
                   9638: 
1.675     albertel 9639: sub digest {
                   9640:     my ($data)=@_;
                   9641:     my $digest=&Digest::MD5::md5($data);
                   9642:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9643:     my ($e,$f);
                   9644:     {
                   9645:         use integer;
                   9646:         $e=($a+$b);
                   9647:         $f=($c+$d);
                   9648:         if ($_64bit) {
                   9649:             $e=(($e<<32)>>32);
                   9650:             $f=(($f<<32)>>32);
                   9651:         }
                   9652:     }
                   9653:     if (wantarray) {
                   9654: 	return ($e,$f);
                   9655:     } else {
                   9656: 	my $g;
                   9657: 	{
                   9658: 	    use integer;
                   9659: 	    $g=($e+$f);
                   9660: 	    if ($_64bit) {
                   9661: 		$g=(($g<<32)>>32);
                   9662: 	    }
                   9663: 	}
                   9664: 	return $g;
                   9665:     }
                   9666: }
                   9667: 
1.368     albertel 9668: sub latest_rnd_algorithm_id {
1.675     albertel 9669:     return '64bit5';
1.366     albertel 9670: }
1.32      www      9671: 
1.503     albertel 9672: sub get_rand_alg {
                   9673:     my ($courseid)=@_;
1.790     albertel 9674:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9675:     if ($courseid) {
1.620     albertel 9676: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9677:     }
                   9678:     return &latest_rnd_algorithm_id();
                   9679: }
                   9680: 
1.562     albertel 9681: sub validCODE {
                   9682:     my ($CODE)=@_;
                   9683:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9684:     return 0;
                   9685: }
                   9686: 
1.491     albertel 9687: sub getCODE {
1.620     albertel 9688:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9689:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9690: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9691: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9692: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9693:     }
                   9694:     return undef;
                   9695: }
                   9696: 
1.31      www      9697: sub rndseed {
1.155     albertel 9698:     my ($symb,$courseid,$domain,$username)=@_;
1.790     albertel 9699:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9700:     if (!defined($symb)) {
1.366     albertel 9701: 	unless ($symb=$wsymb) { return time; }
                   9702:     }
                   9703:     if (!$courseid) { $courseid=$wcourseid; }
                   9704:     if (!$domain) { $domain=$wdomain; }
                   9705:     if (!$username) { $username=$wusername }
1.503     albertel 9706:     my $which=&get_rand_alg();
1.1110    www      9707: 
1.491     albertel 9708:     if (defined(&getCODE())) {
1.675     albertel 9709: 	if ($which eq '64bit5') {
                   9710: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9711: 	} elsif ($which eq '64bit4') {
1.575     albertel 9712: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9713: 	} else {
                   9714: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9715: 	}
1.675     albertel 9716:     } elsif ($which eq '64bit5') {
                   9717: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9718:     } elsif ($which eq '64bit4') {
                   9719: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9720:     } elsif ($which eq '64bit3') {
                   9721: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9722:     } elsif ($which eq '64bit2') {
                   9723: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9724:     } elsif ($which eq '64bit') {
                   9725: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9726:     }
                   9727:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9728: }
                   9729: 
                   9730: sub rndseed_32bit {
                   9731:     my ($symb,$courseid,$domain,$username)=@_;
                   9732:     {
                   9733: 	use integer;
                   9734: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9735: 	my $symbseed=numval($symb) << 22;
                   9736: 	my $namechck=unpack("%32C*",$username) << 17;
                   9737: 	my $nameseed=numval($username) << 12;
                   9738: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9739: 	my $courseseed=unpack("%32C*",$courseid);
                   9740: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9741: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9742: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9743: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9744: 	return $num;
                   9745:     }
                   9746: }
                   9747: 
                   9748: sub rndseed_64bit {
                   9749:     my ($symb,$courseid,$domain,$username)=@_;
                   9750:     {
                   9751: 	use integer;
                   9752: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9753: 	my $symbseed=numval($symb) << 10;
                   9754: 	my $namechck=unpack("%32S*",$username);
                   9755: 	
                   9756: 	my $nameseed=numval($username) << 21;
                   9757: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9758: 	my $courseseed=unpack("%32S*",$courseid);
                   9759: 	
                   9760: 	my $num1=$symbchck+$symbseed+$namechck;
                   9761: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9762: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9763: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9764: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9765: 	return "$num1,$num2";
1.155     albertel 9766:     }
1.366     albertel 9767: }
                   9768: 
1.443     albertel 9769: sub rndseed_64bit2 {
                   9770:     my ($symb,$courseid,$domain,$username)=@_;
                   9771:     {
                   9772: 	use integer;
                   9773: 	# strings need to be an even # of cahracters long, it it is odd the
                   9774:         # last characters gets thrown away
                   9775: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9776: 	my $symbseed=numval($symb) << 10;
                   9777: 	my $namechck=unpack("%32S*",$username.' ');
                   9778: 	
                   9779: 	my $nameseed=numval($username) << 21;
1.501     albertel 9780: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9781: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9782: 	
                   9783: 	my $num1=$symbchck+$symbseed+$namechck;
                   9784: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9785: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9786: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9787: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9788: 	return "$num1,$num2";
                   9789:     }
                   9790: }
                   9791: 
                   9792: sub rndseed_64bit3 {
                   9793:     my ($symb,$courseid,$domain,$username)=@_;
                   9794:     {
                   9795: 	use integer;
                   9796: 	# strings need to be an even # of cahracters long, it it is odd the
                   9797:         # last characters gets thrown away
                   9798: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9799: 	my $symbseed=numval2($symb) << 10;
                   9800: 	my $namechck=unpack("%32S*",$username.' ');
                   9801: 	
                   9802: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9803: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9804: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9805: 	
                   9806: 	my $num1=$symbchck+$symbseed+$namechck;
                   9807: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9808: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9809: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9810: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9811: 	
1.503     albertel 9812: 	return "$num1:$num2";
1.443     albertel 9813:     }
                   9814: }
                   9815: 
1.575     albertel 9816: sub rndseed_64bit4 {
                   9817:     my ($symb,$courseid,$domain,$username)=@_;
                   9818:     {
                   9819: 	use integer;
                   9820: 	# strings need to be an even # of cahracters long, it it is odd the
                   9821:         # last characters gets thrown away
                   9822: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9823: 	my $symbseed=numval3($symb) << 10;
                   9824: 	my $namechck=unpack("%32S*",$username.' ');
                   9825: 	
                   9826: 	my $nameseed=numval3($username) << 21;
                   9827: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9828: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9829: 	
                   9830: 	my $num1=$symbchck+$symbseed+$namechck;
                   9831: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9832: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9833: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9834: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9835: 	
1.575     albertel 9836: 	return "$num1:$num2";
                   9837:     }
                   9838: }
                   9839: 
1.675     albertel 9840: sub rndseed_64bit5 {
                   9841:     my ($symb,$courseid,$domain,$username)=@_;
                   9842:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9843:     return "$num1:$num2";
                   9844: }
                   9845: 
1.366     albertel 9846: sub rndseed_CODE_64bit {
                   9847:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9848:     {
1.366     albertel 9849: 	use integer;
1.443     albertel 9850: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9851: 	my $symbseed=numval2($symb);
1.491     albertel 9852: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9853: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9854: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9855: 	my $num1=$symbseed+$CODEchck;
                   9856: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9857: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9858: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9859: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9860: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9861: 	return "$num1:$num2";
1.366     albertel 9862:     }
                   9863: }
                   9864: 
1.575     albertel 9865: sub rndseed_CODE_64bit4 {
                   9866:     my ($symb,$courseid,$domain,$username)=@_;
                   9867:     {
                   9868: 	use integer;
                   9869: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9870: 	my $symbseed=numval3($symb);
                   9871: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9872: 	my $CODEseed=numval3(&getCODE());
                   9873: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9874: 	my $num1=$symbseed+$CODEchck;
                   9875: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9876: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9877: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9878: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9879: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9880: 	return "$num1:$num2";
                   9881:     }
                   9882: }
                   9883: 
1.675     albertel 9884: sub rndseed_CODE_64bit5 {
                   9885:     my ($symb,$courseid,$domain,$username)=@_;
                   9886:     my $code = &getCODE();
                   9887:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9888:     return "$num1:$num2";
                   9889: }
                   9890: 
1.366     albertel 9891: sub setup_random_from_rndseed {
                   9892:     my ($rndseed)=@_;
1.503     albertel 9893:     if ($rndseed =~/([,:])/) {
                   9894: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9895: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9896:     } else {
                   9897: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9898:     }
1.36      albertel 9899: }
                   9900: 
1.474     albertel 9901: sub latest_receipt_algorithm_id {
1.835     albertel 9902:     return 'receipt3';
1.474     albertel 9903: }
                   9904: 
1.480     www      9905: sub recunique {
                   9906:     my $fucourseid=shift;
                   9907:     my $unique;
1.835     albertel 9908:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9909: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9910: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9911:     } else {
                   9912: 	$unique=$perlvar{'lonReceipt'};
                   9913:     }
                   9914:     return unpack("%32C*",$unique);
                   9915: }
                   9916: 
                   9917: sub recprefix {
                   9918:     my $fucourseid=shift;
                   9919:     my $prefix;
1.835     albertel 9920:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9921: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9922: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9923:     } else {
                   9924: 	$prefix=$perlvar{'lonHostID'};
                   9925:     }
                   9926:     return unpack("%32C*",$prefix);
                   9927: }
                   9928: 
1.76      www      9929: sub ireceipt {
1.474     albertel 9930:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9931: 
                   9932:     my $return =&recprefix($fucourseid).'-';
                   9933: 
                   9934:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9935: 	$env{'request.state'} eq 'construct') {
                   9936: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9937: 	return $return;
                   9938:     }
                   9939: 
1.76      www      9940:     my $cuname=unpack("%32C*",$funame);
                   9941:     my $cudom=unpack("%32C*",$fudom);
                   9942:     my $cucourseid=unpack("%32C*",$fucourseid);
                   9943:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      9944:     my $cunique=&recunique($fucourseid);
1.474     albertel 9945:     my $cpart=unpack("%32S*",$part);
1.835     albertel 9946:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   9947: 
1.790     albertel 9948: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 9949: 			       
                   9950: 	$return.= ($cunique%$cuname+
                   9951: 		   $cunique%$cudom+
                   9952: 		   $cusymb%$cuname+
                   9953: 		   $cusymb%$cudom+
                   9954: 		   $cucourseid%$cuname+
                   9955: 		   $cucourseid%$cudom+
                   9956: 		   $cpart%$cuname+
                   9957: 		   $cpart%$cudom);
                   9958:     } else {
                   9959: 	$return.= ($cunique%$cuname+
                   9960: 		   $cunique%$cudom+
                   9961: 		   $cusymb%$cuname+
                   9962: 		   $cusymb%$cudom+
                   9963: 		   $cucourseid%$cuname+
                   9964: 		   $cucourseid%$cudom);
                   9965:     }
                   9966:     return $return;
1.76      www      9967: }
                   9968: 
                   9969: sub receipt {
1.474     albertel 9970:     my ($part)=@_;
1.790     albertel 9971:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 9972:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      9973: }
1.260     ng       9974: 
1.790     albertel 9975: sub whichuser {
                   9976:     my ($passedsymb)=@_;
                   9977:     my ($symb,$courseid,$domain,$name,$publicuser);
                   9978:     if (defined($env{'form.grade_symb'})) {
                   9979: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   9980: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   9981: 	if (!$allowed &&
                   9982: 	    exists($env{'request.course.sec'}) &&
                   9983: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   9984: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   9985: 			      '/'.$env{'request.course.sec'});
                   9986: 	}
                   9987: 	if ($allowed) {
                   9988: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   9989: 	    $courseid=$tmp_courseid;
                   9990: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   9991: 	    ($name)=&get_env_multiple('form.grade_username');
                   9992: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   9993: 	}
                   9994:     }
                   9995:     if (!$passedsymb) {
                   9996: 	$symb=&symbread();
                   9997:     } else {
                   9998: 	$symb=$passedsymb;
                   9999:     }
                   10000:     $courseid=$env{'request.course.id'};
                   10001:     $domain=$env{'user.domain'};
                   10002:     $name=$env{'user.name'};
                   10003:     if ($name eq 'public' && $domain eq 'public') {
                   10004: 	if (!defined($env{'form.username'})) {
                   10005: 	    $env{'form.username'}.=time.rand(10000000);
                   10006: 	}
                   10007: 	$name.=$env{'form.username'};
                   10008:     }
                   10009:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10010: 
                   10011: }
                   10012: 
1.36      albertel 10013: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10014: # returns either the contents of the file or 
                   10015: # -1 if the file doesn't exist
1.481     raeburn  10016: #
                   10017: # if the target is a file that was uploaded via DOCS, 
                   10018: # a check will be made to see if a current copy exists on the local server,
                   10019: # if it does this will be served, otherwise a copy will be retrieved from
                   10020: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10021: # the local server.   
1.472     albertel 10022: 
1.36      albertel 10023: sub getfile {
1.538     albertel 10024:     my ($file) = @_;
1.609     banghart 10025:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10026:     &repcopy($file);
                   10027:     return &readfile($file);
                   10028: }
                   10029: 
                   10030: sub repcopy_userfile {
                   10031:     my ($file)=@_;
1.609     banghart 10032:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610     albertel 10033:     if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538     albertel 10034:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10035: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10036:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10037:     if (-e "$file") {
1.828     www      10038: # we already have a local copy, check it out
1.538     albertel 10039: 	my @fileinfo = stat($file);
1.828     www      10040: 	my $rtncode;
                   10041: 	my $info;
1.538     albertel 10042: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10043: 	if ($lwpresp ne 'ok') {
1.828     www      10044: # there is no such file anymore, even though we had a local copy
1.482     albertel 10045: 	    if ($rtncode eq '404') {
1.538     albertel 10046: 		unlink($file);
1.482     albertel 10047: 	    }
                   10048: 	    return -1;
                   10049: 	}
                   10050: 	if ($info < $fileinfo[9]) {
1.828     www      10051: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10052: 	    return 'ok';
1.828     www      10053: 	} else {
                   10054: # the file is outdated, get rid of it
                   10055: 	    unlink($file);
1.482     albertel 10056: 	}
1.828     www      10057:     }
                   10058: # one way or the other, at this point, we don't have the file
                   10059: # construct the correct path for the file
                   10060:     my @parts = ($cdom,$cnum); 
                   10061:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10062: 	push @parts, split(/\//,$1);
                   10063:     }
                   10064:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10065:     foreach my $part (@parts) {
                   10066: 	$path .= '/'.$part;
                   10067: 	if (!-e $path) {
                   10068: 	    mkdir($path,0770);
1.482     albertel 10069: 	}
                   10070:     }
1.828     www      10071: # now the path exists for sure
                   10072: # get a user agent
                   10073:     my $ua=new LWP::UserAgent;
                   10074:     my $transferfile=$file.'.in.transfer';
                   10075: # FIXME: this should flock
                   10076:     if (-e $transferfile) { return 'ok'; }
                   10077:     my $request;
                   10078:     $uri=~s/^\///;
1.980     raeburn  10079:     my $homeserver = &homeserver($cnum,$cdom);
                   10080:     my $protocol = $protocol{$homeserver};
                   10081:     $protocol = 'http' if ($protocol ne 'https');
                   10082:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10083:     my $response=$ua->request($request,$transferfile);
                   10084: # did it work?
                   10085:     if ($response->is_error()) {
                   10086: 	unlink($transferfile);
                   10087: 	&logthis("Userfile repcopy failed for $uri");
                   10088: 	return -1;
                   10089:     }
                   10090: # worked, rename the transfer file
                   10091:     rename($transferfile,$file);
1.607     raeburn  10092:     return 'ok';
1.481     raeburn  10093: }
                   10094: 
1.517     albertel 10095: sub tokenwrapper {
                   10096:     my $uri=shift;
1.980     raeburn  10097:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10098:     $uri=~s|^/||;
1.620     albertel 10099:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10100:     my $token=$1;
1.552     albertel 10101:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10102:     if ($udom && $uname && $file) {
                   10103: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10104:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10105:         my $homeserver = &homeserver($uname,$udom);
                   10106:         my $protocol = $protocol{$homeserver};
                   10107:         $protocol = 'http' if ($protocol ne 'https');
                   10108:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10109:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10110:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10111:     } else {
                   10112:         return '/adm/notfound.html';
                   10113:     }
                   10114: }
                   10115: 
1.828     www      10116: # call with reqtype HEAD: get last modification time
                   10117: # call with reqtype GET: get the file contents
                   10118: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10119: #
1.481     raeburn  10120: sub getuploaded {
                   10121:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10122:     $uri=~s/^\///;
1.980     raeburn  10123:     my $homeserver = &homeserver($cnum,$cdom);
                   10124:     my $protocol = $protocol{$homeserver};
                   10125:     $protocol = 'http' if ($protocol ne 'https');
                   10126:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10127:     my $ua=new LWP::UserAgent;
                   10128:     my $request=new HTTP::Request($reqtype,$uri);
                   10129:     my $response=$ua->request($request);
                   10130:     $$rtncode = $response->code;
1.482     albertel 10131:     if (! $response->is_success()) {
                   10132: 	return 'failed';
                   10133:     }      
                   10134:     if ($reqtype eq 'HEAD') {
1.486     www      10135: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10136:     } elsif ($reqtype eq 'GET') {
                   10137: 	$$info = $response->content;
1.472     albertel 10138:     }
1.482     albertel 10139:     return 'ok';
1.36      albertel 10140: }
                   10141: 
1.481     raeburn  10142: sub readfile {
                   10143:     my $file = shift;
                   10144:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10145:     my $fh;
                   10146:     open($fh,"<$file");
                   10147:     my $a='';
1.800     albertel 10148:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10149:     return $a;
                   10150: }
                   10151: 
1.36      albertel 10152: sub filelocation {
1.590     banghart 10153:     my ($dir,$file) = @_;
                   10154:     my $location;
                   10155:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10156: 
                   10157:     if ($file =~ m-^/adm/-) {
                   10158: 	$file=~s-^/adm/wrapper/-/-;
                   10159: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10160:     }
1.882     albertel 10161: 
1.590     banghart 10162:     if ($file=~m:^/~:) { # is a contruction space reference
                   10163:         $location = $file;
                   10164:         $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807     albertel 10165:     } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649     albertel 10166: 	# is a correct contruction space reference
                   10167:         $location = $file;
1.956     raeburn  10168:     } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
                   10169:         $location = $file;
1.609     banghart 10170:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10171:         my ($udom,$uname,$filename)=
1.811     albertel 10172:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10173:         my $home=&homeserver($uname,$udom);
                   10174:         my $is_me=0;
                   10175:         my @ids=&current_machine_ids();
                   10176:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10177:         if ($is_me) {
1.1117    foxr     10178:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10179:         } else {
                   10180:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10181:   	      $udom.'/'.$uname.'/'.$filename;
                   10182:         }
1.882     albertel 10183:     } elsif ($file =~ m-^/adm/-) {
                   10184: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10185:     } else {
                   10186:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
                   10187:         $file=~s:^/res/:/:;
                   10188:         if ( !( $file =~ m:^/:) ) {
                   10189:             $location = $dir. '/'.$file;
                   10190:         } else {
                   10191:             $location = '/home/httpd/html/res'.$file;
                   10192:         }
1.59      albertel 10193:     }
1.590     banghart 10194:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10195:     while ($location=~m{/\.\./}) {
                   10196: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10197: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10198: 	} else {
                   10199: 	    $location=~ s{/\.\./}{/}g;
                   10200: 	}
                   10201:     } #remove dir/..
1.590     banghart 10202:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10203:     return $location;
1.46      www      10204: }
1.36      albertel 10205: 
1.46      www      10206: sub hreflocation {
                   10207:     my ($dir,$file)=@_;
1.980     raeburn  10208:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10209: 	$file=filelocation($dir,$file);
1.700     albertel 10210:     } elsif ($file=~m-^/adm/-) {
                   10211: 	$file=~s-^/adm/wrapper/-/-;
                   10212: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10213:     }
                   10214:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10215: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807     albertel 10216:     } elsif ($file=~m-/home/($match_username)/public_html/-) {
                   10217: 	$file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666     albertel 10218:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811     albertel 10219: 	$file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666     albertel 10220: 	    -/uploaded/$1/$2/-x;
1.46      www      10221:     }
1.913     albertel 10222:     if ($file=~ m{^/userfiles/}) {
                   10223: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10224:     }
1.462     albertel 10225:     return $file;
1.465     albertel 10226: }
                   10227: 
                   10228: sub current_machine_domains {
1.853     albertel 10229:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10230: }
                   10231: 
                   10232: sub machine_domains {
                   10233:     my ($hostname) = @_;
1.465     albertel 10234:     my @domains;
1.838     albertel 10235:     my %hostname = &all_hostnames();
1.465     albertel 10236:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10237: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10238: 	if ($hostname eq $name) {
1.844     albertel 10239: 	    push(@domains,&host_domain($id));
1.465     albertel 10240: 	}
                   10241:     }
                   10242:     return @domains;
                   10243: }
                   10244: 
                   10245: sub current_machine_ids {
1.853     albertel 10246:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10247: }
                   10248: 
                   10249: sub machine_ids {
                   10250:     my ($hostname) = @_;
                   10251:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10252:     my @ids;
1.888     albertel 10253:     my %name_to_host = &all_names();
1.889     albertel 10254:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10255: 	return @{ $name_to_host{$hostname} };
                   10256:     }
                   10257:     return;
1.31      www      10258: }
                   10259: 
1.824     raeburn  10260: sub additional_machine_domains {
                   10261:     my @domains;
                   10262:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10263:     while( my $line = <$fh>) {
                   10264:         $line =~ s/\s//g;
                   10265:         push(@domains,$line);
                   10266:     }
                   10267:     return @domains;
                   10268: }
                   10269: 
                   10270: sub default_login_domain {
                   10271:     my $domain = $perlvar{'lonDefDomain'};
                   10272:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10273:     foreach my $posdom (&current_machine_domains(),
                   10274:                         &additional_machine_domains()) {
                   10275:         if (lc($posdom) eq lc($testdomain)) {
                   10276:             $domain=$posdom;
                   10277:             last;
                   10278:         }
                   10279:     }
                   10280:     return $domain;
                   10281: }
                   10282: 
1.31      www      10283: # ------------------------------------------------------------- Declutters URLs
                   10284: 
                   10285: sub declutter {
                   10286:     my $thisfn=shift;
1.569     albertel 10287:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10288:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10289:     $thisfn=~s/^\///;
1.697     albertel 10290:     $thisfn=~s|^adm/wrapper/||;
                   10291:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10292:     $thisfn=~s/^res\///;
1.1032    raeburn  10293:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10294:         $thisfn=~s/\?.+$//;
                   10295:     }
1.268     www      10296:     return $thisfn;
                   10297: }
                   10298: 
                   10299: # ------------------------------------------------------------- Clutter up URLs
                   10300: 
                   10301: sub clutter {
                   10302:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10303:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10304: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10305:        $thisfn='/res'.$thisfn; 
                   10306:     }
1.1031    raeburn  10307:     if ($thisfn !~m|^/adm|) {
                   10308: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10309: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10310: 	} else {
                   10311: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10312: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10313: 	    if ($embstyle eq 'ssi'
                   10314: 		|| ($embstyle eq 'hdn')
                   10315: 		|| ($embstyle eq 'rat')
                   10316: 		|| ($embstyle eq 'prv')
                   10317: 		|| ($embstyle eq 'ign')) {
                   10318: 		#do nothing with these
                   10319: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10320: 		|| ($embstyle eq 'emb')
                   10321: 		|| ($embstyle eq 'wrp')) {
                   10322: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10323: 	    } elsif ($embstyle eq 'unk'
                   10324: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10325: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10326: 	    } else {
1.718     www      10327: #		&logthis("Got a blank emb style");
1.695     albertel 10328: 	    }
1.694     albertel 10329: 	}
                   10330:     }
1.31      www      10331:     return $thisfn;
1.12      www      10332: }
                   10333: 
1.787     albertel 10334: sub clutter_with_no_wrapper {
                   10335:     my $uri = &clutter(shift);
                   10336:     if ($uri =~ m-^/adm/-) {
                   10337: 	$uri =~ s-^/adm/wrapper/-/-;
                   10338: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10339:     }
                   10340:     return $uri;
                   10341: }
                   10342: 
1.557     albertel 10343: sub freeze_escape {
                   10344:     my ($value)=@_;
                   10345:     if (ref($value)) {
                   10346: 	$value=&nfreeze($value);
                   10347: 	return '__FROZEN__'.&escape($value);
                   10348:     }
                   10349:     return &escape($value);
                   10350: }
                   10351: 
1.11      www      10352: 
1.557     albertel 10353: sub thaw_unescape {
                   10354:     my ($value)=@_;
                   10355:     if ($value =~ /^__FROZEN__/) {
                   10356: 	substr($value,0,10,undef);
                   10357: 	$value=&unescape($value);
                   10358: 	return &thaw($value);
                   10359:     }
                   10360:     return &unescape($value);
                   10361: }
                   10362: 
1.436     albertel 10363: sub correct_line_ends {
                   10364:     my ($result)=@_;
                   10365:     $$result =~s/\r\n/\n/mg;
                   10366:     $$result =~s/\r/\n/mg;
1.415     albertel 10367: }
1.1       albertel 10368: # ================================================================ Main Program
                   10369: 
1.184     www      10370: sub goodbye {
1.204     albertel 10371:    &logthis("Starting Shut down");
1.443     albertel 10372: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10373:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10374: #converted
1.599     albertel 10375: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10376:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10377: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10378: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10379: #1.1 only
1.870     albertel 10380: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10381: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10382: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10383: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10384:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10385:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10386:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10387:    &flushcourselogs();
                   10388:    &logthis("Shutting down");
                   10389: }
                   10390: 
1.852     albertel 10391: sub get_dns {
1.869     albertel 10392:     my ($url,$func,$ignore_cache) = @_;
                   10393:     if (!$ignore_cache) {
                   10394: 	my ($content,$cached)=
                   10395: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10396: 	if ($cached) {
                   10397: 	    &$func($content);
                   10398: 	    return;
                   10399: 	}
                   10400:     }
                   10401: 
                   10402:     my %alldns;
1.852     albertel 10403:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10404:     foreach my $dns (<$config>) {
                   10405: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10406:         my $line = $1;
                   10407:         my ($host,$protocol) = split(/:/,$line);
                   10408:         if ($protocol ne 'https') {
                   10409:             $protocol = 'http';
                   10410:         }
                   10411: 	$alldns{$host} = $protocol;
1.869     albertel 10412:     }
                   10413:     while (%alldns) {
                   10414: 	my ($dns) = keys(%alldns);
1.852     albertel 10415: 	my $ua=new LWP::UserAgent;
1.979     raeburn  10416: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10417: 	my $response=$ua->request($request);
1.979     raeburn  10418:         delete($alldns{$dns});
1.852     albertel 10419: 	next if ($response->is_error());
                   10420: 	my @content = split("\n",$response->content);
1.869     albertel 10421: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10422: 	&$func(\@content);
1.869     albertel 10423: 	return;
1.852     albertel 10424:     }
                   10425:     close($config);
1.871     albertel 10426:     my $which = (split('/',$url))[3];
                   10427:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10428:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10429:     my @content = <$config>;
                   10430:     &$func(\@content);
                   10431:     return;
1.852     albertel 10432: }
1.327     albertel 10433: # ------------------------------------------------------------ Read domain file
                   10434: {
1.852     albertel 10435:     my $loaded;
1.846     albertel 10436:     my %domain;
                   10437: 
1.852     albertel 10438:     sub parse_domain_tab {
                   10439: 	my ($lines) = @_;
                   10440: 	foreach my $line (@$lines) {
                   10441: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10442: 
1.846     albertel 10443: 	    chomp($line);
1.852     albertel 10444: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10445: 	    my %this_domain;
                   10446: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10447: 			       'lang_def', 'city', 'longi', 'lati',
                   10448: 			       'primary') {
                   10449: 		$this_domain{$field} = shift(@elements);
                   10450: 	    }
                   10451: 	    $domain{$name} = \%this_domain;
1.852     albertel 10452: 	}
                   10453:     }
1.864     albertel 10454: 
                   10455:     sub reset_domain_info {
                   10456: 	undef($loaded);
                   10457: 	undef(%domain);
                   10458:     }
                   10459: 
1.852     albertel 10460:     sub load_domain_tab {
1.869     albertel 10461: 	my ($ignore_cache) = @_;
                   10462: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10463: 	my $fh;
                   10464: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10465: 	    my @lines = <$fh>;
                   10466: 	    &parse_domain_tab(\@lines);
1.448     albertel 10467: 	}
1.852     albertel 10468: 	close($fh);
                   10469: 	$loaded = 1;
1.327     albertel 10470:     }
1.846     albertel 10471: 
                   10472:     sub domain {
1.852     albertel 10473: 	&load_domain_tab() if (!$loaded);
                   10474: 
1.846     albertel 10475: 	my ($name,$what) = @_;
                   10476: 	return if ( !exists($domain{$name}) );
                   10477: 
                   10478: 	if (!$what) {
                   10479: 	    return $domain{$name}{'description'};
                   10480: 	}
                   10481: 	return $domain{$name}{$what};
                   10482:     }
1.974     raeburn  10483: 
                   10484:     sub domain_info {
                   10485:         &load_domain_tab() if (!$loaded);
                   10486:         return %domain;
                   10487:     }
                   10488: 
1.327     albertel 10489: }
                   10490: 
                   10491: 
1.1       albertel 10492: # ------------------------------------------------------------- Read hosts file
                   10493: {
1.838     albertel 10494:     my %hostname;
1.844     albertel 10495:     my %hostdom;
1.845     albertel 10496:     my %libserv;
1.852     albertel 10497:     my $loaded;
1.888     albertel 10498:     my %name_to_host;
1.1074    raeburn  10499:     my %internetdom;
1.1107    raeburn  10500:     my %LC_dns_serv;
1.852     albertel 10501: 
                   10502:     sub parse_hosts_tab {
                   10503: 	my ($file) = @_;
                   10504: 	foreach my $configline (@$file) {
                   10505: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10506:             chomp($configline);
                   10507: 	    if ($configline =~ /^\^/) {
                   10508:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10509:                     $LC_dns_serv{$1} = 1;
                   10510:                 }
                   10511:                 next;
                   10512:             }
1.1074    raeburn  10513: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10514: 	    $name=~s/\s//g;
                   10515: 	    if ($id && $domain && $role && $name) {
                   10516: 		$hostname{$id}=$name;
1.888     albertel 10517: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10518: 		$hostdom{$id}=$domain;
                   10519: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10520:                 if (defined($protocol)) {
                   10521:                     if ($protocol eq 'https') {
                   10522:                         $protocol{$id} = $protocol;
                   10523:                     } else {
                   10524:                         $protocol{$id} = 'http'; 
                   10525:                     }
1.968     raeburn  10526:                 } else {
1.969     raeburn  10527:                     $protocol{$id} = 'http';
1.968     raeburn  10528:                 }
1.1074    raeburn  10529:                 if (defined($intdom)) {
                   10530:                     $internetdom{$id} = $intdom;
                   10531:                 }
1.852     albertel 10532: 	    }
                   10533: 	}
                   10534:     }
1.864     albertel 10535:     
                   10536:     sub reset_hosts_info {
1.897     albertel 10537: 	&purge_remembered();
1.864     albertel 10538: 	&reset_domain_info();
                   10539: 	&reset_hosts_ip_info();
1.892     albertel 10540: 	undef(%name_to_host);
1.864     albertel 10541: 	undef(%hostname);
                   10542: 	undef(%hostdom);
                   10543: 	undef(%libserv);
                   10544: 	undef($loaded);
                   10545:     }
1.1       albertel 10546: 
1.852     albertel 10547:     sub load_hosts_tab {
1.869     albertel 10548: 	my ($ignore_cache) = @_;
                   10549: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10550: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10551: 	my @config = <$config>;
                   10552: 	&parse_hosts_tab(\@config);
                   10553: 	close($config);
                   10554: 	$loaded=1;
1.1       albertel 10555:     }
1.852     albertel 10556: 
1.838     albertel 10557:     sub hostname {
1.852     albertel 10558: 	&load_hosts_tab() if (!$loaded);
                   10559: 
1.838     albertel 10560: 	my ($lonid) = @_;
                   10561: 	return $hostname{$lonid};
                   10562:     }
1.845     albertel 10563: 
1.838     albertel 10564:     sub all_hostnames {
1.852     albertel 10565: 	&load_hosts_tab() if (!$loaded);
                   10566: 
1.838     albertel 10567: 	return %hostname;
                   10568:     }
1.845     albertel 10569: 
1.888     albertel 10570:     sub all_names {
                   10571: 	&load_hosts_tab() if (!$loaded);
                   10572: 
                   10573: 	return %name_to_host;
                   10574:     }
                   10575: 
1.974     raeburn  10576:     sub all_host_domain {
                   10577:         &load_hosts_tab() if (!$loaded);
                   10578:         return %hostdom;
                   10579:     }
                   10580: 
1.845     albertel 10581:     sub is_library {
1.852     albertel 10582: 	&load_hosts_tab() if (!$loaded);
                   10583: 
1.845     albertel 10584: 	return exists($libserv{$_[0]});
                   10585:     }
                   10586: 
                   10587:     sub all_library {
1.852     albertel 10588: 	&load_hosts_tab() if (!$loaded);
                   10589: 
1.845     albertel 10590: 	return %libserv;
                   10591:     }
                   10592: 
1.1062    droeschl 10593:     sub unique_library {
                   10594: 	#2x reverse removes all hostnames that appear more than once
                   10595:         my %unique = reverse &all_library();
                   10596:         return reverse %unique;
                   10597:     }
                   10598: 
1.841     albertel 10599:     sub get_servers {
1.852     albertel 10600: 	&load_hosts_tab() if (!$loaded);
                   10601: 
1.841     albertel 10602: 	my ($domain,$type) = @_;
                   10603: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10604: 	                                          : %hostname;
                   10605: 	my %result;
1.842     albertel 10606: 	if (ref($domain) eq 'ARRAY') {
                   10607: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10608: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10609: 		    $result{$host} = $hostname;
                   10610: 		}
                   10611: 	    }
                   10612: 	} else {
                   10613: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10614: 		if ($hostdom{$host} eq $domain) {
                   10615: 		    $result{$host} = $hostname;
                   10616: 		}
1.841     albertel 10617: 	    }
                   10618: 	}
                   10619: 	return %result;
                   10620:     }
1.845     albertel 10621: 
1.1062    droeschl 10622:     sub get_unique_servers {
                   10623:         my %unique = reverse &get_servers(@_);
                   10624: 	return reverse %unique;
                   10625:     }
                   10626: 
1.844     albertel 10627:     sub host_domain {
1.852     albertel 10628: 	&load_hosts_tab() if (!$loaded);
                   10629: 
1.844     albertel 10630: 	my ($lonid) = @_;
                   10631: 	return $hostdom{$lonid};
                   10632:     }
                   10633: 
1.841     albertel 10634:     sub all_domains {
1.852     albertel 10635: 	&load_hosts_tab() if (!$loaded);
                   10636: 
1.841     albertel 10637: 	my %seen;
                   10638: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10639: 	return @uniq;
                   10640:     }
1.1074    raeburn  10641: 
                   10642:     sub internet_dom {
                   10643:         &load_hosts_tab() if (!$loaded);
                   10644: 
                   10645:         my ($lonid) = @_;
                   10646:         return $internetdom{$lonid};
                   10647:     }
1.1107    raeburn  10648: 
                   10649:     sub is_LC_dns {
                   10650:         &load_hosts_tab() if (!$loaded);
                   10651: 
                   10652:         my ($hostname) = @_;
                   10653:         return exists($LC_dns_serv{$hostname});
                   10654:     }
                   10655: 
1.1       albertel 10656: }
                   10657: 
1.847     albertel 10658: { 
                   10659:     my %iphost;
1.856     albertel 10660:     my %name_to_ip;
                   10661:     my %lonid_to_ip;
1.869     albertel 10662: 
1.847     albertel 10663:     sub get_hosts_from_ip {
                   10664: 	my ($ip) = @_;
                   10665: 	my %iphosts = &get_iphost();
                   10666: 	if (ref($iphosts{$ip})) {
                   10667: 	    return @{$iphosts{$ip}};
                   10668: 	}
                   10669: 	return;
1.839     albertel 10670:     }
1.864     albertel 10671:     
                   10672:     sub reset_hosts_ip_info {
                   10673: 	undef(%iphost);
                   10674: 	undef(%name_to_ip);
                   10675: 	undef(%lonid_to_ip);
                   10676:     }
1.856     albertel 10677: 
                   10678:     sub get_host_ip {
                   10679: 	my ($lonid) = @_;
                   10680: 	if (exists($lonid_to_ip{$lonid})) {
                   10681: 	    return $lonid_to_ip{$lonid};
                   10682: 	}
                   10683: 	my $name=&hostname($lonid);
                   10684:    	my $ip = gethostbyname($name);
                   10685: 	return if (!$ip || length($ip) ne 4);
                   10686: 	$ip=inet_ntoa($ip);
                   10687: 	$name_to_ip{$name}   = $ip;
                   10688: 	$lonid_to_ip{$lonid} = $ip;
                   10689: 	return $ip;
                   10690:     }
1.847     albertel 10691:     
                   10692:     sub get_iphost {
1.869     albertel 10693: 	my ($ignore_cache) = @_;
1.894     albertel 10694: 
1.869     albertel 10695: 	if (!$ignore_cache) {
                   10696: 	    if (%iphost) {
                   10697: 		return %iphost;
                   10698: 	    }
                   10699: 	    my ($ip_info,$cached)=
                   10700: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10701: 	    if ($cached) {
                   10702: 		%iphost      = %{$ip_info->[0]};
                   10703: 		%name_to_ip  = %{$ip_info->[1]};
                   10704: 		%lonid_to_ip = %{$ip_info->[2]};
                   10705: 		return %iphost;
                   10706: 	    }
                   10707: 	}
1.894     albertel 10708: 
                   10709: 	# get yesterday's info for fallback
                   10710: 	my %old_name_to_ip;
                   10711: 	my ($ip_info,$cached)=
                   10712: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10713: 	if ($cached) {
                   10714: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10715: 	}
                   10716: 
1.888     albertel 10717: 	my %name_to_host = &all_names();
                   10718: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10719: 	    my $ip;
                   10720: 	    if (!exists($name_to_ip{$name})) {
                   10721: 		$ip = gethostbyname($name);
                   10722: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10723: 		    if (defined($old_name_to_ip{$name})) {
                   10724: 			$ip = $old_name_to_ip{$name};
                   10725: 			&logthis("Can't find $name defaulting to old $ip");
                   10726: 		    } else {
                   10727: 			&logthis("Name $name no IP found");
                   10728: 			next;
                   10729: 		    }
                   10730: 		} else {
                   10731: 		    $ip=inet_ntoa($ip);
1.847     albertel 10732: 		}
                   10733: 		$name_to_ip{$name} = $ip;
                   10734: 	    } else {
                   10735: 		$ip = $name_to_ip{$name};
1.653     albertel 10736: 	    }
1.888     albertel 10737: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10738: 		$lonid_to_ip{$id} = $ip;
                   10739: 	    }
                   10740: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10741: 	}
1.869     albertel 10742: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10743: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10744: 				      48*60*60);
1.869     albertel 10745: 
1.847     albertel 10746: 	return %iphost;
1.598     albertel 10747:     }
                   10748: 
1.992     raeburn  10749:     #
                   10750:     #  Given a DNS returns the loncapa host name for that DNS 
                   10751:     # 
                   10752:     sub host_from_dns {
                   10753:         my ($dns) = @_;
                   10754:         my @hosts;
                   10755:         my $ip;
                   10756: 
1.993     raeburn  10757:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10758:             $ip = $name_to_ip{$dns};
                   10759:         }
                   10760:         if (!$ip) {
                   10761:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10762:             if (length($ip) == 4) { 
                   10763: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10764:             }
                   10765:         }
                   10766:         if ($ip) {
                   10767: 	    @hosts = get_hosts_from_ip($ip);
                   10768: 	    return $hosts[0];
                   10769:         }
                   10770:         return undef;
1.986     foxr     10771:     }
1.992     raeburn  10772: 
1.1074    raeburn  10773:     sub get_internet_names {
                   10774:         my ($lonid) = @_;
                   10775:         return if ($lonid eq '');
                   10776:         my ($idnref,$cached)=
                   10777:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10778:         if ($cached) {
                   10779:             return $idnref;
                   10780:         }
                   10781:         my $ip = &get_host_ip($lonid);
                   10782:         my @hosts = &get_hosts_from_ip($ip);
                   10783:         my %iphost = &get_iphost();
                   10784:         my (@idns,%seen);
                   10785:         foreach my $id (@hosts) {
                   10786:             my $dom = &host_domain($id);
                   10787:             my $prim_id = &domain($dom,'primary');
                   10788:             my $prim_ip = &get_host_ip($prim_id);
                   10789:             next if ($seen{$prim_ip});
                   10790:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10791:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10792:                     my $intdom = &internet_dom($id);
                   10793:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10794:                         push(@idns,$intdom);
                   10795:                     }
                   10796:                 }
                   10797:             }
                   10798:             $seen{$prim_ip} = 1;
                   10799:         }
                   10800:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10801:     }
                   10802: 
1.986     foxr     10803: }
                   10804: 
1.1079    raeburn  10805: sub all_loncaparevs {
                   10806:     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);
                   10807: }
                   10808: 
1.862     albertel 10809: BEGIN {
                   10810: 
                   10811: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10812:     unless ($readit) {
                   10813: {
                   10814:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10815:     %perlvar = (%perlvar,%{$configvars});
                   10816: }
                   10817: 
                   10818: 
1.1       albertel 10819: # ------------------------------------------------------ Read spare server file
                   10820: {
1.448     albertel 10821:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10822: 
                   10823:     while (my $configline=<$config>) {
                   10824:        chomp($configline);
1.284     matthew  10825:        if ($configline) {
1.784     albertel 10826: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10827: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10828: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10829:        }
                   10830:     }
1.448     albertel 10831:     close($config);
1.1       albertel 10832: }
1.11      www      10833: # ------------------------------------------------------------ Read permissions
                   10834: {
1.448     albertel 10835:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10836: 
                   10837:     while (my $configline=<$config>) {
1.448     albertel 10838: 	chomp($configline);
                   10839: 	if ($configline) {
                   10840: 	    my ($role,$perm)=split(/ /,$configline);
                   10841: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10842: 	}
1.11      www      10843:     }
1.448     albertel 10844:     close($config);
1.11      www      10845: }
                   10846: 
                   10847: # -------------------------------------------- Read plain texts for permissions
                   10848: {
1.448     albertel 10849:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10850: 
                   10851:     while (my $configline=<$config>) {
1.448     albertel 10852: 	chomp($configline);
                   10853: 	if ($configline) {
1.742     raeburn  10854: 	    my ($short,@plain)=split(/:/,$configline);
                   10855:             %{$prp{$short}} = ();
                   10856: 	    if (@plain > 0) {
                   10857:                 $prp{$short}{'std'} = $plain[0];
                   10858:                 for (my $i=1; $i<@plain; $i++) {
                   10859:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10860:                 }
                   10861:             }
1.448     albertel 10862: 	}
1.135     www      10863:     }
1.448     albertel 10864:     close($config);
1.135     www      10865: }
                   10866: 
                   10867: # ---------------------------------------------------------- Read package table
                   10868: {
1.448     albertel 10869:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10870: 
                   10871:     while (my $configline=<$config>) {
1.483     albertel 10872: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10873: 	chomp($configline);
                   10874: 	my ($short,$plain)=split(/:/,$configline);
                   10875: 	my ($pack,$name)=split(/\&/,$short);
                   10876: 	if ($plain ne '') {
                   10877: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10878: 	    $packagetab{$short}=$plain; 
                   10879: 	}
1.11      www      10880:     }
1.448     albertel 10881:     close($config);
1.329     matthew  10882: }
                   10883: 
1.1073    raeburn  10884: # ---------------------------------------------------------- Read loncaparev table
                   10885: {
                   10886:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10887:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10888:             while (my $configline=<$config>) {
                   10889:                 chomp($configline);
                   10890:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10891:                 $loncaparevs{$hostid}=$loncaparev;
                   10892:             }
                   10893:             close($config);
                   10894:         }
                   10895:     }
                   10896: }
                   10897: 
1.1074    raeburn  10898: # ---------------------------------------------------------- Read serverhostID table
                   10899: {
                   10900:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10901:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10902:             while (my $configline=<$config>) {
                   10903:                 chomp($configline);
                   10904:                 my ($name,$id)=split(/:/,$configline);
                   10905:                 $serverhomeIDs{$name}=$id;
                   10906:             }
                   10907:             close($config);
                   10908:         }
                   10909:     }
                   10910: }
                   10911: 
1.1079    raeburn  10912: {
                   10913:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10914:     if (-e $file) {
                   10915:         my $parser = HTML::LCParser->new($file);
                   10916:         while (my $token = $parser->get_token()) {
                   10917:             if ($token->[0] eq 'S') {
                   10918:                 my $item = $token->[1];
                   10919:                 my $name = $token->[2]{'name'};
                   10920:                 my $value = $token->[2]{'value'};
                   10921:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10922:                     my $release = $parser->get_text();
                   10923:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10924:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10925:                 }
                   10926:             }
                   10927:         }
                   10928:     }
1.1073    raeburn  10929: }
                   10930: 
1.329     matthew  10931: # ------------- set up temporary directory
                   10932: {
1.1117    foxr     10933:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  10934: 
1.11      www      10935: }
                   10936: 
1.794     albertel 10937: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   10938: 				'compress_threshold'=> 20_000,
                   10939:  			        });
1.185     www      10940: 
1.281     www      10941: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      10942: $dumpcount=0;
1.958     www      10943: $locknum=0;
1.22      www      10944: 
1.163     harris41 10945: &logtouch();
1.672     albertel 10946: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      10947: $readit=1;
1.564     albertel 10948:     {
                   10949: 	use integer;
                   10950: 	my $test=(2**32)+1;
1.568     albertel 10951: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 10952: 	&logthis(" Detected 64bit platform ($_64bit)");
                   10953:     }
1.195     www      10954: }
1.1       albertel 10955: }
1.179     www      10956: 
1.1       albertel 10957: 1;
1.191     harris41 10958: __END__
                   10959: 
1.243     albertel 10960: =pod
                   10961: 
1.191     harris41 10962: =head1 NAME
                   10963: 
1.243     albertel 10964: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 10965: 
                   10966: =head1 SYNOPSIS
                   10967: 
1.243     albertel 10968: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 10969: 
                   10970:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   10971: 
1.243     albertel 10972: Common parameters:
                   10973: 
                   10974: =over 4
                   10975: 
                   10976: =item *
                   10977: 
                   10978: $uname : an internal username (if $cname expecting a course Id specifically)
                   10979: 
                   10980: =item *
                   10981: 
                   10982: $udom : a domain (if $cdom expecting a course's domain specifically)
                   10983: 
                   10984: =item *
                   10985: 
                   10986: $symb : a resource instance identifier
                   10987: 
                   10988: =item *
                   10989: 
                   10990: $namespace : the name of a .db file that contains the data needed or
                   10991: being set.
                   10992: 
                   10993: =back
                   10994: 
1.394     bowersj2 10995: =head1 OVERVIEW
1.191     harris41 10996: 
1.394     bowersj2 10997: lonnet provides subroutines which interact with the
                   10998: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   10999: about classes, users, and resources.
1.243     albertel 11000: 
                   11001: For many of these objects you can also use this to store data about
                   11002: them or modify them in various ways.
1.191     harris41 11003: 
1.394     bowersj2 11004: =head2 Symbs
1.191     harris41 11005: 
1.394     bowersj2 11006: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11007: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11008: map, the resource number of the resource in the map, and the URL of
                   11009: the resource itself. The latter is somewhat redundant, but might help
                   11010: if maps change.
                   11011: 
                   11012: An example is
                   11013: 
                   11014:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11015: 
                   11016: The respective map entry is
                   11017: 
                   11018:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11019:   title="Problem 2">
                   11020:  </resource>
                   11021: 
                   11022: Symbs are used by the random number generator, as well as to store and
                   11023: restore data specific to a certain instance of for example a problem.
                   11024: 
                   11025: =head2 Storing And Retrieving Data
                   11026: 
                   11027: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11028: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11029: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11030: is is the non-critical message twin of cstore. These functions are for
                   11031: handlers to store a perl hash to a user's permanent data space in an
                   11032: easy manner, and to retrieve it again on another call. It is expected
                   11033: that a handler would use this once at the beginning to retrieve data,
                   11034: and then again once at the end to send only the new data back.
                   11035: 
                   11036: The data is stored in the user's data directory on the user's
                   11037: homeserver under the ID of the course.
                   11038: 
                   11039: The hash that is returned by restore will have all of the previous
                   11040: value for all of the elements of the hash.
                   11041: 
                   11042: Example:
                   11043: 
                   11044:  #creating a hash
                   11045:  my %hash;
                   11046:  $hash{'foo'}='bar';
                   11047: 
                   11048:  #storing it
                   11049:  &Apache::lonnet::cstore(\%hash);
                   11050: 
                   11051:  #changing a value
                   11052:  $hash{'foo'}='notbar';
                   11053: 
                   11054:  #adding a new value
                   11055:  $hash{'bar'}='foo';
                   11056:  &Apache::lonnet::cstore(\%hash);
                   11057: 
                   11058:  #retrieving the hash
                   11059:  my %history=&Apache::lonnet::restore();
                   11060: 
                   11061:  #print the hash
                   11062:  foreach my $key (sort(keys(%history))) {
                   11063:    print("\%history{$key} = $history{$key}");
                   11064:  }
                   11065: 
                   11066: Will print out:
1.191     harris41 11067: 
1.394     bowersj2 11068:  %history{1:foo} = bar
                   11069:  %history{1:keys} = foo:timestamp
                   11070:  %history{1:timestamp} = 990455579
                   11071:  %history{2:bar} = foo
                   11072:  %history{2:foo} = notbar
                   11073:  %history{2:keys} = foo:bar:timestamp
                   11074:  %history{2:timestamp} = 990455580
                   11075:  %history{bar} = foo
                   11076:  %history{foo} = notbar
                   11077:  %history{timestamp} = 990455580
                   11078:  %history{version} = 2
                   11079: 
                   11080: Note that the special hash entries C<keys>, C<version> and
                   11081: C<timestamp> were added to the hash. C<version> will be equal to the
                   11082: total number of versions of the data that have been stored. The
                   11083: C<timestamp> attribute will be the UNIX time the hash was
                   11084: stored. C<keys> is available in every historical section to list which
                   11085: keys were added or changed at a specific historical revision of a
                   11086: hash.
                   11087: 
                   11088: B<Warning>: do not store the hash that restore returns directly. This
                   11089: will cause a mess since it will restore the historical keys as if the
                   11090: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11091: 
1.394     bowersj2 11092: Calling convention:
1.191     harris41 11093: 
1.394     bowersj2 11094:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11095:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11096: 
1.394     bowersj2 11097: For more detailed information, see lonnet specific documentation.
1.191     harris41 11098: 
1.394     bowersj2 11099: =head1 RETURN MESSAGES
1.191     harris41 11100: 
1.394     bowersj2 11101: =over 4
1.191     harris41 11102: 
1.394     bowersj2 11103: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11104: 
1.394     bowersj2 11105: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11106: when the connection is brought back up
1.191     harris41 11107: 
1.394     bowersj2 11108: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11109: for later delivery
1.191     harris41 11110: 
1.967     bisitz   11111: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11112: 
1.394     bowersj2 11113: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11114: that was requested
1.191     harris41 11115: 
1.243     albertel 11116: =back
1.191     harris41 11117: 
1.243     albertel 11118: =head1 PUBLIC SUBROUTINES
1.191     harris41 11119: 
1.243     albertel 11120: =head2 Session Environment Functions
1.191     harris41 11121: 
1.243     albertel 11122: =over 4
1.191     harris41 11123: 
1.394     bowersj2 11124: =item * 
                   11125: X<appenv()>
1.949     raeburn  11126: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11127: the user envirnoment file, and will be restored for each access this
1.620     albertel 11128: user makes during this session, also modifies the %env for the current
1.949     raeburn  11129: process. Optional rolesarrayref - if defined contains a reference to an array
                   11130: of roles which are exempt from the restriction on modifying user.role entries 
                   11131: in the user's environment.db and in %env.    
1.191     harris41 11132: 
                   11133: =item *
1.394     bowersj2 11134: X<delenv()>
1.987     raeburn  11135: B<delenv($delthis,$regexp)>: removes all items from the session
                   11136: environment file that begin with $delthis. If the 
                   11137: optional second arg - $regexp - is true, $delthis is treated as a 
                   11138: regular expression, otherwise \Q$delthis\E is used. 
                   11139: The values are also deleted from the current processes %env.
1.191     harris41 11140: 
1.795     albertel 11141: =item * get_env_multiple($name) 
                   11142: 
                   11143: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11144: values may be defined and end up as an array ref.
                   11145: 
                   11146: returns an array of values
                   11147: 
1.243     albertel 11148: =back
                   11149: 
                   11150: =head2 User Information
1.191     harris41 11151: 
1.243     albertel 11152: =over 4
1.191     harris41 11153: 
                   11154: =item *
1.394     bowersj2 11155: X<queryauthenticate()>
                   11156: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11157: authentication scheme
                   11158: 
                   11159: =item *
1.394     bowersj2 11160: X<authenticate()>
1.1073    raeburn  11161: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11162: authenticate user from domain's lib servers (first use the current
                   11163: one). C<$upass> should be the users password.
1.1073    raeburn  11164: $checkdefauth is optional (value is 1 if a check should be made to
                   11165:    authenticate user using default authentication method, and allow
                   11166:    account creation if username does not have account in the domain).
                   11167: $clientcancheckhost is optional (value is 1 if checking whether the
                   11168:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11169: 
                   11170: =item *
1.394     bowersj2 11171: X<homeserver()>
                   11172: B<homeserver($uname,$udom)>: find the server which has
                   11173: the user's directory and files (there must be only one), this caches
                   11174: the answer, and also caches if there is a borken connection.
1.191     harris41 11175: 
                   11176: =item *
1.394     bowersj2 11177: X<idget()>
                   11178: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11179: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11180: username, and only 1 username per ID in a specific domain) (returns
                   11181: hash: id=>name,id=>name)
1.191     harris41 11182: 
                   11183: =item *
1.394     bowersj2 11184: X<idrget()>
                   11185: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11186: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11187: 
                   11188: =item *
1.394     bowersj2 11189: X<idput()>
                   11190: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11191: 
                   11192: =item *
1.394     bowersj2 11193: X<rolesinit()>
                   11194: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 11195: 
                   11196: =item *
1.551     albertel 11197: X<getsection()>
                   11198: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11199: course $cname, return section name/number or '' for "not in course"
                   11200: and '-1' for "no section"
                   11201: 
                   11202: =item *
1.394     bowersj2 11203: X<userenvironment()>
                   11204: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11205: passed in @what from the requested user's environment, returns a hash
                   11206: 
1.858     raeburn  11207: =item * 
                   11208: X<userlog_query()>
1.859     albertel 11209: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11210: activity.log file. %filters defines filters applied when parsing the
                   11211: log file. These can be start or end timestamps, or the type of action
                   11212: - log to look for Login or Logout events, check for Checkin or
                   11213: Checkout, role for role selection. The response is in the form
                   11214: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11215: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11216: 
1.243     albertel 11217: =back
                   11218: 
                   11219: =head2 User Roles
                   11220: 
                   11221: =over 4
                   11222: 
                   11223: =item *
                   11224: 
1.810     raeburn  11225: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11226:  F: full access
                   11227:  U,I,K: authentication modes (cxx only)
                   11228:  '': forbidden
                   11229:  1: user needs to choose course
                   11230:  2: browse allowed
1.766     albertel 11231:  A: passphrase authentication needed
1.243     albertel 11232: 
                   11233: =item *
                   11234: 
                   11235: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11236: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11237: and course level
                   11238: 
                   11239: =item *
                   11240: 
1.988     raeburn  11241: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11242: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11243: $type is Course (default) or Community.
1.988     raeburn  11244: If $forcedefault evaluates to true, text returned will be default 
                   11245: text for $type. Otherwise, if this is a course, the text returned 
                   11246: will be a custom name for the role (if defined in the course's 
                   11247: environment).  If no custom name is defined the default is returned.
                   11248:    
1.832     raeburn  11249: =item *
                   11250: 
1.935     raeburn  11251: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11252: All arguments are optional. Returns a hash of a roles, either for
                   11253: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11254: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11255: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11256: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11257: For each key, value is set to colon-separated start and end times for
                   11258: the role.  If no username and domain are specified, will default to
1.934     raeburn  11259: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11260: of role statuses (active, future or previous), roles 
                   11261: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11262: to restrict the list of roles reported. If no array ref is 
                   11263: provided for types, will default to return only active roles.
1.834     albertel 11264: 
1.243     albertel 11265: =back
                   11266: 
                   11267: =head2 User Modification
                   11268: 
                   11269: =over 4
                   11270: 
                   11271: =item *
                   11272: 
1.957     raeburn  11273: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11274: user for the level given by URL.  Optional start and end dates (leave empty
                   11275: string or zero for "no date")
1.191     harris41 11276: 
                   11277: =item *
                   11278: 
1.243     albertel 11279: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11280: change a users, password, possible return values are: ok,
                   11281: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11282: refused
1.191     harris41 11283: 
                   11284: =item *
                   11285: 
1.243     albertel 11286: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11287: 
                   11288: =item *
                   11289: 
1.1058    raeburn  11290: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11291:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11292: 
                   11293: will update user information (firstname,middlename,lastname,generation,
                   11294: permanentemail), and if forceid is true, student/employee ID also.
                   11295: A user's institutional affiliation(s) can also be updated.
                   11296: User information fields will not be overwritten with empty entries 
                   11297: unless the field is included in the $candelete array reference.
                   11298: This array is included when a single user is modified via "Manage Users",
                   11299: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11300: 
                   11301: =item *
                   11302: 
1.286     matthew  11303: modifystudent
                   11304: 
1.957     raeburn  11305: modify a student's enrollment and identification information.
1.286     matthew  11306: The course id is resolved based on the current users environment.  
                   11307: This means the envoking user must be a course coordinator or otherwise
                   11308: associated with a course.
                   11309: 
1.297     matthew  11310: This call is essentially a wrapper for lonnet::modifyuser and
                   11311: lonnet::modify_student_enrollment
1.286     matthew  11312: 
                   11313: Inputs: 
                   11314: 
                   11315: =over 4
                   11316: 
1.957     raeburn  11317: =item B<$udom> Student's loncapa domain
1.286     matthew  11318: 
1.957     raeburn  11319: =item B<$uname> Student's loncapa login name
1.286     matthew  11320: 
1.964     bisitz   11321: =item B<$uid> Student/Employee ID
1.286     matthew  11322: 
1.957     raeburn  11323: =item B<$umode> Student's authentication mode
1.286     matthew  11324: 
1.957     raeburn  11325: =item B<$upass> Student's password
1.286     matthew  11326: 
1.957     raeburn  11327: =item B<$first> Student's first name
1.286     matthew  11328: 
1.957     raeburn  11329: =item B<$middle> Student's middle name
1.286     matthew  11330: 
1.957     raeburn  11331: =item B<$last> Student's last name
1.286     matthew  11332: 
1.957     raeburn  11333: =item B<$gene> Student's generation
1.286     matthew  11334: 
1.957     raeburn  11335: =item B<$usec> Student's section in course
1.286     matthew  11336: 
                   11337: =item B<$end> Unix time of the roles expiration
                   11338: 
                   11339: =item B<$start> Unix time of the roles start date
                   11340: 
                   11341: =item B<$forceid> If defined, allow $uid to be changed
                   11342: 
                   11343: =item B<$desiredhome> server to use as home server for student
                   11344: 
1.957     raeburn  11345: =item B<$email> Student's permanent e-mail address
                   11346: 
                   11347: =item B<$type> Type of enrollment (auto or manual)
                   11348: 
1.963     raeburn  11349: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11350: 
                   11351: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11352: 
1.963     raeburn  11353: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11354: 
1.963     raeburn  11355: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11356: 
1.963     raeburn  11357: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11358: 
1.286     matthew  11359: =back
1.297     matthew  11360: 
                   11361: =item *
                   11362: 
                   11363: modify_student_enrollment
                   11364: 
                   11365: Change a students enrollment status in a class.  The environment variable
                   11366: 'role.request.course' must be defined for this function to proceed.
                   11367: 
                   11368: Inputs:
                   11369: 
                   11370: =over 4
                   11371: 
                   11372: =item $udom, students domain
                   11373: 
                   11374: =item $uname, students name
                   11375: 
                   11376: =item $uid, students user id
                   11377: 
                   11378: =item $first, students first name
                   11379: 
                   11380: =item $middle
                   11381: 
                   11382: =item $last
                   11383: 
                   11384: =item $gene
                   11385: 
                   11386: =item $usec
                   11387: 
                   11388: =item $end
                   11389: 
                   11390: =item $start
                   11391: 
1.957     raeburn  11392: =item $type
                   11393: 
                   11394: =item $locktype
                   11395: 
                   11396: =item $cid
                   11397: 
                   11398: =item $selfenroll
                   11399: 
                   11400: =item $context
                   11401: 
1.297     matthew  11402: =back
                   11403: 
1.191     harris41 11404: 
                   11405: =item *
                   11406: 
1.243     albertel 11407: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11408: custom role; give a custom role to a user for the level given by URL.  Specify
                   11409: name and domain of role author, and role name
1.191     harris41 11410: 
                   11411: =item *
                   11412: 
1.243     albertel 11413: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11414: 
                   11415: =item *
                   11416: 
1.243     albertel 11417: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11418: 
                   11419: =back
                   11420: 
                   11421: =head2 Course Infomation
                   11422: 
                   11423: =over 4
1.191     harris41 11424: 
                   11425: =item *
                   11426: 
1.1118    foxr     11427: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11428: specified course id, including all environment settings for the
                   11429: course, the description of the course will be in the hash under the
                   11430: key 'description'
1.191     harris41 11431: 
1.1118    foxr     11432: $options is an optional parameter that if supplied is a hash reference that controls
                   11433: what how this function works.  It has the following key/values:
                   11434: 
                   11435: =over 4
                   11436: 
                   11437: =item freshen_cache
                   11438: 
                   11439: If defined, and the environment cache for the course is valid, it is 
                   11440: returned in the returned hash.
                   11441: 
                   11442: =item one_time
                   11443: 
                   11444: If defined, the last cache time is set to _now_
                   11445: 
                   11446: =item user
                   11447: 
                   11448: If defined, the supplied username is used instead of the current user.
                   11449: 
                   11450: 
                   11451: =back
                   11452: 
1.191     harris41 11453: =item *
                   11454: 
1.624     albertel 11455: resdata($name,$domain,$type,@which) : request for current parameter
                   11456: setting for a specific $type, where $type is either 'course' or 'user',
                   11457: @what should be a list of parameters to ask about. This routine caches
                   11458: answers for 5 minutes.
1.243     albertel 11459: 
1.877     foxr     11460: =item *
                   11461: 
                   11462: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11463: data base, returning a hash that is keyed by the resource name and has
                   11464: values that are the resource value.  I believe that the timestamps and
                   11465: versions are also returned.
                   11466: 
                   11467: 
1.243     albertel 11468: =back
                   11469: 
                   11470: =head2 Course Modification
                   11471: 
                   11472: =over 4
1.191     harris41 11473: 
                   11474: =item *
                   11475: 
1.243     albertel 11476: writecoursepref($courseid,%prefs) : write preferences (environment
                   11477: database) for a course
1.191     harris41 11478: 
                   11479: =item *
                   11480: 
1.1011    raeburn  11481: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11482: 
                   11483: =item *
                   11484: 
1.1038    raeburn  11485: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11486: 
                   11487: =back
                   11488: 
                   11489: =head2 Resource Subroutines
                   11490: 
                   11491: =over 4
1.191     harris41 11492: 
                   11493: =item *
                   11494: 
1.243     albertel 11495: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11496: 
                   11497: =item *
                   11498: 
1.243     albertel 11499: repcopy($filename) : subscribes to the requested file, and attempts to
                   11500: replicate from the owning library server, Might return
1.607     raeburn  11501: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11502: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11503: resource. Expects the local filesystem pathname
                   11504: (/home/httpd/html/res/....)
                   11505: 
                   11506: =back
                   11507: 
                   11508: =head2 Resource Information
                   11509: 
                   11510: =over 4
1.191     harris41 11511: 
                   11512: =item *
                   11513: 
1.243     albertel 11514: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11515: a vairety of different possible values, $varname should be a request
                   11516: string, and the other parameters can be used to specify who and what
                   11517: one is asking about.
                   11518: 
                   11519: Possible values for $varname are environment.lastname (or other item
                   11520: from the envirnment hash), user.name (or someother aspect about the
                   11521: user), resource.0.maxtries (or some other part and parameter of a
                   11522: resource)
1.204     albertel 11523: 
                   11524: =item *
                   11525: 
1.243     albertel 11526: directcondval($number) : get current value of a condition; reads from a state
                   11527: string
1.204     albertel 11528: 
                   11529: =item *
                   11530: 
1.243     albertel 11531: condval($condidx) : value of condition index based on state
1.204     albertel 11532: 
                   11533: =item *
                   11534: 
1.243     albertel 11535: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11536: resource's metadata, $what should be either a specific key, or either
                   11537: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11538: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11539: 
                   11540: this function automatically caches all requests
1.191     harris41 11541: 
                   11542: =item *
                   11543: 
1.243     albertel 11544: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11545: network of library servers; returns file handle of where SQL and regex results
                   11546: will be stored for query
1.191     harris41 11547: 
                   11548: =item *
                   11549: 
1.243     albertel 11550: symbread($filename) : return symbolic list entry (filename argument optional);
                   11551: returns the data handle
1.191     harris41 11552: 
                   11553: =item *
                   11554: 
1.243     albertel 11555: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11556: a possible symb for the URL in $thisfn, and if is an encryypted
                   11557: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11558: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11559: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11560: 
1.191     harris41 11561: 
                   11562: =item *
                   11563: 
1.243     albertel 11564: symbclean($symb) : removes versions numbers from a symb, returns the
                   11565: cleaned symb
1.191     harris41 11566: 
                   11567: =item *
                   11568: 
1.243     albertel 11569: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11570: course map, user must be in a course for it to work.
1.191     harris41 11571: 
                   11572: =item *
                   11573: 
1.243     albertel 11574: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11575: 
                   11576: =item *
                   11577: 
1.243     albertel 11578: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11579: a random seed, all arguments are optional, if they aren't sent it uses the
                   11580: environment to derive them. Note: if symb isn't sent and it can't get one
                   11581: from &symbread it will use the current time as its return value
1.191     harris41 11582: 
                   11583: =item *
                   11584: 
1.243     albertel 11585: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11586: unfakeable, receipt
1.191     harris41 11587: 
                   11588: =item *
                   11589: 
1.620     albertel 11590: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11591: 
                   11592: =item *
                   11593: 
1.243     albertel 11594: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11595: 
                   11596: =item *
                   11597: 
1.243     albertel 11598: 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 11599: 
                   11600: =item *
                   11601: 
1.243     albertel 11602: 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 11603: 
                   11604: =item *
                   11605: 
1.243     albertel 11606: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11607: 
                   11608: =item *
                   11609: 
1.243     albertel 11610: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11611: forcing spreadsheet to reevaluate the resource scores next time.
                   11612: 
                   11613: =back
                   11614: 
                   11615: =head2 Storing/Retreiving Data
                   11616: 
                   11617: =over 4
1.191     harris41 11618: 
                   11619: =item *
                   11620: 
1.243     albertel 11621: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11622: for this url; hashref needs to be given and should be a \%hashname; the
                   11623: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11624: be derived from the env
1.191     harris41 11625: 
                   11626: =item *
                   11627: 
1.243     albertel 11628: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11629: uses critical subroutine
1.191     harris41 11630: 
                   11631: =item *
                   11632: 
1.243     albertel 11633: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11634: all args are optional
1.191     harris41 11635: 
                   11636: =item *
                   11637: 
1.717     albertel 11638: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11639: dumps the complete (or key matching regexp) namespace into a hash
                   11640: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11641: normally &store()ed into
                   11642: 
                   11643: $range should be either an integer '100' (give me the first 100
                   11644:                                            matching records)
                   11645:               or be  two integers sperated by a - with no spaces
                   11646:                  '30-50' (give me the 30th through the 50th matching
                   11647:                           records)
                   11648: 
                   11649: 
                   11650: =item *
                   11651: 
                   11652: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11653: replaces a &store() version of data with a replacement set of data
                   11654: for a particular resource in a namespace passed in the $storehash hash 
                   11655: reference
                   11656: 
                   11657: =item *
                   11658: 
1.243     albertel 11659: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11660: works very similar to store/cstore, but all data is stored in a
                   11661: temporary location and can be reset using tmpreset, $storehash should
                   11662: be a hash reference, returns nothing on success
1.191     harris41 11663: 
                   11664: =item *
                   11665: 
1.243     albertel 11666: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11667: similar to restore, but all data is stored in a temporary location and
                   11668: can be reset using tmpreset. Returns a hash of values on success,
                   11669: error string otherwise.
1.191     harris41 11670: 
                   11671: =item *
                   11672: 
1.243     albertel 11673: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11674: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11675: 
                   11676: =item *
                   11677: 
1.243     albertel 11678: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11679: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11680: 
                   11681: =item *
                   11682: 
1.243     albertel 11683: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11684: namesp ($udom and $uname are optional)
1.191     harris41 11685: 
                   11686: =item *
                   11687: 
1.702     albertel 11688: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11689: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11690: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11691: 
1.702     albertel 11692: $range should be either an integer '100' (give me the first 100
                   11693:                                            matching records)
                   11694:               or be  two integers sperated by a - with no spaces
                   11695:                  '30-50' (give me the 30th through the 50th matching
                   11696:                           records)
1.449     matthew  11697: =item *
                   11698: 
                   11699: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11700: $store can be a scalar, an array reference, or if the amount to be 
                   11701: incremented is > 1, a hash reference.
                   11702: 
                   11703: ($udom and $uname are optional)
1.191     harris41 11704: 
                   11705: =item *
                   11706: 
1.243     albertel 11707: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11708: ($udom and $uname are optional)
1.191     harris41 11709: 
                   11710: =item *
                   11711: 
1.243     albertel 11712: cput($namespace,$storehash,$udom,$uname) : critical put
                   11713: ($udom and $uname are optional)
1.191     harris41 11714: 
                   11715: =item *
                   11716: 
1.748     albertel 11717: newput($namespace,$storehash,$udom,$uname) :
                   11718: 
                   11719: Attempts to store the items in the $storehash, but only if they don't
                   11720: currently exist, if this succeeds you can be certain that you have 
                   11721: successfully created a new key value pair in the $namespace db.
                   11722: 
                   11723: 
                   11724: Args:
                   11725:  $namespace: name of database to store values to
                   11726:  $storehash: hashref to store to the db
                   11727:  $udom: (optional) domain of user containing the db
                   11728:  $uname: (optional) name of user caontaining the db
                   11729: 
                   11730: Returns:
                   11731:  'ok' -> succeeded in storing all keys of $storehash
                   11732:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11733:                         least <key> already existed in the db (other
                   11734:                         requested keys may also already exist)
1.967     bisitz   11735:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11736:  'con_lost' -> unable to contact request server
                   11737:  'refused' -> action was not allowed by remote machine
                   11738: 
                   11739: 
                   11740: =item *
                   11741: 
1.243     albertel 11742: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11743: reference filled in from namesp (encrypts the return communication)
                   11744: ($udom and $uname are optional)
1.191     harris41 11745: 
                   11746: =item *
                   11747: 
1.243     albertel 11748: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11749: critical subroutine
                   11750: 
1.806     raeburn  11751: =item *
                   11752: 
1.860     raeburn  11753: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11754: array reference filled in from namespace found in domain level on either
                   11755: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11756: 
                   11757: =item *
                   11758: 
1.860     raeburn  11759: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11760: domain level either on specified domain server ($uhome) or primary domain 
                   11761: server ($udom and $uhome are optional)
1.806     raeburn  11762: 
1.943     raeburn  11763: =item * 
                   11764: 
                   11765: get_domain_defaults($target_domain) : returns hash with defaults for
                   11766: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11767: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11768: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11769: Values are retrieved from cache (if current), or from domain's configuration.db
                   11770: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11771: or lonTabs/domain.tab. 
                   11772: 
                   11773: %domdefaults = &get_auth_defaults($target_domain);
                   11774: 
1.243     albertel 11775: =back
                   11776: 
                   11777: =head2 Network Status Functions
                   11778: 
                   11779: =over 4
1.191     harris41 11780: 
                   11781: =item *
                   11782: 
                   11783: dirlist($uri) : return directory list based on URI
                   11784: 
                   11785: =item *
                   11786: 
1.243     albertel 11787: spareserver() : find server with least workload from spare.tab
                   11788: 
1.986     foxr     11789: 
                   11790: =item *
                   11791: 
                   11792: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11793: if there is no corresponding loncapa host.
                   11794: 
1.243     albertel 11795: =back
                   11796: 
1.986     foxr     11797: 
1.243     albertel 11798: =head2 Apache Request
                   11799: 
                   11800: =over 4
1.191     harris41 11801: 
                   11802: =item *
                   11803: 
1.243     albertel 11804: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11805: localhost, posts hash
                   11806: 
                   11807: =back
                   11808: 
                   11809: =head2 Data to String to Data
                   11810: 
                   11811: =over 4
1.191     harris41 11812: 
                   11813: =item *
                   11814: 
1.243     albertel 11815: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11816: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11817: 
                   11818: =item *
                   11819: 
1.243     albertel 11820: hashref2str($hashref) : convert a hashref into a string complete with
                   11821: escaping and '=' and '&' separators, supports elements that are
                   11822: arrayrefs and hashrefs
1.191     harris41 11823: 
                   11824: =item *
                   11825: 
1.243     albertel 11826: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11827: with escaping and '&' separators, supports elements that are arrayrefs
                   11828: and hashrefs
1.191     harris41 11829: 
                   11830: =item *
                   11831: 
1.243     albertel 11832: str2hash($string) : convert string to hash using unescaping and
                   11833: splitting on '=' and '&', supports elements that are arrayrefs and
                   11834: hashrefs
1.191     harris41 11835: 
                   11836: =item *
                   11837: 
1.243     albertel 11838: str2array($string) : convert string to hash using unescaping and
                   11839: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11840: 
                   11841: =back
                   11842: 
                   11843: =head2 Logging Routines
                   11844: 
                   11845: 
                   11846: These routines allow one to make log messages in the lonnet.log and
                   11847: lonnet.perm logfiles.
1.191     harris41 11848: 
1.1119    foxr     11849: =over 4
                   11850: 
1.191     harris41 11851: =item *
                   11852: 
1.243     albertel 11853: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 11854: 
                   11855: =item *
                   11856: 
1.243     albertel 11857: logthis() : append message to the normal lonnet.log file, it gets
                   11858: preiodically rolled over and deleted.
1.191     harris41 11859: 
                   11860: =item *
                   11861: 
1.243     albertel 11862: logperm() : append a permanent message to lonnet.perm.log, this log
                   11863: file never gets deleted by any automated portion of the system, only
                   11864: messages of critical importance should go in here.
                   11865: 
1.1119    foxr     11866: 
1.243     albertel 11867: =back
                   11868: 
                   11869: =head2 General File Helper Routines
                   11870: 
                   11871: =over 4
1.191     harris41 11872: 
                   11873: =item *
                   11874: 
1.481     raeburn  11875: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   11876: (a) files in /uploaded
                   11877:   (i) If a local copy of the file exists - 
                   11878:       compares modification date of local copy with last-modified date for 
                   11879:       definitive version stored on home server for course. If local copy is 
                   11880:       stale, requests a new version from the home server and stores it. 
                   11881:       If the original has been removed from the home server, then local copy 
                   11882:       is unlinked.
                   11883:   (ii) If local copy does not exist -
                   11884:       requests the file from the home server and stores it. 
                   11885:   
                   11886:   If $caller is 'uploadrep':  
                   11887:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   11888:     for request for files originally uploaded via DOCS. 
                   11889:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   11890:   
                   11891:   Otherwise:
                   11892:      This indicates a call from the content generation phase of the request.
                   11893:      -  returns the entire contents of the file or -1.
                   11894:      
                   11895: (b) files in /res
                   11896:    - returns the entire contents of a file or -1; 
                   11897:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 11898: 
1.712     albertel 11899: 
                   11900: =item *
                   11901: 
                   11902: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   11903:                   reference
                   11904: 
                   11905: returns either a stat() list of data about the file or an empty list
                   11906: if the file doesn't exist or couldn't find out about it (connection
                   11907: problems or user unknown)
                   11908: 
1.191     harris41 11909: =item *
                   11910: 
1.243     albertel 11911: filelocation($dir,$file) : returns file system location of a file
                   11912: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   11913: directory that relative $file lookups are to looked in ($dir of /a/dir
                   11914: and a file of ../bob will become /a/bob)
1.191     harris41 11915: 
                   11916: =item *
                   11917: 
                   11918: hreflocation($dir,$file) : returns file system location or a URL; same as
                   11919: filelocation except for hrefs
                   11920: 
                   11921: =item *
                   11922: 
                   11923: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   11924: 
1.243     albertel 11925: =back
                   11926: 
1.608     albertel 11927: =head2 Usererfile file routines (/uploaded*)
                   11928: 
                   11929: =over 4
                   11930: 
                   11931: =item *
                   11932: 
                   11933: userfileupload(): main rotine for putting a file in a user or course's
                   11934:                   filespace, arguments are,
                   11935: 
1.620     albertel 11936:  formname - required - this is the name of the element in $env where the
1.608     albertel 11937:            filename, and the contents of the file to create/modifed exist
1.620     albertel 11938:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   11939:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  11940:  context - if coursedoc, store the file in the course of the active role
                   11941:              of the current user; 
                   11942:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   11943:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 11944:  subdir - required - subdirectory to put the file in under ../userfiles/
                   11945:          if undefined, it will be placed in "unknown"
                   11946: 
                   11947:  (This routine calls clean_filename() to remove any dangerous
                   11948:  characters from the filename, and then calls finuserfileupload() to
                   11949:  complete the transaction)
                   11950: 
                   11951:  returns either the url of the uploaded file (/uploaded/....) if successful
                   11952:  and /adm/notfound.html if unsuccessful
                   11953: 
                   11954: =item *
                   11955: 
                   11956: clean_filename(): routine for cleaing a filename up for storage in
                   11957:                  userfile space, argument is:
                   11958: 
                   11959:  filename - proposed filename
                   11960: 
                   11961: returns: the new clean filename
                   11962: 
                   11963: =item *
                   11964: 
1.1090    raeburn  11965: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 11966: userspace, probably shouldn't be called directly
                   11967: 
                   11968:   docuname: username or courseid of destination for the file
                   11969:   docudom: domain of user/course of destination for the file
                   11970:   formname: same as for userfileupload()
1.1090    raeburn  11971:   fname: filename (including subdirectories) for the file
                   11972:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   11973:   allfiles: reference to hash used to store objects found by parser
                   11974:   codebase: reference to hash used for codebases of java objects found by parser
                   11975:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   11976:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   11977:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   11978:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   11979:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   11980:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  11981:   mimetype: reference to scalar to accommodate mime type determined
                   11982:             from File::MMagic if $parser = parse.
1.608     albertel 11983: 
                   11984:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  11985:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   11986:  was 'overwrite').
                   11987:  
1.608     albertel 11988: 
                   11989: =item *
                   11990: 
                   11991: renameuserfile(): renames an existing userfile to a new name
                   11992: 
                   11993:   Args:
                   11994:    docuname: username or courseid of destination for the file
                   11995:    docudom: domain of user/course of destination for the file
                   11996:    old: current file name (including any subdirs under userfiles)
                   11997:    new: desired file name (including any subdirs under userfiles)
                   11998: 
                   11999: =item *
                   12000: 
                   12001: mkdiruserfile(): creates a directory is a userfiles dir
                   12002: 
                   12003:   Args:
                   12004:    docuname: username or courseid of destination for the file
                   12005:    docudom: domain of user/course of destination for the file
                   12006:    dir: dir to create (including any subdirs under userfiles)
                   12007: 
                   12008: =item *
                   12009: 
                   12010: removeuserfile(): removes a file that exists in userfiles
                   12011: 
                   12012:   Args:
                   12013:    docuname: username or courseid of destination for the file
                   12014:    docudom: domain of user/course of destination for the file
                   12015:    fname: filname to delete (including any subdirs under userfiles)
                   12016: 
                   12017: =item *
                   12018: 
                   12019: removeuploadedurl(): convience function for removeuserfile()
                   12020: 
                   12021:   Args:
                   12022:    url:  a full /uploaded/... url to delete
                   12023: 
1.747     albertel 12024: =item * 
                   12025: 
                   12026: get_portfile_permissions():
                   12027:   Args:
                   12028:     domain: domain of user or course contain the portfolio files
                   12029:     user: name of user or num of course contain the portfolio files
                   12030:   Returns:
                   12031:     hashref of a dump of the proper file_permissions.db
                   12032:    
                   12033: 
                   12034: =item * 
                   12035: 
                   12036: get_access_controls():
                   12037: 
                   12038: Args:
                   12039:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12040:   group: (optional) the group you want the files associated with
                   12041:   file: (optional) the file you want access info on
                   12042: 
                   12043: Returns:
1.749     raeburn  12044:     a hash (keys are file names) of hashes containing
                   12045:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12046:         values are XML containing access control settings (see below) 
1.747     albertel 12047: 
                   12048: Internal notes:
                   12049: 
1.749     raeburn  12050:  access controls are stored in file_permissions.db as key=value pairs.
                   12051:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12052:         where scope -> public,guest,course,group,domains or users.
                   12053:               end -> UNIX time for end of access (0 -> no end date)
                   12054:               start -> UNIX time for start of access
                   12055: 
                   12056:     value -> XML description of access control
                   12057:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12058:             <start></start>
                   12059:             <end></end>
                   12060: 
                   12061:             <password></password>  for scope type = guest
                   12062: 
                   12063:             <domain></domain>     for scope type = course or group
                   12064:             <number></number>
                   12065:             <roles id="">
                   12066:              <role></role>
                   12067:              <access></access>
                   12068:              <section></section>
                   12069:              <group></group>
                   12070:             </roles>
                   12071: 
                   12072:             <dom></dom>         for scope type = domains
                   12073: 
                   12074:             <users>             for scope type = users
                   12075:              <user>
                   12076:               <uname></uname>
                   12077:               <udom></udom>
                   12078:              </user>
                   12079:             </users>
                   12080:            </scope> 
                   12081:               
                   12082:  Access data is also aggregated for each file in an additional key=value pair:
                   12083:  key -> path to file/file_name\0accesscontrol 
                   12084:  value -> reference to hash
                   12085:           hash contains key = value pairs
                   12086:           where key = uniqueID:scope_end_start
                   12087:                 value = UNIX time record was last updated
                   12088: 
                   12089:           Used to improve speed of look-ups of access controls for each file.  
                   12090:  
                   12091:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12092: 
                   12093: modify_access_controls():
                   12094: 
                   12095: Modifies access controls for a portfolio file
                   12096: Args
                   12097: 1. file name
                   12098: 2. reference to hash of required changes,
                   12099: 3. domain
                   12100: 4. username
                   12101:   where domain,username are the domain of the portfolio owner 
                   12102:   (either a user or a course) 
                   12103: 
                   12104: Returns:
                   12105: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12106: 2. result of deletions ('ok' or 'error', with error message).
                   12107: 3. reference to hash of any new or updated access controls.
                   12108: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12109:    key = integer (inbound ID)
                   12110:    value = uniqueID  
1.747     albertel 12111: 
1.608     albertel 12112: =back
                   12113: 
1.243     albertel 12114: =head2 HTTP Helper Routines
                   12115: 
                   12116: =over 4
                   12117: 
1.191     harris41 12118: =item *
                   12119: 
                   12120: escape() : unpack non-word characters into CGI-compatible hex codes
                   12121: 
                   12122: =item *
                   12123: 
                   12124: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12125: 
1.243     albertel 12126: =back
                   12127: 
                   12128: =head1 PRIVATE SUBROUTINES
                   12129: 
                   12130: =head2 Underlying communication routines (Shouldn't call)
                   12131: 
                   12132: =over 4
                   12133: 
                   12134: =item *
                   12135: 
                   12136: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12137: 
                   12138: =item *
                   12139: 
                   12140: reply() : uses subreply to send a message to remote machine, logs all failures
                   12141: 
                   12142: =item *
                   12143: 
                   12144: critical() : passes a critical message to another server; if cannot
                   12145: get through then place message in connection buffer directory and
                   12146: returns con_delayed, if incapable of saving message, returns
                   12147: con_failed
                   12148: 
                   12149: =item *
                   12150: 
                   12151: reconlonc() : tries to reconnect lonc client processes.
                   12152: 
                   12153: =back
                   12154: 
                   12155: =head2 Resource Access Logging
                   12156: 
                   12157: =over 4
                   12158: 
                   12159: =item *
                   12160: 
                   12161: flushcourselogs() : flush (save) buffer logs and access logs
                   12162: 
                   12163: =item *
                   12164: 
                   12165: courselog($what) : save message for course in hash
                   12166: 
                   12167: =item *
                   12168: 
                   12169: courseacclog($what) : save message for course using &courselog().  Perform
                   12170: special processing for specific resource types (problems, exams, quizzes, etc).
                   12171: 
1.191     harris41 12172: =item *
                   12173: 
                   12174: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12175: as a PerlChildExitHandler
1.243     albertel 12176: 
                   12177: =back
                   12178: 
                   12179: =head2 Other
                   12180: 
                   12181: =over 4
                   12182: 
                   12183: =item *
                   12184: 
                   12185: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12186: 
                   12187: =back
                   12188: 
                   12189: =cut
1.877     foxr     12190: 

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