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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1147  ! raeburn     4: # $Id: lonnet.pm,v 1.1146 2011/11/29 11:54:33 foxr Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.871     albertel   78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    79:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     80:             %managerstab);
1.871     albertel   81: 
                     82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     83:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     84:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        85:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        86: 
1.1       albertel   87: use IO::Socket;
1.31      www        88: use GDBM_File;
1.208     albertel   89: use HTML::LCParser;
1.88      www        90: use Fcntl qw(:flock);
1.870     albertel   91: use Storable qw(thaw nfreeze);
1.539     albertel   92: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   93: use Cache::Memcached;
1.676     albertel   94: use Digest::MD5;
1.790     albertel   95: use Math::Random;
1.1024    raeburn    96: use File::MMagic;
1.807     albertel   97: use LONCAPA qw(:DEFAULT :match);
1.740     www        98: use LONCAPA::Configuration;
1.1117    foxr       99: 
1.1090    raeburn   100: use File::Copy;
1.676     albertel  101: 
1.195     www       102: my $readit;
1.550     foxr      103: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  104: 
1.619     albertel  105: require Exporter;
                    106: 
                    107: our @ISA = qw (Exporter);
                    108: our @EXPORT = qw(%env);
                    109: 
1.449     matthew   110: 
1.1       albertel  111: # --------------------------------------------------------------------- Logging
1.729     www       112: {
                    113:     my $logid;
                    114:     sub instructor_log {
1.957     raeburn   115: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    116:         if (($cnum eq '') || ($cdom eq '')) {
                    117:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    118:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    119:         }
1.729     www       120: 	$logid++;
1.957     raeburn   121:         my $now = time();
                    122: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       123: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       124: 				    { $id => {
                    125: 					'exe_uname' => $env{'user.name'},
                    126: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   127: 					'exe_time'  => $now,
1.730     www       128: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    129: 					'delflag'   => $delflag,
                    130: 					'logentry'  => $storehash,
                    131: 					'uname'     => $uname,
                    132: 					'udom'      => $udom,
                    133: 				    }
1.957     raeburn   134: 				  },$cdom,$cnum);
1.729     www       135:     }
                    136: }
1.1       albertel  137: 
1.163     harris41  138: sub logtouch {
                    139:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  140:     unless (-e "$execdir/logs/lonnet.log") {	
                    141: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  142: 	close $fh;
                    143:     }
                    144:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    145:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    146: }
                    147: 
1.1       albertel  148: sub logthis {
                    149:     my $message=shift;
                    150:     my $execdir=$perlvar{'lonDaemons'};
                    151:     my $now=time;
                    152:     my $local=localtime($now);
1.448     albertel  153:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      154: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    155: 	print $fh $logstring;
1.448     albertel  156: 	close($fh);
                    157:     }
1.1       albertel  158:     return 1;
                    159: }
                    160: 
                    161: sub logperm {
                    162:     my $message=shift;
                    163:     my $execdir=$perlvar{'lonDaemons'};
                    164:     my $now=time;
                    165:     my $local=localtime($now);
1.448     albertel  166:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    167: 	print $fh "$now:$message:$local\n";
                    168: 	close($fh);
                    169:     }
1.1       albertel  170:     return 1;
                    171: }
                    172: 
1.850     albertel  173: sub create_connection {
1.853     albertel  174:     my ($hostname,$lonid) = @_;
1.851     albertel  175:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  176: 				     Type    => SOCK_STREAM,
                    177: 				     Timeout => 10);
                    178:     return 0 if (!$client);
1.890     albertel  179:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  180:     my $result = <$client>;
                    181:     chomp($result);
                    182:     return 1 if ($result eq 'done');
                    183:     return 0;
                    184: }
                    185: 
1.983     raeburn   186: sub get_server_timezone {
                    187:     my ($cnum,$cdom) = @_;
                    188:     my $home=&homeserver($cnum,$cdom);
                    189:     if ($home ne 'no_host') {
                    190:         my $cachetime = 24*3600;
                    191:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    192:         if (defined($cached)) {
                    193:             return $timezone;
                    194:         } else {
                    195:             my $timezone = &reply('servertimezone',$home);
                    196:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    197:         }
                    198:     }
                    199: }
1.850     albertel  200: 
1.1106    raeburn   201: sub get_server_distarch {
                    202:     my ($lonhost,$ignore_cache) = @_;
                    203:     if (defined($lonhost)) {
                    204:         if (!defined(&hostname($lonhost))) {
                    205:             return;
                    206:         }
                    207:         my $cachetime = 12*3600;
                    208:         if (!$ignore_cache) {
                    209:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    210:             if (defined($cached)) {
                    211:                 return $distarch;
                    212:             }
                    213:         }
                    214:         my $rep = &reply('serverdistarch',$lonhost);
                    215:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    216:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    217:                 $rep eq '') {
                    218:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    219:         }
                    220:     }
                    221:     return;
                    222: }
                    223: 
1.993     raeburn   224: sub get_server_loncaparev {
1.1073    raeburn   225:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   226:     if (defined($lonhost)) {
                    227:         if (!defined(&hostname($lonhost))) {
                    228:             undef($lonhost);
                    229:         }
                    230:     }
                    231:     if (!defined($lonhost)) {
                    232:         if (defined(&domain($dom,'primary'))) {
                    233:             $lonhost=&domain($dom,'primary');
                    234:             if ($lonhost eq 'no_host') {
                    235:                 undef($lonhost);
                    236:             }
                    237:         }
                    238:     }
                    239:     if (defined($lonhost)) {
1.1073    raeburn   240:         my $cachetime = 12*3600;
                    241:         if (!$ignore_cache) {
                    242:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    243:             if (defined($cached)) {
                    244:                 return $loncaparev;
                    245:             }
                    246:         }
                    247:         my ($answer,$loncaparev);
                    248:         my @ids=&current_machine_ids();
                    249:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    250:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   251:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   252:                 $loncaparev = $1;
                    253:             }
                    254:         } else {
                    255:             $answer = &reply('serverloncaparev',$lonhost);
                    256:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    257:                 if ($caller eq 'loncron') {
                    258:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   259:                     $ua->timeout(4);
1.1073    raeburn   260:                     my $protocol = $protocol{$lonhost};
                    261:                     $protocol = 'http' if ($protocol ne 'https');
                    262:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    263:                     my $request=new HTTP::Request('GET',$url);
                    264:                     my $response=$ua->request($request);
                    265:                     unless ($response->is_error()) {
                    266:                         my $content = $response->content;
1.1081    raeburn   267:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   268:                             $loncaparev = $1;
                    269:                         }
                    270:                     }
                    271:                 } else {
                    272:                     $loncaparev = $loncaparevs{$lonhost};
                    273:                 }
1.1081    raeburn   274:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   275:                 $loncaparev = $1;
                    276:             }
1.993     raeburn   277:         }
1.1073    raeburn   278:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   279:     }
                    280: }
                    281: 
1.1074    raeburn   282: sub get_server_homeID {
                    283:     my ($hostname,$ignore_cache,$caller) = @_;
                    284:     unless ($ignore_cache) {
                    285:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    286:         if (defined($cached)) {
                    287:             return $serverhomeID;
                    288:         }
                    289:     }
                    290:     my $cachetime = 12*3600;
                    291:     my $serverhomeID;
                    292:     if ($caller eq 'loncron') { 
                    293:         my @machine_ids = &machine_ids($hostname);
                    294:         foreach my $id (@machine_ids) {
                    295:             my $response = &reply('serverhomeID',$id);
                    296:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    297:                 $serverhomeID = $response;
                    298:                 last;
                    299:             }
                    300:         }
                    301:         if ($serverhomeID eq '') {
                    302:             $serverhomeID = $machine_ids[-1];
                    303:         }
                    304:     } else {
                    305:         $serverhomeID = $serverhomeIDs{$hostname};
                    306:     }
                    307:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    308: }
                    309: 
1.1121    raeburn   310: sub get_remote_globals {
                    311:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   312:     my ($result,%returnhash,%whatneeded);
                    313:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   314:         foreach my $what (sort(keys(%{$whathash}))) {
                    315:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   316:             my ($response,$cached);
1.1121    raeburn   317:             unless ($ignore_cache) {
1.1125    raeburn   318:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   319:             }
                    320:             if (defined($cached)) {
1.1125    raeburn   321:                 $returnhash{$what} = $response;
1.1121    raeburn   322:             } else {
1.1125    raeburn   323:                 $whatneeded{$what} = 1;
1.1121    raeburn   324:             }
                    325:         }
1.1125    raeburn   326:         if (keys(%whatneeded) == 0) {
                    327:             $result = 'ok';
                    328:         } else {
1.1121    raeburn   329:             my $requested = &freeze_escape(\%whatneeded);
                    330:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   331:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    332:                 ($rep eq 'unknown_cmd')) {
                    333:                 $result = $rep;
                    334:             } else {
                    335:                 $result = 'ok';
1.1121    raeburn   336:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   337:                 foreach my $item (@pairs) {
                    338:                     my ($key,$value)=split(/=/,$item,2);
                    339:                     my $what = &unescape($key);
                    340:                     my $hashid = $lonhost.'-'.$what;
                    341:                     $returnhash{$what}=&thaw_unescape($value);
                    342:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   343:                 }
                    344:             }
                    345:         }
                    346:     }
1.1125    raeburn   347:     return ($result,\%returnhash);
1.1121    raeburn   348: }
                    349: 
1.1124    raeburn   350: sub remote_devalidate_cache {
                    351:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   352:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   353:     return $response;
                    354: }
                    355: 
1.1       albertel  356: # -------------------------------------------------- Non-critical communication
                    357: sub subreply {
                    358:     my ($cmd,$server)=@_;
1.838     albertel  359:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      360:     #
                    361:     #  With loncnew process trimming, there's a timing hole between lonc server
                    362:     #  process exit and the master server picking up the listen on the AF_UNIX
                    363:     #  socket.  In that time interval, a lock file will exist:
                    364: 
                    365:     my $lockfile=$peerfile.".lock";
                    366:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    367: 	sleep(1);
                    368:     }
                    369:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      370:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      371:     #
1.550     foxr      372:     #   We'll give the connection a few tries before abandoning it.  If
                    373:     #   connection is not possible, we'll con_lost back to the client.
                    374:     #   
                    375:     my $client;
                    376:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    377: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    378: 				      Type    => SOCK_STREAM,
                    379: 				      Timeout => 10);
1.869     albertel  380: 	if ($client) {
1.550     foxr      381: 	    last;		# Connected!
1.850     albertel  382: 	} else {
1.853     albertel  383: 	    &create_connection(&hostname($server),$server);
1.550     foxr      384: 	}
1.850     albertel  385:         sleep(1);		# Try again later if failed connection.
1.550     foxr      386:     }
                    387:     my $answer;
                    388:     if ($client) {
1.704     albertel  389: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      390: 	$answer=<$client>;
                    391: 	if (!$answer) { $answer="con_lost"; }
                    392: 	chomp($answer);
                    393:     } else {
                    394: 	$answer = 'con_lost';	# Failed connection.
                    395:     }
1.1       albertel  396:     return $answer;
                    397: }
                    398: 
                    399: sub reply {
                    400:     my ($cmd,$server)=@_;
1.838     albertel  401:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  402:     my $answer=subreply($cmd,$server);
1.65      www       403:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  404:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       405:                 " $cmd to $server returned $answer</font>");
                    406:     }
1.1       albertel  407:     return $answer;
                    408: }
                    409: 
                    410: # ----------------------------------------------------------- Send USR1 to lonc
                    411: 
                    412: sub reconlonc {
1.891     albertel  413:     my ($lonid) = @_;
                    414:     my $hostname = &hostname($lonid);
                    415:     if ($lonid) {
                    416: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    417: 	if ($hostname && -e $peerfile) {
                    418: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    419: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    420: 					     Type    => SOCK_STREAM,
                    421: 					     Timeout => 10);
                    422: 	    if ($client) {
                    423: 		print $client ("reset_retries\n");
                    424: 		my $answer=<$client>;
                    425: 		#reset just this one.
                    426: 	    }
                    427: 	}
                    428: 	return;
                    429:     }
                    430: 
1.836     www       431:     &logthis("Trying to reconnect lonc");
1.1       albertel  432:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  433:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  434: 	my $loncpid=<$fh>;
                    435:         chomp($loncpid);
                    436:         if (kill 0 => $loncpid) {
                    437: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    438:             kill USR1 => $loncpid;
                    439:             sleep 1;
1.836     www       440:          } else {
1.12      www       441: 	    &logthis(
1.672     albertel  442:                "<font color=\"blue\">WARNING:".
1.12      www       443:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  444:         }
                    445:     } else {
1.836     www       446: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  447:     }
                    448: }
                    449: 
                    450: # ------------------------------------------------------ Critical communication
1.12      www       451: 
1.1       albertel  452: sub critical {
                    453:     my ($cmd,$server)=@_;
1.838     albertel  454:     unless (&hostname($server)) {
1.672     albertel  455:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       456:                " Critical message to unknown server ($server)</font>");
                    457:         return 'no_such_host';
                    458:     }
1.1       albertel  459:     my $answer=reply($cmd,$server);
                    460:     if ($answer eq 'con_lost') {
                    461: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  462: 	my $answer=reply($cmd,$server);
1.1       albertel  463:         if ($answer eq 'con_lost') {
                    464:             my $now=time;
                    465:             my $middlename=$cmd;
1.5       www       466:             $middlename=substr($middlename,0,16);
1.1       albertel  467:             $middlename=~s/\W//g;
                    468:             my $dfilename=
1.305     www       469:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    470:             $dumpcount++;
1.1       albertel  471:             {
1.448     albertel  472: 		my $dfh;
                    473: 		if (open($dfh,">$dfilename")) {
                    474: 		    print $dfh "$cmd\n"; 
                    475: 		    close($dfh);
                    476: 		}
1.1       albertel  477:             }
                    478:             sleep 2;
                    479:             my $wcmd='';
                    480:             {
1.448     albertel  481: 		my $dfh;
                    482: 		if (open($dfh,"<$dfilename")) {
                    483: 		    $wcmd=<$dfh>; 
                    484: 		    close($dfh);
                    485: 		}
1.1       albertel  486:             }
                    487:             chomp($wcmd);
1.7       www       488:             if ($wcmd eq $cmd) {
1.672     albertel  489: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       490:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  491:                 &logperm("D:$server:$cmd");
                    492: 	        return 'con_delayed';
                    493:             } else {
1.672     albertel  494:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       495:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  496:                 &logperm("F:$server:$cmd");
                    497:                 return 'con_failed';
                    498:             }
                    499:         }
                    500:     }
                    501:     return $answer;
1.405     albertel  502: }
                    503: 
1.755     albertel  504: # ------------------------------------------- check if return value is an error
                    505: 
                    506: sub error {
                    507:     my ($result) = @_;
1.756     albertel  508:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  509: 	if ($2 == 2) { return undef; }
                    510: 	return $1;
                    511:     }
                    512:     return undef;
                    513: }
                    514: 
1.783     albertel  515: sub convert_and_load_session_env {
                    516:     my ($lonidsdir,$handle)=@_;
                    517:     my @profile;
                    518:     {
1.917     albertel  519: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    520: 	if (!$opened) {
1.915     albertel  521: 	    return 0;
                    522: 	}
1.783     albertel  523: 	flock($idf,LOCK_SH);
                    524: 	@profile=<$idf>;
                    525: 	close($idf);
                    526:     }
                    527:     my %temp_env;
                    528:     foreach my $line (@profile) {
1.786     albertel  529: 	if ($line !~ m/=/) {
                    530: 	    return 0;
                    531: 	}
1.783     albertel  532: 	chomp($line);
                    533: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    534: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    535:     }
                    536:     unlink("$lonidsdir/$handle.id");
                    537:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    538: 	    0640)) {
                    539: 	%disk_env = %temp_env;
                    540: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    541: 	untie(%disk_env);
                    542:     }
1.786     albertel  543:     return 1;
1.783     albertel  544: }
                    545: 
1.374     www       546: # ------------------------------------------- Transfer profile into environment
1.780     albertel  547: my $env_loaded;
                    548: sub transfer_profile_to_env {
1.788     albertel  549:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    550:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       551: 
1.720     albertel  552:     if (!defined($lonidsdir)) {
                    553: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    554:     }
                    555:     if (!defined($handle)) {
                    556:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    557:     }
                    558: 
1.786     albertel  559:     my $convert;
                    560:     {
1.917     albertel  561:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    562: 	if (!$opened) {
1.915     albertel  563: 	    return;
                    564: 	}
1.786     albertel  565: 	flock($idf,LOCK_SH);
                    566: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    567: 		&GDBM_READER(),0640)) {
                    568: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    569: 	    untie(%disk_env);
                    570: 	} else {
                    571: 	    $convert = 1;
                    572: 	}
                    573:     }
                    574:     if ($convert) {
                    575: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    576: 	    &logthis("Failed to load session, or convert session.");
                    577: 	}
1.374     www       578:     }
1.783     albertel  579: 
1.786     albertel  580:     my %remove;
1.783     albertel  581:     while ( my $envname = each(%env) ) {
1.433     matthew   582:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    583:             if ($time < time-300) {
1.783     albertel  584:                 $remove{$key}++;
1.433     matthew   585:             }
                    586:         }
                    587:     }
1.783     albertel  588: 
1.619     albertel  589:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  590:     $env_loaded=1;
1.783     albertel  591:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   592:         &delenv($expired_key);
1.374     www       593:     }
1.1       albertel  594: }
                    595: 
1.916     albertel  596: # ---------------------------------------------------- Check for valid session 
                    597: sub check_for_valid_session {
                    598:     my ($r) = @_;
                    599:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
                    600:     my $lonid=$cookies{'lonID'};
                    601:     return undef if (!$lonid);
                    602: 
                    603:     my $handle=&LONCAPA::clean_handle($lonid->value);
                    604:     my $lonidsdir=$r->dir_config('lonIDsDir');
                    605:     return undef if (!-e "$lonidsdir/$handle.id");
                    606: 
1.917     albertel  607:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    608:     return undef if (!$opened);
1.916     albertel  609: 
                    610:     flock($idf,LOCK_SH);
                    611:     my %disk_env;
                    612:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    613: 	    &GDBM_READER(),0640)) {
                    614: 	return undef;	
                    615:     }
                    616: 
                    617:     if (!defined($disk_env{'user.name'})
                    618: 	|| !defined($disk_env{'user.domain'})) {
                    619: 	return undef;
                    620:     }
                    621:     return $handle;
                    622: }
                    623: 
1.830     albertel  624: sub timed_flock {
                    625:     my ($file,$lock_type) = @_;
                    626:     my $failed=0;
                    627:     eval {
                    628: 	local $SIG{__DIE__}='DEFAULT';
                    629: 	local $SIG{ALRM}=sub {
                    630: 	    $failed=1;
                    631: 	    die("failed lock");
                    632: 	};
                    633: 	alarm(13);
                    634: 	flock($file,$lock_type);
                    635: 	alarm(0);
                    636:     };
                    637:     if ($failed) {
                    638: 	return undef;
                    639:     } else {
                    640: 	return 1;
                    641:     }
                    642: }
                    643: 
1.5       www       644: # ---------------------------------------------------------- Append Environment
                    645: 
                    646: sub appenv {
1.949     raeburn   647:     my ($newenv,$roles) = @_;
                    648:     if (ref($newenv) eq 'HASH') {
                    649:         foreach my $key (keys(%{$newenv})) {
                    650:             my $refused = 0;
                    651: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    652:                 $refused = 1;
                    653:                 if (ref($roles) eq 'ARRAY') {
                    654:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    655:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    656:                         $refused = 0;
                    657:                     }
                    658:                 }
                    659:             }
                    660:             if ($refused) {
                    661:                 &logthis("<font color=\"blue\">WARNING: ".
                    662:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    663:                          .'</font>');
                    664: 	        delete($newenv->{$key});
                    665:             } else {
                    666:                 $env{$key}=$newenv->{$key};
                    667:             }
                    668:         }
                    669:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    670:         if ($opened
                    671: 	    && &timed_flock($env_file,LOCK_EX)
                    672: 	    &&
                    673: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    674: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    675: 	    while (my ($key,$value) = each(%{$newenv})) {
                    676: 	        $disk_env{$key} = $value;
                    677: 	    }
                    678: 	    untie(%disk_env);
1.35      www       679:         }
1.191     harris41  680:     }
1.56      www       681:     return 'ok';
                    682: }
                    683: # ----------------------------------------------------- Delete from Environment
                    684: 
                    685: sub delenv {
1.1104    raeburn   686:     my ($delthis,$regexp,$roles) = @_;
                    687:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    688:         my $refused = 1;
                    689:         if (ref($roles) eq 'ARRAY') {
                    690:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    691:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    692:                 $refused = 0;
                    693:             }
                    694:         }
                    695:         if ($refused) {
                    696:             &logthis("<font color=\"blue\">WARNING: ".
                    697:                      "Attempt to delete from environment ".$delthis);
                    698:             return 'error';
                    699:         }
1.56      www       700:     }
1.917     albertel  701:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    702:     if ($opened
1.915     albertel  703: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  704: 	&&
                    705: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    706: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  707: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   708: 	    if ($regexp) {
                    709:                 if ($key=~/^$delthis/) {
                    710:                     delete($env{$key});
                    711:                     delete($disk_env{$key});
                    712:                 } 
                    713:             } else {
                    714:                 if ($key=~/^\Q$delthis\E/) {
                    715: 		    delete($env{$key});
                    716: 		    delete($disk_env{$key});
                    717: 	        }
                    718:             }
1.448     albertel  719: 	}
1.783     albertel  720: 	untie(%disk_env);
1.5       www       721:     }
                    722:     return 'ok';
1.369     albertel  723: }
                    724: 
1.790     albertel  725: sub get_env_multiple {
                    726:     my ($name) = @_;
                    727:     my @values;
                    728:     if (defined($env{$name})) {
                    729:         # exists is it an array
                    730:         if (ref($env{$name})) {
                    731:             @values=@{ $env{$name} };
                    732:         } else {
                    733:             $values[0]=$env{$name};
                    734:         }
                    735:     }
                    736:     return(@values);
                    737: }
                    738: 
1.958     www       739: # ------------------------------------------------------------------- Locking
                    740: 
                    741: sub set_lock {
                    742:     my ($text)=@_;
                    743:     $locknum++;
                    744:     my $id=$$.'-'.$locknum;
                    745:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    746:              'session.lock.'.$id => $text});
                    747:     return $id;
                    748: }
                    749: 
                    750: sub get_locks {
                    751:     my $num=0;
                    752:     my %texts=();
                    753:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    754:        if ($lock=~/\w/) {
                    755:           $num++;
                    756:           $texts{$lock}=$env{'session.lock.'.$lock};
                    757:        }
                    758:    }
                    759:    return ($num,%texts);
                    760: }
                    761: 
                    762: sub remove_lock {
                    763:     my ($id)=@_;
                    764:     my $newlocks='';
                    765:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    766:        if (($lock=~/\w/) && ($lock ne $id)) {
                    767:           $newlocks.=','.$lock;
                    768:        }
                    769:     }
                    770:     &appenv({'session.locks' => $newlocks});
                    771:     &delenv('session.lock.'.$id);
                    772: }
                    773: 
                    774: sub remove_all_locks {
                    775:     my $activelocks=$env{'session.locks'};
                    776:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    777:        if ($lock=~/\w/) {
                    778:           &remove_lock($lock);
                    779:        }
                    780:     }
                    781: }
                    782: 
                    783: 
1.369     albertel  784: # ------------------------------------------ Find out current server userload
                    785: sub userload {
                    786:     my $numusers=0;
                    787:     {
                    788: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    789: 	my $filename;
                    790: 	my $curtime=time;
                    791: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  792: 	    next if ($filename eq '.' || $filename eq '..');
                    793: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  794: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  795: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  796: 	}
                    797: 	closedir(LONIDS);
                    798:     }
                    799:     my $userloadpercent=0;
                    800:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    801:     if ($maxuserload) {
1.371     albertel  802: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  803:     }
1.372     albertel  804:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  805:     return $userloadpercent;
1.283     www       806: }
                    807: 
1.1       albertel  808: # ------------------------------ Find server with least workload from spare.tab
1.11      www       809: 
1.1       albertel  810: sub spareserver {
1.1083    raeburn   811:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  812:     my $spare_server;
1.370     albertel  813:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  814:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    815:                                                      :  $userloadpercent;
1.1083    raeburn   816:     my ($uint_dom,$remotesessions);
                    817:     if (($udom ne '') && (&domain($udom) ne '')) {
                    818:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    819:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    820:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    821:         $remotesessions = $udomdefaults{'remotesessions'};
                    822:     }
1.1123    raeburn   823:     my $spareshash = &this_host_spares($udom);
                    824:     if (ref($spareshash) eq 'HASH') {
                    825:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    826:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    827:                 if ($uint_dom) {
                    828:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    829:                                                  $try_server));
                    830:                 }
                    831: 	        ($spare_server, $lowest_load) =
                    832: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    833:             }
1.1083    raeburn   834:         }
1.784     albertel  835: 
1.1123    raeburn   836:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    837: 
                    838:         if (!$found_server) {
                    839:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    840: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    841:                     if ($uint_dom) {
                    842:                         next unless (&spare_can_host($udom,$uint_dom,
                    843:                                                      $remotesessions,$try_server));
                    844:                     }
                    845: 	            ($spare_server, $lowest_load) =
                    846: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    847:                 }
                    848: 	    }
                    849:         }
1.784     albertel  850:     }
                    851: 
                    852:     if (!$want_server_name) {
1.968     raeburn   853:         my $protocol = 'http';
                    854:         if ($protocol{$spare_server} eq 'https') {
                    855:             $protocol = $protocol{$spare_server};
                    856:         }
1.1001    raeburn   857:         if (defined($spare_server)) {
                    858:             my $hostname = &hostname($spare_server);
1.1083    raeburn   859:             if (defined($hostname)) {
1.1001    raeburn   860: 	        $spare_server = $protocol.'://'.$hostname;
                    861:             }
                    862:         }
1.784     albertel  863:     }
                    864:     return $spare_server;
                    865: }
                    866: 
                    867: sub compare_server_load {
                    868:     my ($try_server, $spare_server, $lowest_load) = @_;
                    869: 
                    870:     my $loadans     = &reply('load',    $try_server);
                    871:     my $userloadans = &reply('userload',$try_server);
                    872: 
                    873:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   874: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  875:     }
                    876: 
                    877:     my $load;
                    878:     if ($loadans =~ /\d/) {
                    879: 	if ($userloadans =~ /\d/) {
                    880: 	    #both are numbers, pick the bigger one
                    881: 	    $load = ($loadans > $userloadans) ? $loadans 
                    882: 		                              : $userloadans;
1.411     albertel  883: 	} else {
1.784     albertel  884: 	    $load = $loadans;
1.411     albertel  885: 	}
1.784     albertel  886:     } else {
                    887: 	$load = $userloadans;
                    888:     }
                    889: 
                    890:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    891: 	$spare_server = $try_server;
                    892: 	$lowest_load  = $load;
1.370     albertel  893:     }
1.784     albertel  894:     return ($spare_server,$lowest_load);
1.202     matthew   895: }
1.914     albertel  896: 
                    897: # --------------------------- ask offload servers if user already has a session
                    898: sub find_existing_session {
                    899:     my ($udom,$uname) = @_;
1.1123    raeburn   900:     my $spareshash = &this_host_spares($udom);
                    901:     if (ref($spareshash) eq 'HASH') {
                    902:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    903:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    904:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    905:             }
                    906:         }
                    907:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    908:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    909:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    910:             }
                    911:         }
1.914     albertel  912:     }
                    913:     return;
                    914: }
                    915: 
                    916: # -------------------------------- ask if server already has a session for user
                    917: sub has_user_session {
                    918:     my ($lonid,$udom,$uname) = @_;
                    919:     my $result = &reply(join(':','userhassession',
                    920: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    921:     return 1 if ($result eq 'ok');
                    922: 
                    923:     return 0;
                    924: }
                    925: 
1.1076    raeburn   926: # --------- determine least loaded server in a user's domain which allows login
                    927: 
                    928: sub choose_server {
1.1115    raeburn   929:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   930:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   931:     my %servers = &get_servers($udom);
1.1076    raeburn   932:     my $lowest_load = 30000;
1.1116    raeburn   933:     my ($login_host,$hostname,$portal_path);
1.1076    raeburn   934:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   935:         my $loginvia;
                    936:         if ($checkloginvia) {
                    937:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   938:             if ($loginvia) {
                    939:                 my ($server,$path) = split(/:/,$loginvia);
                    940:                 ($login_host, $lowest_load) =
                    941:                     &compare_server_load($server, $login_host, $lowest_load);
                    942:                 if ($login_host eq $server) {
                    943:                     $portal_path = $path;
                    944:                 }
                    945:             } else {
                    946:                 ($login_host, $lowest_load) =
                    947:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    948:                 if ($login_host eq $lonhost) {
                    949:                     $portal_path = '';
                    950:                 }
                    951:             }
                    952:         } else {
1.1076    raeburn   953:             ($login_host, $lowest_load) =
1.1116    raeburn   954:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   955:         }
                    956:     }
                    957:     if ($login_host ne '') {
1.1116    raeburn   958:         $hostname = &hostname($login_host);
1.1076    raeburn   959:     }
1.1116    raeburn   960:     return ($login_host,$hostname,$portal_path);
1.1076    raeburn   961: }
                    962: 
1.202     matthew   963: # --------------------------------------------- Try to change a user's password
                    964: 
                    965: sub changepass {
1.799     raeburn   966:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   967:     $currentpass = &escape($currentpass);
                    968:     $newpass     = &escape($newpass);
1.1030    raeburn   969:     my $lonhost = $perlvar{'lonHostID'};
                    970:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   971: 		       $server);
                    972:     if (! $answer) {
                    973: 	&logthis("No reply on password change request to $server ".
                    974: 		 "by $uname in domain $udom.");
                    975:     } elsif ($answer =~ "^ok") {
                    976:         &logthis("$uname in $udom successfully changed their password ".
                    977: 		 "on $server.");
                    978:     } elsif ($answer =~ "^pwchange_failure") {
                    979: 	&logthis("$uname in $udom was unable to change their password ".
                    980: 		 "on $server.  The action was blocked by either lcpasswd ".
                    981: 		 "or pwchange");
                    982:     } elsif ($answer =~ "^non_authorized") {
                    983:         &logthis("$uname in $udom did not get their password correct when ".
                    984: 		 "attempting to change it on $server.");
                    985:     } elsif ($answer =~ "^auth_mode_error") {
                    986:         &logthis("$uname in $udom attempted to change their password despite ".
                    987: 		 "not being locally or internally authenticated on $server.");
                    988:     } elsif ($answer =~ "^unknown_user") {
                    989:         &logthis("$uname in $udom attempted to change their password ".
                    990: 		 "on $server but were unable to because $server is not ".
                    991: 		 "their home server.");
                    992:     } elsif ($answer =~ "^refused") {
                    993: 	&logthis("$server refused to change $uname in $udom password because ".
                    994: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn   995:     } elsif ($answer =~ "invalid_client") {
                    996:         &logthis("$server refused to change $uname in $udom password because ".
                    997:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew   998:     }
                    999:     return $answer;
1.1       albertel 1000: }
                   1001: 
1.169     harris41 1002: # ----------------------- Try to determine user's current authentication scheme
                   1003: 
                   1004: sub queryauthenticate {
                   1005:     my ($uname,$udom)=@_;
1.456     albertel 1006:     my $uhome=&homeserver($uname,$udom);
                   1007:     if (!$uhome) {
                   1008: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1009: 	return 'no_host';
                   1010:     }
                   1011:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1012:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1013: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1014:     }
1.456     albertel 1015:     return $answer;
1.169     harris41 1016: }
                   1017: 
1.1       albertel 1018: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1019: 
1.1       albertel 1020: sub authenticate {
1.1073    raeburn  1021:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1022:     $upass=&escape($upass);
                   1023:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1024:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1025:     my $newhome;
1.836     www      1026:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1027: # Maybe the machine was offline and only re-appeared again recently?
                   1028:         &reconlonc();
                   1029: # One more
1.952     raeburn  1030: 	$uhome=&homeserver($uname,$udom,1);
                   1031:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1032:             if (defined(&domain($udom,'primary'))) {
                   1033:                 $newhome=&domain($udom,'primary');
                   1034:             }
                   1035:             if ($newhome ne '') {
                   1036:                 $uhome = $newhome;
                   1037:             }
                   1038:         }
1.836     www      1039: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1040: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1041: 	    return 'no_host';
                   1042:         }
1.1       albertel 1043:     }
1.1073    raeburn  1044:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1045:     if ($answer eq 'authorized') {
1.952     raeburn  1046:         if ($newhome) {
                   1047:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1048:             return 'no_account_on_host'; 
                   1049:         } else {
                   1050:             &logthis("User $uname at $udom authorized by $uhome");
                   1051:             return $uhome;
                   1052:         }
1.471     albertel 1053:     }
                   1054:     if ($answer eq 'non_authorized') {
                   1055: 	&logthis("User $uname at $udom rejected by $uhome");
                   1056: 	return 'no_host'; 
1.9       www      1057:     }
1.471     albertel 1058:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1059:     return 'no_host';
                   1060: }
                   1061: 
1.1073    raeburn  1062: sub can_host_session {
1.1074    raeburn  1063:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1064:     my $canhost = 1;
1.1074    raeburn  1065:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1066:     if (ref($remotesessions) eq 'HASH') {
                   1067:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1068:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1069:                 $canhost = 0;
                   1070:             } else {
                   1071:                 $canhost = 1;
                   1072:             }
                   1073:         }
                   1074:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1075:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1076:                 $canhost = 1;
                   1077:             } else {
                   1078:                 $canhost = 0;
                   1079:             }
                   1080:         }
                   1081:         if ($canhost) {
                   1082:             if ($remotesessions->{'version'} ne '') {
                   1083:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1084:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1085:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1086:                         my $major = $1;
                   1087:                         my $minor = $2;
                   1088:                         if (($major < $reqmajor ) ||
                   1089:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1090:                             $canhost = 0;
                   1091:                         }
                   1092:                     } else {
                   1093:                         $canhost = 0;
                   1094:                     }
                   1095:                 }
                   1096:             }
                   1097:         }
                   1098:     }
                   1099:     if ($canhost) {
                   1100:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1101:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1102:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1103:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1104:                 if (($uint_dom ne '') && 
                   1105:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1106:                     $canhost = 0;
                   1107:                 } else {
                   1108:                     $canhost = 1;
                   1109:                 }
                   1110:             }
                   1111:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1112:                 if (($uint_dom ne '') && 
                   1113:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1114:                     $canhost = 1;
                   1115:                 } else {
                   1116:                     $canhost = 0;
                   1117:                 }
                   1118:             }
                   1119:         }
                   1120:     }
                   1121:     return $canhost;
                   1122: }
                   1123: 
1.1083    raeburn  1124: sub spare_can_host {
                   1125:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1126:     my $canhost=1;
                   1127:     my @intdoms;
                   1128:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1129:     if (ref($internet_names) eq 'ARRAY') {
                   1130:         @intdoms = @{$internet_names};
                   1131:     }
                   1132:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1133:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1134:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1135:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1136:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1137:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1138:                                      $remotesessions,
                   1139:                                      $defdomdefaults{'hostedsessions'});
                   1140:     }
                   1141:     return $canhost;
                   1142: }
                   1143: 
1.1123    raeburn  1144: sub this_host_spares {
                   1145:     my ($dom) = @_;
1.1126    raeburn  1146:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1147:     my @hosts = &current_machine_ids();
                   1148:     foreach my $lonhost (@hosts) {
                   1149:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1150:             $dom_in_use = $dom;
                   1151:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1152:             last;
                   1153:         }
                   1154:     }
1.1126    raeburn  1155:     if ($dom_in_use ne '') {
                   1156:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1157:     }
                   1158:     if (ref($result) ne 'HASH') {
                   1159:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1160:         $dom_in_use = &host_domain($lonhost_in_use);
                   1161:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1162:         if (ref($result) ne 'HASH') {
                   1163:             $result = \%spareid;
                   1164:         }
                   1165:     }
                   1166:     return $result;
                   1167: }
                   1168: 
                   1169: sub spares_for_offload  {
                   1170:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1171:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1172:     if (defined($cached)) {
                   1173:         return $result;
                   1174:     } else {
1.1126    raeburn  1175:         my $cachetime = 60*60*24;
                   1176:         my %domconfig =
                   1177:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1178:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1179:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1180:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1181:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1182:                 }
                   1183:             }
                   1184:         }
                   1185:     }
1.1126    raeburn  1186:     return;
1.1123    raeburn  1187: }
                   1188: 
1.1129    raeburn  1189: sub get_lonbalancer_config {
                   1190:     my ($servers) = @_;
                   1191:     my ($currbalancer,$currtargets);
                   1192:     if (ref($servers) eq 'HASH') {
                   1193:         foreach my $server (keys(%{$servers})) {
                   1194:             my %what = (
                   1195:                          spareid => 1,
                   1196:                          perlvar => 1,
                   1197:                        );
                   1198:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1199:             if ($result eq 'ok') {
                   1200:                 if (ref($returnhash) eq 'HASH') {
                   1201:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1202:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1203:                             $currbalancer = $server;
                   1204:                             $currtargets = {};
                   1205:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1206:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1207:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1208:                                 }
                   1209:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1210:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1211:                                 }
                   1212:                             }
                   1213:                             last;
                   1214:                         }
                   1215:                     }
                   1216:                 }
                   1217:             }
                   1218:         }
                   1219:     }
                   1220:     return ($currbalancer,$currtargets);
                   1221: }
                   1222: 
                   1223: sub check_loadbalancing {
                   1224:     my ($uname,$udom) = @_;
                   1225:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1226:         $offloadto,$otherserver);
                   1227:     my $lonhost = $perlvar{'lonHostID'};
                   1228:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1229:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1230:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1231:     my $serverhomedom = &host_domain($lonhost);
                   1232: 
                   1233:     my $cachetime = 60*60*24;
                   1234: 
                   1235:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1236:         $dom_in_use = $udom;
                   1237:         $homeintdom = 1;
                   1238:     } else {
                   1239:         $dom_in_use = $serverhomedom;
                   1240:     }
                   1241:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1242:     unless (defined($cached)) {
                   1243:         my %domconfig =
                   1244:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1245:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1246:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1247:         }
                   1248:     }
                   1249:     if (ref($result) eq 'HASH') {
                   1250:         my $currbalancer = $result->{'lonhost'};
                   1251:         my $currtargets = $result->{'targets'};
                   1252:         my $currrules = $result->{'rules'};
                   1253:         if ($currbalancer ne '') {
                   1254:             my @hosts = &current_machine_ids();
                   1255:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1256:                 $is_balancer = 1;
                   1257:             }
                   1258:         }
                   1259:         if ($is_balancer) {
                   1260:             if (ref($currrules) eq 'HASH') {
                   1261:                 if ($homeintdom) {
                   1262:                     if ($uname ne '') {
                   1263:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1264:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1265:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1266:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1267:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1268:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1269:                             }
                   1270:                         }
                   1271:                         if ($rule_in_effect eq '') {
                   1272:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1273:                             if ($userenv{'inststatus'} ne '') {
                   1274:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1275:                                 my ($othertitle,$usertypes,$types) =
                   1276:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1277:                                 if (ref($types) eq 'ARRAY') {
                   1278:                                     foreach my $type (@{$types}) {
                   1279:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1280:                                             if (exists($currrules->{$type})) {
                   1281:                                                 $rule_in_effect = $currrules->{$type};
                   1282:                                             }
                   1283:                                         }
                   1284:                                     }
                   1285:                                 }
                   1286:                             } else {
                   1287:                                 if (exists($currrules->{'default'})) {
                   1288:                                     $rule_in_effect = $currrules->{'default'};
                   1289:                                 }
                   1290:                             }
                   1291:                         }
                   1292:                     } else {
                   1293:                         if (exists($currrules->{'default'})) {
                   1294:                             $rule_in_effect = $currrules->{'default'};
                   1295:                         }
                   1296:                     }
                   1297:                 } else {
                   1298:                     if ($currrules->{'_LC_external'} ne '') {
                   1299:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1300:                     }
                   1301:                 }
                   1302:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1303:                                                        $uname,$udom);
                   1304:             }
                   1305:         }
                   1306:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1307:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1308:         unless (defined($cached)) {
                   1309:             my %domconfig =
                   1310:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1311:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1312:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1313:             }
                   1314:         }
                   1315:         if (ref($result) eq 'HASH') {
                   1316:             my $currbalancer = $result->{'lonhost'};
                   1317:             my $currtargets = $result->{'targets'};
                   1318:             my $currrules = $result->{'rules'};
                   1319: 
                   1320:             if ($currbalancer eq $lonhost) {
                   1321:                 $is_balancer = 1;
                   1322:                 if (ref($currrules) eq 'HASH') {
                   1323:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1324:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1325:                     }
                   1326:                 }
                   1327:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1328:                                                        $uname,$udom);
                   1329:             }
                   1330:         } else {
                   1331:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1332:                 $is_balancer = 1;
                   1333:                 $offloadto = &this_host_spares($dom_in_use);
                   1334:             }
                   1335:         }
                   1336:     } else {
                   1337:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1338:             $is_balancer = 1;
                   1339:             $offloadto = &this_host_spares($dom_in_use);
                   1340:         }
                   1341:     }
                   1342:     my $lowest_load = 30000;
                   1343:     if (ref($offloadto) eq 'HASH') {
                   1344:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1345:             foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1346:                 ($otherserver,$lowest_load) =
                   1347:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1348:             }
                   1349:         }
                   1350:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
                   1351: 
                   1352:         if (!$found_server) {
                   1353:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1354:                 foreach my $try_server (@{$offloadto->{'default'}}) {
                   1355:                     ($otherserver,$lowest_load) =
                   1356:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1357:                 }
                   1358:             }
                   1359:         }
                   1360:     } elsif (ref($offloadto) eq 'ARRAY') {
                   1361:         if (@{$offloadto} == 1) {
                   1362:             $otherserver = $offloadto->[0];
                   1363:         } elsif (@{$offloadto} > 1) {
                   1364:             foreach my $try_server (@{$offloadto}) {
                   1365:                 ($otherserver,$lowest_load) =
                   1366:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1367:             }
                   1368:         }
                   1369:     }
                   1370:     return ($is_balancer,$otherserver);
                   1371: }
                   1372: 
                   1373: sub get_loadbalancer_targets {
                   1374:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1375:     my $offloadto;
                   1376:     if ($rule_in_effect eq '') {
                   1377:         $offloadto = $currtargets;
                   1378:     } else {
                   1379:         if ($rule_in_effect eq 'homeserver') {
                   1380:             my $homeserver = &homeserver($uname,$udom);
                   1381:             if ($homeserver ne 'no_host') {
                   1382:                 $offloadto = [$homeserver];
                   1383:             }
                   1384:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1385:             my %domconfig =
                   1386:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1387:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1388:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1389:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1390:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1391:                     }
                   1392:                 }
                   1393:             } else {
                   1394:                 my %servers = &dom_servers($udom);
                   1395:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1396:                 if (&hostname($remotebalancer) ne '') {
                   1397:                     $offloadto = [$remotebalancer];
                   1398:                 }
                   1399:             }
                   1400:         } elsif (&hostname($rule_in_effect) ne '') {
                   1401:             $offloadto = [$rule_in_effect];
                   1402:         }
                   1403:     }
                   1404:     return $offloadto;
                   1405: }
                   1406: 
1.1127    raeburn  1407: sub internet_dom_servers {
                   1408:     my ($dom) = @_;
                   1409:     my (%uniqservers,%servers);
                   1410:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1411:     my @machinedoms = &machine_domains($primaryserver);
                   1412:     foreach my $mdom (@machinedoms) {
                   1413:         my %currservers = %servers;
                   1414:         my %server = &get_servers($mdom);
                   1415:         %servers = (%currservers,%server);
                   1416:     }
                   1417:     my %by_hostname;
                   1418:     foreach my $id (keys(%servers)) {
                   1419:         push(@{$by_hostname{$servers{$id}}},$id);
                   1420:     }
                   1421:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1422:         if (@{$by_hostname{$hostname}} > 1) {
                   1423:             my $match = 0;
                   1424:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1425:                 if (&host_domain($id) eq $dom) {
                   1426:                     $uniqservers{$id} = $hostname;
                   1427:                     $match = 1;
                   1428:                 }
                   1429:             }
                   1430:             unless ($match) {
                   1431:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1432:             }
                   1433:         } else {
                   1434:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1435:         }
                   1436:     }
                   1437:     return %uniqservers;
                   1438: }
                   1439: 
1.1       albertel 1440: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1441: 
1.599     albertel 1442: my %homecache;
1.1       albertel 1443: sub homeserver {
1.230     stredwic 1444:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1445:     my $index="$uname:$udom";
1.426     albertel 1446: 
1.599     albertel 1447:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1448: 
                   1449:     my %servers = &get_servers($udom,'library');
                   1450:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1451:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1452: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1453: 
                   1454: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1455: 	if ($answer eq 'found') {
                   1456: 	    delete($badServerCache{$tryserver}); 
                   1457: 	    return $homecache{$index}=$tryserver;
                   1458: 	} elsif ($answer eq 'no_host') {
                   1459: 	    $badServerCache{$tryserver}=1;
                   1460: 	}
1.1       albertel 1461:     }    
                   1462:     return 'no_host';
1.70      www      1463: }
                   1464: 
                   1465: # ------------------------------------- Find the usernames behind a list of IDs
                   1466: 
                   1467: sub idget {
                   1468:     my ($udom,@ids)=@_;
                   1469:     my %returnhash=();
                   1470:     
1.841     albertel 1471:     my %servers = &get_servers($udom,'library');
                   1472:     foreach my $tryserver (keys(%servers)) {
                   1473: 	my $idlist=join('&',@ids);
                   1474: 	$idlist=~tr/A-Z/a-z/; 
                   1475: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1476: 	my @answer=();
                   1477: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1478: 	    @answer=split(/\&/,$reply);
                   1479: 	}                    ;
                   1480: 	my $i;
                   1481: 	for ($i=0;$i<=$#ids;$i++) {
                   1482: 	    if ($answer[$i]) {
                   1483: 		$returnhash{$ids[$i]}=$answer[$i];
                   1484: 	    } 
                   1485: 	}
                   1486:     } 
1.70      www      1487:     return %returnhash;
                   1488: }
                   1489: 
                   1490: # ------------------------------------- Find the IDs behind a list of usernames
                   1491: 
                   1492: sub idrget {
                   1493:     my ($udom,@unames)=@_;
                   1494:     my %returnhash=();
1.800     albertel 1495:     foreach my $uname (@unames) {
                   1496:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1497:     }
1.70      www      1498:     return %returnhash;
                   1499: }
                   1500: 
                   1501: # ------------------------------- Store away a list of names and associated IDs
                   1502: 
                   1503: sub idput {
                   1504:     my ($udom,%ids)=@_;
                   1505:     my %servers=();
1.800     albertel 1506:     foreach my $uname (keys(%ids)) {
                   1507: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1508:         my $uhom=&homeserver($uname,$udom);
1.70      www      1509:         if ($uhom ne 'no_host') {
1.800     albertel 1510:             my $id=&escape($ids{$uname});
1.70      www      1511:             $id=~tr/A-Z/a-z/;
1.800     albertel 1512:             my $esc_unam=&escape($uname);
1.70      www      1513: 	    if ($servers{$uhom}) {
1.800     albertel 1514: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1515:             } else {
1.800     albertel 1516:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1517:             }
                   1518:         }
1.191     harris41 1519:     }
1.800     albertel 1520:     foreach my $server (keys(%servers)) {
                   1521:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1522:     }
1.344     www      1523: }
                   1524: 
1.1023    raeburn  1525: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1526: sub dump_dom {
1.1023    raeburn  1527:     my ($namespace,$udom,$regexp,$range)=@_;
1.1012    raeburn  1528:     if (!$udom) {
                   1529:         $udom=$env{'user.domain'};
                   1530:     }
                   1531:     my %returnhash;
1.1023    raeburn  1532:     if ($udom) {
                   1533:         my $uname = &get_domainconfiguser($udom);
                   1534:         %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012    raeburn  1535:     }
                   1536:     return %returnhash;
                   1537: }
                   1538: 
1.1023    raeburn  1539: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1540: 
                   1541: sub get_dom {
1.860     raeburn  1542:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1543:     my $items='';
                   1544:     foreach my $item (@$storearr) {
                   1545:         $items.=&escape($item).'&';
                   1546:     }
                   1547:     $items=~s/\&$//;
1.860     raeburn  1548:     if (!$udom) {
                   1549:         $udom=$env{'user.domain'};
                   1550:         if (defined(&domain($udom,'primary'))) {
                   1551:             $uhome=&domain($udom,'primary');
                   1552:         } else {
1.874     albertel 1553:             undef($uhome);
1.860     raeburn  1554:         }
                   1555:     } else {
                   1556:         if (!$uhome) {
                   1557:             if (defined(&domain($udom,'primary'))) {
                   1558:                 $uhome=&domain($udom,'primary');
                   1559:             }
                   1560:         }
                   1561:     }
                   1562:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1563:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1564:         my %returnhash;
1.875     albertel 1565:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1566:             return %returnhash;
                   1567:         }
1.806     raeburn  1568:         my @pairs=split(/\&/,$rep);
                   1569:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1570:             return @pairs;
                   1571:         }
                   1572:         my $i=0;
                   1573:         foreach my $item (@$storearr) {
                   1574:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1575:             $i++;
                   1576:         }
                   1577:         return %returnhash;
                   1578:     } else {
1.880     banghart 1579:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1580:     }
                   1581: }
                   1582: 
                   1583: # -------------------------------------------- put items in domain db files 
                   1584: 
                   1585: sub put_dom {
1.860     raeburn  1586:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1587:     if (!$udom) {
                   1588:         $udom=$env{'user.domain'};
                   1589:         if (defined(&domain($udom,'primary'))) {
                   1590:             $uhome=&domain($udom,'primary');
                   1591:         } else {
1.874     albertel 1592:             undef($uhome);
1.860     raeburn  1593:         }
                   1594:     } else {
                   1595:         if (!$uhome) {
                   1596:             if (defined(&domain($udom,'primary'))) {
                   1597:                 $uhome=&domain($udom,'primary');
                   1598:             }
                   1599:         }
                   1600:     } 
                   1601:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1602:         my $items='';
                   1603:         foreach my $item (keys(%$storehash)) {
                   1604:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1605:         }
                   1606:         $items=~s/\&$//;
                   1607:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1608:     } else {
1.860     raeburn  1609:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1610:     }
                   1611: }
                   1612: 
1.1023    raeburn  1613: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1614: sub newput_dom {
1.1023    raeburn  1615:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1616:     my $result;
                   1617:     if (!$udom) {
                   1618:         $udom=$env{'user.domain'};
                   1619:     }
1.1023    raeburn  1620:     if ($udom) {
                   1621:         my $uname = &get_domainconfiguser($udom);
                   1622:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1623:     }
                   1624:     return $result;
                   1625: }
                   1626: 
1.1023    raeburn  1627: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1628: sub del_dom {
1.1023    raeburn  1629:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1630:     if (ref($storearr) eq 'ARRAY') {
                   1631:         if (!$udom) {
                   1632:             $udom=$env{'user.domain'};
                   1633:         }
1.1023    raeburn  1634:         if ($udom) {
                   1635:             my $uname = &get_domainconfiguser($udom); 
                   1636:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1637:         }
                   1638:     }
                   1639: }
                   1640: 
1.1023    raeburn  1641: # ----------------------------------construct domainconfig user for a domain 
                   1642: sub get_domainconfiguser {
                   1643:     my ($udom) = @_;
                   1644:     return $udom.'-domainconfig';
                   1645: }
                   1646: 
1.837     raeburn  1647: sub retrieve_inst_usertypes {
                   1648:     my ($udom) = @_;
                   1649:     my (%returnhash,@order);
1.989     raeburn  1650:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1651:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1652:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1653:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1654:         @order = @{$domdefs{'inststatusorder'}};
                   1655:     } else {
                   1656:         if (defined(&domain($udom,'primary'))) {
                   1657:             my $uhome=&domain($udom,'primary');
                   1658:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1659:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1660:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1661:                 return (\%returnhash,\@order);
                   1662:             }
                   1663:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1664:             my @pairs=split(/\&/,$hashitems);
                   1665:             foreach my $item (@pairs) {
                   1666:                 my ($key,$value)=split(/=/,$item,2);
                   1667:                 $key = &unescape($key);
                   1668:                 next if ($key =~ /^error: 2 /);
                   1669:                 $returnhash{$key}=&thaw_unescape($value);
                   1670:             }
                   1671:             my @esc_order = split(/\&/,$orderitems);
                   1672:             foreach my $item (@esc_order) {
                   1673:                 push(@order,&unescape($item));
                   1674:             }
                   1675:         } else {
                   1676:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1677:         }
                   1678:     }
                   1679:     return (\%returnhash,\@order);
                   1680: }
                   1681: 
1.868     raeburn  1682: sub is_domainimage {
                   1683:     my ($url) = @_;
                   1684:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1685:         if (&domain($1) ne '') {
                   1686:             return '1';
                   1687:         }
                   1688:     }
                   1689:     return;
                   1690: }
                   1691: 
1.899     raeburn  1692: sub inst_directory_query {
                   1693:     my ($srch) = @_;
                   1694:     my $udom = $srch->{'srchdomain'};
                   1695:     my %results;
                   1696:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1697:     my $outcome;
1.899     raeburn  1698:     if ($homeserver ne '') {
1.904     albertel 1699: 	my $queryid=&reply("querysend:instdirsearch:".
                   1700: 			   &escape($srch->{'srchby'}).':'.
                   1701: 			   &escape($srch->{'srchterm'}).':'.
                   1702: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1703: 	my $host=&hostname($homeserver);
                   1704: 	if ($queryid !~/^\Q$host\E\_/) {
                   1705: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1706: 	    return;
                   1707: 	}
                   1708: 	my $response = &get_query_reply($queryid);
                   1709: 	my $maxtries = 5;
                   1710: 	my $tries = 1;
                   1711: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1712: 	    $response = &get_query_reply($queryid);
                   1713: 	    $tries ++;
                   1714: 	}
                   1715: 
                   1716:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1717:             if ($response eq 'unavailable') {
                   1718:                 $outcome = $response;
                   1719:             } else {
                   1720:                 $outcome = 'ok';
                   1721:                 my @matches = split(/\n/,$response);
                   1722:                 foreach my $match (@matches) {
                   1723:                     my ($key,$value) = split(/=/,$match);
                   1724:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1725:                 }
1.899     raeburn  1726:             }
                   1727:         }
                   1728:     }
1.909     raeburn  1729:     return ($outcome,%results);
1.899     raeburn  1730: }
                   1731: 
                   1732: sub usersearch {
                   1733:     my ($srch) = @_;
                   1734:     my $dom = $srch->{'srchdomain'};
                   1735:     my %results;
                   1736:     my %libserv = &all_library();
                   1737:     my $query = 'usersearch';
                   1738:     foreach my $tryserver (keys(%libserv)) {
                   1739:         if (&host_domain($tryserver) eq $dom) {
                   1740:             my $host=&hostname($tryserver);
                   1741:             my $queryid=
1.911     raeburn  1742:                 &reply("querysend:".&escape($query).':'.
                   1743:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1744:                        &escape($srch->{'srchtype'}).':'.
                   1745:                        &escape($srch->{'srchterm'}),$tryserver);
                   1746:             if ($queryid !~/^\Q$host\E\_/) {
                   1747:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1748:                 next;
1.899     raeburn  1749:             }
                   1750:             my $reply = &get_query_reply($queryid);
                   1751:             my $maxtries = 1;
                   1752:             my $tries = 1;
                   1753:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1754:                 $reply = &get_query_reply($queryid);
                   1755:                 $tries ++;
                   1756:             }
                   1757:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1758:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1759:             } else {
1.911     raeburn  1760:                 my @matches;
                   1761:                 if ($reply =~ /\n/) {
                   1762:                     @matches = split(/\n/,$reply);
                   1763:                 } else {
                   1764:                     @matches = split(/\&/,$reply);
                   1765:                 }
1.899     raeburn  1766:                 foreach my $match (@matches) {
                   1767:                     my ($uname,$udom,%userhash);
1.911     raeburn  1768:                     foreach my $entry (split(/:/,$match)) {
                   1769:                         my ($key,$value) =
                   1770:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1771:                         $userhash{$key} = $value;
                   1772:                         if ($key eq 'username') {
                   1773:                             $uname = $value;
                   1774:                         } elsif ($key eq 'domain') {
                   1775:                             $udom = $value;
1.911     raeburn  1776:                         }
1.899     raeburn  1777:                     }
                   1778:                     $results{$uname.':'.$udom} = \%userhash;
                   1779:                 }
                   1780:             }
                   1781:         }
                   1782:     }
                   1783:     return %results;
                   1784: }
                   1785: 
1.912     raeburn  1786: sub get_instuser {
                   1787:     my ($udom,$uname,$id) = @_;
                   1788:     my $homeserver = &domain($udom,'primary');
                   1789:     my ($outcome,%results);
                   1790:     if ($homeserver ne '') {
                   1791:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1792:                            &escape($id).':'.&escape($udom),$homeserver);
                   1793:         my $host=&hostname($homeserver);
                   1794:         if ($queryid !~/^\Q$host\E\_/) {
                   1795:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1796:             return;
                   1797:         }
                   1798:         my $response = &get_query_reply($queryid);
                   1799:         my $maxtries = 5;
                   1800:         my $tries = 1;
                   1801:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1802:             $response = &get_query_reply($queryid);
                   1803:             $tries ++;
                   1804:         }
                   1805:         if (!&error($response) && $response ne 'refused') {
                   1806:             if ($response eq 'unavailable') {
                   1807:                 $outcome = $response;
                   1808:             } else {
                   1809:                 $outcome = 'ok';
                   1810:                 my @matches = split(/\n/,$response);
                   1811:                 foreach my $match (@matches) {
                   1812:                     my ($key,$value) = split(/=/,$match);
                   1813:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1814:                 }
                   1815:             }
                   1816:         }
                   1817:     }
                   1818:     my %userinfo;
                   1819:     if (ref($results{$uname}) eq 'HASH') {
                   1820:         %userinfo = %{$results{$uname}};
                   1821:     } 
                   1822:     return ($outcome,%userinfo);
                   1823: }
                   1824: 
                   1825: sub inst_rulecheck {
1.923     raeburn  1826:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1827:     my %returnhash;
                   1828:     if ($udom ne '') {
                   1829:         if (ref($rules) eq 'ARRAY') {
                   1830:             @{$rules} = map {&escape($_);} (@{$rules});
                   1831:             my $rulestr = join(':',@{$rules});
                   1832:             my $homeserver=&domain($udom,'primary');
                   1833:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1834:                 my $response;
                   1835:                 if ($item eq 'username') {                
                   1836:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1837:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1838:                                               $homeserver));
1.923     raeburn  1839:                 } elsif ($item eq 'id') {
                   1840:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1841:                                               ':'.&escape($id).':'.$rulestr,
                   1842:                                               $homeserver));
1.945     raeburn  1843:                 } elsif ($item eq 'selfcreate') {
                   1844:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1845:                                                &escape($udom).':'.&escape($uname).
                   1846:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1847:                 }
1.912     raeburn  1848:                 if ($response ne 'refused') {
                   1849:                     my @pairs=split(/\&/,$response);
                   1850:                     foreach my $item (@pairs) {
                   1851:                         my ($key,$value)=split(/=/,$item,2);
                   1852:                         $key = &unescape($key);
                   1853:                         next if ($key =~ /^error: 2 /);
                   1854:                         $returnhash{$key}=&thaw_unescape($value);
                   1855:                     }
                   1856:                 }
                   1857:             }
                   1858:         }
                   1859:     }
                   1860:     return %returnhash;
                   1861: }
                   1862: 
                   1863: sub inst_userrules {
1.923     raeburn  1864:     my ($udom,$check) = @_;
1.912     raeburn  1865:     my (%ruleshash,@ruleorder);
                   1866:     if ($udom ne '') {
                   1867:         my $homeserver=&domain($udom,'primary');
                   1868:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1869:             my $response;
                   1870:             if ($check eq 'id') {
                   1871:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1872:                                  $homeserver);
1.943     raeburn  1873:             } elsif ($check eq 'email') {
                   1874:                 $response=&reply('instemailrules:'.&escape($udom),
                   1875:                                  $homeserver);
1.923     raeburn  1876:             } else {
                   1877:                 $response=&reply('instuserrules:'.&escape($udom),
                   1878:                                  $homeserver);
                   1879:             }
1.912     raeburn  1880:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1881:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1882:                 ($response ne 'no_such_host')) {
                   1883:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1884:                 my @pairs=split(/\&/,$hashitems);
                   1885:                 foreach my $item (@pairs) {
                   1886:                     my ($key,$value)=split(/=/,$item,2);
                   1887:                     $key = &unescape($key);
                   1888:                     next if ($key =~ /^error: 2 /);
                   1889:                     $ruleshash{$key}=&thaw_unescape($value);
                   1890:                 }
                   1891:                 my @esc_order = split(/\&/,$orderitems);
                   1892:                 foreach my $item (@esc_order) {
                   1893:                     push(@ruleorder,&unescape($item));
                   1894:                 }
                   1895:             }
                   1896:         }
                   1897:     }
                   1898:     return (\%ruleshash,\@ruleorder);
                   1899: }
                   1900: 
1.976     raeburn  1901: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1902: 
                   1903: sub get_domain_defaults {
                   1904:     my ($domain) = @_;
                   1905:     my $cachetime = 60*60*24;
                   1906:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1907:     if (defined($cached)) {
                   1908:         if (ref($result) eq 'HASH') {
                   1909:             return %{$result};
                   1910:         }
                   1911:     }
                   1912:     my %domdefaults;
                   1913:     my %domconfig =
1.989     raeburn  1914:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1915:                                   'requestcourses','inststatus',
1.1073    raeburn  1916:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1917:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1918:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1919:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1920:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1921:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1922:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147  ! raeburn  1923:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1924:     } else {
                   1925:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1926:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1927:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1928:     }
1.976     raeburn  1929:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1930:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1931:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1932:         } else {
                   1933:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1934:         } 
                   1935:         my @usertools = ('aboutme','blog','portfolio');
                   1936:         foreach my $item (@usertools) {
                   1937:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1938:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1939:             }
                   1940:         }
                   1941:     }
1.985     raeburn  1942:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1943:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1944:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1945:         }
                   1946:     }
1.989     raeburn  1947:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1948:         foreach my $item ('inststatustypes','inststatusorder') {
                   1949:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1950:         }
                   1951:     }
1.1047    raeburn  1952:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1953:         foreach my $item ('canuse_pdfforms') {
                   1954:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1955:         }
                   1956:     }
1.1073    raeburn  1957:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1958:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1959:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1960:         }
                   1961:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1962:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1963:         }
                   1964:     }
1.943     raeburn  1965:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1966:                                   $cachetime);
                   1967:     return %domdefaults;
                   1968: }
                   1969: 
1.344     www      1970: # --------------------------------------------------- Assign a key to a student
                   1971: 
                   1972: sub assign_access_key {
1.364     www      1973: #
                   1974: # a valid key looks like uname:udom#comments
                   1975: # comments are being appended
                   1976: #
1.498     www      1977:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1978:     $kdom=
1.620     albertel 1979:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1980:     $knum=
1.620     albertel 1981:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1982:     $cdom=
1.620     albertel 1983:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      1984:     $cnum=
1.620     albertel 1985:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   1986:     $udom=$env{'user.name'} unless (defined($udom));
                   1987:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      1988:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      1989:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 1990:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      1991:                                                   # assigned to this person
                   1992:                                                   # - this should not happen,
1.345     www      1993:                                                   # unless something went wrong
                   1994:                                                   # the first time around
                   1995: # ready to assign
1.364     www      1996:         $logentry=$1.'; '.$logentry;
1.496     www      1997:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      1998:                                                  $kdom,$knum) eq 'ok') {
1.345     www      1999: # key now belongs to user
1.346     www      2000: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2001:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2002:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2003:                 return 'ok';
                   2004:             } else {
                   2005:                 return 
                   2006:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2007: 	    }
                   2008:         } else {
                   2009:             return 'error: Could not assign key, try again later.';
                   2010:         }
1.364     www      2011:     } elsif (!$existing{$ckey}) {
1.345     www      2012: # the key does not exist
                   2013: 	return 'error: The key does not exist';
                   2014:     } else {
                   2015: # the key is somebody else's
                   2016: 	return 'error: The key is already in use';
                   2017:     }
1.344     www      2018: }
                   2019: 
1.364     www      2020: # ------------------------------------------ put an additional comment on a key
                   2021: 
                   2022: sub comment_access_key {
                   2023: #
                   2024: # a valid key looks like uname:udom#comments
                   2025: # comments are being appended
                   2026: #
                   2027:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2028:     $cdom=
1.620     albertel 2029:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2030:     $cnum=
1.620     albertel 2031:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2032:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2033:     if ($existing{$ckey}) {
                   2034:         $existing{$ckey}.='; '.$logentry;
                   2035: # ready to assign
1.367     www      2036:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2037:                                                  $cdom,$cnum) eq 'ok') {
                   2038: 	    return 'ok';
                   2039:         } else {
                   2040: 	    return 'error: Count not store comment.';
                   2041:         }
                   2042:     } else {
                   2043: # the key does not exist
                   2044: 	return 'error: The key does not exist';
                   2045:     }
                   2046: }
                   2047: 
1.344     www      2048: # ------------------------------------------------------ Generate a set of keys
                   2049: 
                   2050: sub generate_access_keys {
1.364     www      2051:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2052:     $cdom=
1.620     albertel 2053:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2054:     $cnum=
1.620     albertel 2055:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2056:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2057:     unless (($cdom) && ($cnum)) { return 0; }
                   2058:     if ($number>10000) { return 0; }
                   2059:     sleep(2); # make sure don't get same seed twice
                   2060:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2061:     my $total=0;
                   2062:     for (my $i=1;$i<=$number;$i++) {
                   2063:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2064:                   sprintf("%lx",int(100000*rand)).'-'.
                   2065:                   sprintf("%lx",int(100000*rand));
                   2066:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2067:        $newkey=~s/0/h/g; # and also 0 and O
                   2068:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2069:        if ($existing{$newkey}) {
                   2070:            $i--;
                   2071:        } else {
1.364     www      2072: 	  if (&put('accesskeys',
                   2073:               { $newkey => '# generated '.localtime().
1.620     albertel 2074:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2075:                            '; '.$logentry },
                   2076: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2077:               $total++;
                   2078: 	  }
                   2079:        }
                   2080:     }
1.620     albertel 2081:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2082:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2083:     return $total;
                   2084: }
                   2085: 
                   2086: # ------------------------------------------------------- Validate an accesskey
                   2087: 
                   2088: sub validate_access_key {
                   2089:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2090:     $cdom=
1.620     albertel 2091:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2092:     $cnum=
1.620     albertel 2093:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2094:     $udom=$env{'user.domain'} unless (defined($udom));
                   2095:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2096:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2097:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2098: }
                   2099: 
                   2100: # ------------------------------------- Find the section of student in a course
1.652     albertel 2101: sub devalidate_getsection_cache {
                   2102:     my ($udom,$unam,$courseid)=@_;
                   2103:     my $hashid="$udom:$unam:$courseid";
                   2104:     &devalidate_cache_new('getsection',$hashid);
                   2105: }
1.298     matthew  2106: 
1.815     albertel 2107: sub courseid_to_courseurl {
                   2108:     my ($courseid) = @_;
                   2109:     #already url style courseid
                   2110:     return $courseid if ($courseid =~ m{^/});
                   2111: 
                   2112:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2113: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2114: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2115: 	return "/$cdom/$cnum";
                   2116:     }
                   2117: 
                   2118:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2119:     if (exists($courseinfo{'num'})) {
                   2120: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2121:     }
                   2122: 
                   2123:     return undef;
                   2124: }
                   2125: 
1.298     matthew  2126: sub getsection {
                   2127:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2128:     my $cachetime=1800;
1.551     albertel 2129: 
                   2130:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2131:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2132:     if (defined($cached)) { return $result; }
                   2133: 
1.298     matthew  2134:     my %Pending; 
                   2135:     my %Expired;
                   2136:     #
                   2137:     # Each role can either have not started yet (pending), be active, 
                   2138:     #    or have expired.
                   2139:     #
                   2140:     # If there is an active role, we are done.
                   2141:     #
                   2142:     # If there is more than one role which has not started yet, 
                   2143:     #     choose the one which will start sooner
                   2144:     # If there is one role which has not started yet, return it.
                   2145:     #
                   2146:     # If there is more than one expired role, choose the one which ended last.
                   2147:     # If there is a role which has expired, return it.
                   2148:     #
1.815     albertel 2149:     $courseid = &courseid_to_courseurl($courseid);
1.1086    raeburn  2150:     my $extra = &freeze_escape({'skipcheck' => 1});
                   2151:     my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817     raeburn  2152:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2153:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2154:         my $section=$1;
                   2155:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2156:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2157:         my $now=time;
1.548     albertel 2158:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2159:             $Expired{$end}=$section;
                   2160:             next;
                   2161:         }
1.548     albertel 2162:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2163:             $Pending{$start}=$section;
                   2164:             next;
                   2165:         }
1.599     albertel 2166:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2167:     }
                   2168:     #
                   2169:     # Presumedly there will be few matching roles from the above
                   2170:     # loop and the sorting time will be negligible.
                   2171:     if (scalar(keys(%Pending))) {
                   2172:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2173:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2174:     } 
                   2175:     if (scalar(keys(%Expired))) {
                   2176:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2177:         my $time = pop(@sorted);
1.599     albertel 2178:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2179:     }
1.599     albertel 2180:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2181: }
1.70      www      2182: 
1.599     albertel 2183: sub save_cache {
                   2184:     &purge_remembered();
1.722     albertel 2185:     #&Apache::loncommon::validate_page();
1.620     albertel 2186:     undef(%env);
1.780     albertel 2187:     undef($env_loaded);
1.599     albertel 2188: }
1.452     albertel 2189: 
1.599     albertel 2190: my $to_remember=-1;
                   2191: my %remembered;
                   2192: my %accessed;
                   2193: my $kicks=0;
                   2194: my $hits=0;
1.849     albertel 2195: sub make_key {
                   2196:     my ($name,$id) = @_;
1.872     albertel 2197:     if (length($id) > 65 
                   2198: 	&& length(&escape($id)) > 200) {
                   2199: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2200:     }
1.849     albertel 2201:     return &escape($name.':'.$id);
                   2202: }
                   2203: 
1.599     albertel 2204: sub devalidate_cache_new {
                   2205:     my ($name,$id,$debug) = @_;
                   2206:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2207:     $id=&make_key($name,$id);
1.599     albertel 2208:     $memcache->delete($id);
                   2209:     delete($remembered{$id});
                   2210:     delete($accessed{$id});
                   2211: }
                   2212: 
                   2213: sub is_cached_new {
                   2214:     my ($name,$id,$debug) = @_;
1.849     albertel 2215:     $id=&make_key($name,$id);
1.599     albertel 2216:     if (exists($remembered{$id})) {
1.1133    foxr     2217: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2218: 	$accessed{$id}=[&gettimeofday()];
                   2219: 	$hits++;
                   2220: 	return ($remembered{$id},1);
                   2221:     }
                   2222:     my $value = $memcache->get($id);
                   2223:     if (!(defined($value))) {
                   2224: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2225: 	return (undef,undef);
1.416     albertel 2226:     }
1.599     albertel 2227:     if ($value eq '__undef__') {
                   2228: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2229: 	$value=undef;
                   2230:     }
                   2231:     &make_room($id,$value,$debug);
                   2232:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2233:     return ($value,1);
                   2234: }
                   2235: 
                   2236: sub do_cache_new {
                   2237:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2238:     $id=&make_key($name,$id);
1.599     albertel 2239:     my $setvalue=$value;
                   2240:     if (!defined($setvalue)) {
                   2241: 	$setvalue='__undef__';
                   2242:     }
1.623     albertel 2243:     if (!defined($time) ) {
                   2244: 	$time=600;
                   2245:     }
1.599     albertel 2246:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2247:     my $result = $memcache->set($id,$setvalue,$time);
                   2248:     if (! $result) {
1.872     albertel 2249: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2250: 	$memcache->disconnect_all();
1.872     albertel 2251:     }
1.600     albertel 2252:     # need to make a copy of $value
1.919     albertel 2253:     &make_room($id,$value,$debug);
1.599     albertel 2254:     return $value;
                   2255: }
                   2256: 
                   2257: sub make_room {
                   2258:     my ($id,$value,$debug)=@_;
1.919     albertel 2259: 
                   2260:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2261:                                     : $value;
1.599     albertel 2262:     if ($to_remember<0) { return; }
                   2263:     $accessed{$id}=[&gettimeofday()];
                   2264:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2265:     my $to_kick;
                   2266:     my $max_time=0;
                   2267:     foreach my $other (keys(%accessed)) {
                   2268: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2269: 	    $to_kick=$other;
                   2270: 	    $max_time=&tv_interval($accessed{$other});
                   2271: 	}
                   2272:     }
                   2273:     delete($remembered{$to_kick});
                   2274:     delete($accessed{$to_kick});
                   2275:     $kicks++;
                   2276:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2277:     return;
                   2278: }
                   2279: 
1.599     albertel 2280: sub purge_remembered {
1.604     albertel 2281:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2282:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2283:     undef(%remembered);
                   2284:     undef(%accessed);
1.428     albertel 2285: }
1.70      www      2286: # ------------------------------------- Read an entry from a user's environment
                   2287: 
                   2288: sub userenvironment {
                   2289:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2290:     my $items;
                   2291:     foreach my $item (@what) {
                   2292:         $items.=&escape($item).'&';
                   2293:     }
                   2294:     $items=~s/\&$//;
1.70      www      2295:     my %returnhash=();
1.1009    raeburn  2296:     my $uhome = &homeserver($unam,$udom);
                   2297:     unless ($uhome eq 'no_host') {
                   2298:         my @answer=split(/\&/, 
                   2299:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2300:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2301:             return %returnhash;
                   2302:         }
1.1009    raeburn  2303:         my $i;
                   2304:         for ($i=0;$i<=$#what;$i++) {
                   2305: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2306:         }
1.70      www      2307:     }
                   2308:     return %returnhash;
1.1       albertel 2309: }
                   2310: 
1.617     albertel 2311: # ---------------------------------------------------------- Get a studentphoto
                   2312: sub studentphoto {
                   2313:     my ($udom,$unam,$ext) = @_;
                   2314:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2315:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2316:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2317:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2318:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2319:             } else {
                   2320:                 my ($result,$perm_reqd)=
1.707     albertel 2321: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2322:                 if ($result eq 'ok') {
                   2323:                     if (!($perm_reqd eq 'yes')) {
                   2324:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2325:                     }
                   2326:                 }
                   2327:             }
                   2328:         }
                   2329:     } else {
                   2330:         my ($result,$perm_reqd) = 
1.707     albertel 2331: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2332:         if ($result eq 'ok') {
                   2333:             if (!($perm_reqd eq 'yes')) {
                   2334:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2335:             }
                   2336:         }
                   2337:     }
                   2338:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2339: }
                   2340: 
                   2341: sub retrievestudentphoto {
                   2342:     my ($udom,$unam,$ext,$type) = @_;
                   2343:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2344:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2345:     if ($ret eq 'ok') {
                   2346:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2347:         if ($type eq 'thumbnail') {
                   2348:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2349:         }
                   2350:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2351:         return $tokenurl;
                   2352:     } else {
                   2353:         if ($type eq 'thumbnail') {
                   2354:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2355:         } else { 
                   2356:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2357:         }
1.617     albertel 2358:     }
                   2359: }
                   2360: 
1.263     www      2361: # -------------------------------------------------------------------- New chat
                   2362: 
                   2363: sub chatsend {
1.724     raeburn  2364:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2365:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2366:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2367:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2368:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2369: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2370: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2371: }
                   2372: 
                   2373: # ------------------------------------------ Find current version of a resource
                   2374: 
                   2375: sub getversion {
                   2376:     my $fname=&clutter(shift);
                   2377:     unless ($fname=~/^\/res\//) { return -1; }
                   2378:     return &currentversion(&filelocation('',$fname));
                   2379: }
                   2380: 
                   2381: sub currentversion {
                   2382:     my $fname=shift;
                   2383:     my $author=$fname;
                   2384:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2385:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2386:     my $home=&homeserver($uname,$udom);
1.292     www      2387:     if ($home eq 'no_host') { 
                   2388:         return -1; 
                   2389:     }
1.1112    www      2390:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2391:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2392: 	return -1;
                   2393:     }
1.1112    www      2394:     return $answer;
1.263     www      2395: }
                   2396: 
1.1111    www      2397: #
                   2398: # Return special version number of resource if set by override, empty otherwise
                   2399: #
                   2400: sub usedversion {
                   2401:     my $fname=shift;
                   2402:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2403:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2404:     if ($urlversion) { return $urlversion; }
                   2405:     return '';
                   2406: }
                   2407: 
1.1       albertel 2408: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2409: 
1.1       albertel 2410: sub subscribe {
                   2411:     my $fname=shift;
1.761     raeburn  2412:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2413:     $fname=~s/[\n\r]//g;
1.1       albertel 2414:     my $author=$fname;
                   2415:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2416:     my ($udom,$uname)=split(/\//,$author);
                   2417:     my $home=homeserver($uname,$udom);
1.335     albertel 2418:     if ($home eq 'no_host') {
                   2419:         return 'not_found';
1.1       albertel 2420:     }
                   2421:     my $answer=reply("sub:$fname",$home);
1.64      www      2422:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2423: 	$answer.=' by '.$home;
                   2424:     }
1.1       albertel 2425:     return $answer;
                   2426: }
                   2427:     
1.8       www      2428: # -------------------------------------------------------------- Replicate file
                   2429: 
                   2430: sub repcopy {
                   2431:     my $filename=shift;
1.23      www      2432:     $filename=~s/\/+/\//g;
1.1142    raeburn  2433:     my $londocroot = $perlvar{'lonDocRoot'};
                   2434:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
                   2435:     if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
                   2436:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2437: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2438: 	return &repcopy_userfile($filename);
                   2439:     }
1.532     albertel 2440:     $filename=~s/[\n\r]//g;
1.8       www      2441:     my $transname="$filename.in.transfer";
1.828     www      2442: # FIXME: this should flock
1.607     raeburn  2443:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2444:     my $remoteurl=subscribe($filename);
1.64      www      2445:     if ($remoteurl =~ /^con_lost by/) {
                   2446: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2447:            return 'unavailable';
1.8       www      2448:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2449: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2450: 	   return 'not_found';
1.64      www      2451:     } elsif ($remoteurl =~ /^rejected by/) {
                   2452: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2453:            return 'forbidden';
1.20      www      2454:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2455:            return 'ok';
1.8       www      2456:     } else {
1.290     www      2457:         my $author=$filename;
                   2458:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2459:         my ($udom,$uname)=split(/\//,$author);
                   2460:         my $home=homeserver($uname,$udom);
                   2461:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2462:            my @parts=split(/\//,$filename);
                   2463:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2464:            if ($path ne "$londocroot/res") {
1.8       www      2465:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2466: 	       return 'bad_request';
1.8       www      2467:            }
                   2468:            my $count;
                   2469:            for ($count=5;$count<$#parts;$count++) {
                   2470:                $path.="/$parts[$count]";
                   2471:                if ((-e $path)!=1) {
                   2472: 		   mkdir($path,0777);
                   2473:                }
                   2474:            }
                   2475:            my $ua=new LWP::UserAgent;
                   2476:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2477:            my $response=$ua->request($request,$transname);
                   2478:            if ($response->is_error()) {
                   2479: 	       unlink($transname);
                   2480:                my $message=$response->status_line;
1.672     albertel 2481:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2482:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2483:                return 'unavailable';
1.8       www      2484:            } else {
1.16      www      2485: 	       if ($remoteurl!~/\.meta$/) {
                   2486:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2487:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2488:                   if ($mresponse->is_error()) {
                   2489: 		      unlink($filename.'.meta');
                   2490:                       &logthis(
1.672     albertel 2491:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2492:                   }
                   2493: 	       }
1.8       www      2494:                rename($transname,$filename);
1.607     raeburn  2495:                return 'ok';
1.8       www      2496:            }
1.290     www      2497:        }
1.8       www      2498:     }
1.330     www      2499: }
                   2500: 
                   2501: # ------------------------------------------------ Get server side include body
                   2502: sub ssi_body {
1.381     albertel 2503:     my ($filelink,%form)=@_;
1.606     matthew  2504:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2505:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2506:     }
1.953     www      2507:     my $output='';
                   2508:     my $response;
1.980     raeburn  2509:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2510:        ($output,$response)=&externalssi($filelink);
1.953     www      2511:     } else {
1.1004    droeschl 2512:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2513:        $filelink .= 'inhibitmenu=yes';
1.953     www      2514:        ($output,$response)=&ssi($filelink,%form);
                   2515:     }
1.778     albertel 2516:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2517:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2518:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2519:     if (wantarray) {
                   2520:         return ($output, $response);
                   2521:     } else {
                   2522:         return $output;
                   2523:     }
1.8       www      2524: }
                   2525: 
1.15      www      2526: # --------------------------------------------------------- Server Side Include
                   2527: 
1.782     albertel 2528: sub absolute_url {
                   2529:     my ($host_name) = @_;
                   2530:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2531:     if ($host_name eq '') {
                   2532: 	$host_name = $ENV{'SERVER_NAME'};
                   2533:     }
                   2534:     return $protocol.$host_name;
                   2535: }
                   2536: 
1.942     foxr     2537: #
                   2538: #   Server side include.
                   2539: # Parameters:
                   2540: #  fn     Possibly encrypted resource name/id.
                   2541: #  form   Hash that describes how the rendering should be done
                   2542: #         and other things.
1.944     foxr     2543: # Returns:
1.950     raeburn  2544: #   Scalar context: The content of the response.
                   2545: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2546: #     
1.15      www      2547: sub ssi {
                   2548: 
1.944     foxr     2549:     my ($fn,%form)=@_;
1.15      www      2550:     my $ua=new LWP::UserAgent;
1.23      www      2551:     my $request;
1.711     albertel 2552: 
                   2553:     $form{'no_update_last_known'}=1;
1.895     albertel 2554:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2555:     if (%form) {
1.782     albertel 2556:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2557:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2558:     } else {
1.782     albertel 2559:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2560:     }
                   2561: 
1.15      www      2562:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
                   2563:     my $response=$ua->request($request);
                   2564: 
1.944     foxr     2565:     if (wantarray) {
                   2566: 	return ($response->content, $response);
                   2567:     } else {
                   2568: 	return $response->content;
1.942     foxr     2569:     }
1.324     www      2570: }
                   2571: 
                   2572: sub externalssi {
                   2573:     my ($url)=@_;
                   2574:     my $ua=new LWP::UserAgent;
                   2575:     my $request=new HTTP::Request('GET',$url);
                   2576:     my $response=$ua->request($request);
1.954     raeburn  2577:     if (wantarray) {
                   2578:         return ($response->content, $response);
                   2579:     } else {
                   2580:         return $response->content;
                   2581:     }
1.15      www      2582: }
1.254     www      2583: 
1.492     albertel 2584: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2585: 
                   2586: sub allowuploaded {
                   2587:     my ($srcurl,$url)=@_;
                   2588:     $url=&clutter(&declutter($url));
                   2589:     my $dir=$url;
                   2590:     $dir=~s/\/[^\/]+$//;
                   2591:     my %httpref=();
                   2592:     my $httpurl=&hreflocation('',$url);
                   2593:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2594:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2595: }
1.477     raeburn  2596: 
1.478     albertel 2597: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2598: # input: action, courseID, current domain, intended
1.637     raeburn  2599: #        path to file, source of file, instruction to parse file for objects,
                   2600: #        ref to hash for embedded objects,
                   2601: #        ref to hash for codebase of java objects.
1.1095    raeburn  2602: #        reference to scalar to accommodate mime type determined
                   2603: #          from File::MMagic if $parser = parse.
1.637     raeburn  2604: #
1.485     raeburn  2605: # output: url to file (if action was uploaddoc), 
                   2606: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2607: #
1.478     albertel 2608: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2609: # course.
1.477     raeburn  2610: #
1.478     albertel 2611: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2612: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2613: #          course's home server.
1.477     raeburn  2614: #
1.478     albertel 2615: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2616: #          be copied from $source (current location) to 
                   2617: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2618: #         and will then be copied to
                   2619: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2620: #         course's home server.
1.485     raeburn  2621: #
1.481     raeburn  2622: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2623: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2624: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2625: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2626: #         in course's home server.
1.637     raeburn  2627: #
1.477     raeburn  2628: 
                   2629: sub process_coursefile {
1.1095    raeburn  2630:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2631:         $mimetype)=@_;
1.477     raeburn  2632:     my $fetchresult;
1.638     albertel 2633:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2634:     if ($action eq 'propagate') {
1.638     albertel 2635:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2636: 			     $home);
1.481     raeburn  2637:     } else {
1.477     raeburn  2638:         my $fpath = '';
                   2639:         my $fname = $file;
1.478     albertel 2640:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2641:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2642:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2643:         if ($action eq 'copy') {
                   2644:             if ($source eq '') {
                   2645:                 $fetchresult = 'no source file';
                   2646:                 return $fetchresult;
                   2647:             } else {
                   2648:                 my $destination = $filepath.'/'.$fname;
                   2649:                 rename($source,$destination);
                   2650:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2651:                                  $home);
1.481     raeburn  2652:             }
                   2653:         } elsif ($action eq 'uploaddoc') {
                   2654:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2655:             print $fh $env{'form.'.$source};
1.481     raeburn  2656:             close($fh);
1.637     raeburn  2657:             if ($parser eq 'parse') {
1.1024    raeburn  2658:                 my $mm = new File::MMagic;
1.1095    raeburn  2659:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2660:                 if ($type eq 'text/html') {
1.1024    raeburn  2661:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2662:                     unless ($parse_result eq 'ok') {
                   2663:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2664:                     }
1.637     raeburn  2665:                 }
1.1095    raeburn  2666:                 if (ref($mimetype)) {
                   2667:                     $$mimetype = $type;
                   2668:                 } 
1.637     raeburn  2669:             }
1.477     raeburn  2670:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2671:                                  $home);
1.481     raeburn  2672:             if ($fetchresult eq 'ok') {
                   2673:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2674:             } else {
                   2675:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2676:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2677:                 return '/adm/notfound.html';
                   2678:             }
1.477     raeburn  2679:         }
                   2680:     }
1.485     raeburn  2681:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2682:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2683:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2684:     }
                   2685:     return $fetchresult;
                   2686: }
                   2687: 
1.637     raeburn  2688: sub build_filepath {
                   2689:     my ($fpath) = @_;
                   2690:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2691:     unless ($fpath eq '') {
                   2692:         my @parts=split('/',$fpath);
                   2693:         foreach my $part (@parts) {
                   2694:             $filepath.= '/'.$part;
                   2695:             if ((-e $filepath)!=1) {
                   2696:                 mkdir($filepath,0777);
                   2697:             }
                   2698:         }
                   2699:     }
                   2700:     return $filepath;
                   2701: }
                   2702: 
                   2703: sub store_edited_file {
1.638     albertel 2704:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2705:     my $file = $primary_url;
                   2706:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2707:     my $fpath = '';
                   2708:     my $fname = $file;
                   2709:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2710:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2711:     my $filepath = &build_filepath($fpath);
                   2712:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2713:     print $fh $content;
                   2714:     close($fh);
1.638     albertel 2715:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2716:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2717: 			  $home);
1.637     raeburn  2718:     if ($$fetchresult eq 'ok') {
                   2719:         return '/uploaded/'.$fpath.'/'.$fname;
                   2720:     } else {
1.638     albertel 2721:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2722: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2723:         return '/adm/notfound.html';
                   2724:     }
                   2725: }
                   2726: 
1.531     albertel 2727: sub clean_filename {
1.831     albertel 2728:     my ($fname,$args)=@_;
1.315     www      2729: # Replace Windows backslashes by forward slashes
1.257     www      2730:     $fname=~s/\\/\//g;
1.831     albertel 2731:     if (!$args->{'keep_path'}) {
                   2732:         # Get rid of everything but the actual filename
                   2733: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2734:     }
1.315     www      2735: # Replace spaces by underscores
                   2736:     $fname=~s/\s+/\_/g;
                   2737: # Replace all other weird characters by nothing
1.831     albertel 2738:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2739: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2740: # numbers
                   2741:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2742:     return $fname;
                   2743: }
1.1051    raeburn  2744: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2745: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2746: # image with the same aspect ratio as the original, but with dimensions which do 
                   2747: # not exceed $resizewidth and $resizeheight.
                   2748:  
1.984     neumanie 2749: sub resizeImage {
1.1051    raeburn  2750:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2751:     my $ima = Image::Magick->new;
                   2752:     my $resized;
                   2753:     if (-e $img_path) {
                   2754:         $ima->Read($img_path);
                   2755:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2756:             my $width = $ima->Get('width');
                   2757:             my $height = $ima->Get('height');
                   2758:             if ($width > $resizewidth) {
                   2759: 	        my $factor = $width/$resizewidth;
                   2760:                 my $newheight = $height/$factor;
                   2761:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2762:                 $resized = 1;
                   2763:             }
                   2764:         }
                   2765:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2766:             my $width = $ima->Get('width');
                   2767:             my $height = $ima->Get('height');
                   2768:             if ($height > $resizeheight) {
                   2769:                 my $factor = $height/$resizeheight;
                   2770:                 my $newwidth = $width/$factor;
                   2771:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2772:                 $resized = 1;
                   2773:             }
                   2774:         }
                   2775:         if ($resized) {
                   2776:             $ima->Write($img_path);
                   2777:         }
                   2778:     }
                   2779:     return;
1.977     amueller 2780: }
                   2781: 
1.608     albertel 2782: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2783: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2784: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2785: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2786: #                                    canceloverwrite, or ''. 
                   2787: #                   if 'coursedoc': upload to the current course
                   2788: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2789: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2790: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2791: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2792: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2793: #        $allfiles - reference to hash for embedded objects
                   2794: #        $codebase - reference to hash for codebase of java objects
                   2795: #        $desuname - username for permanent storage of uploaded file
                   2796: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2797: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2798: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2799: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2800: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2801: #        $mimetype - reference to scalar to accommodate mime type determined
                   2802: #                    from File::MMagic if $parser = parse.
1.858     raeburn  2803: # 
1.686     albertel 2804: # output: url of file in userspace, or error: <message> 
                   2805: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2806: 
1.531     albertel 2807: sub userfileupload {
1.1090    raeburn  2808:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2809:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2810:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2811:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2812:     $fname=&clean_filename($fname);
1.1090    raeburn  2813:     # See if there is anything left
1.257     www      2814:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2815:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2816:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2817:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2818:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2819:         my $now = time;
1.1090    raeburn  2820:         my $filepath;
1.1095    raeburn  2821:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2822:              $filepath = 'tmp/helprequests/'.$now;
                   2823:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2824:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2825:                          '_'.$env{'user.domain'}.'/pending';
                   2826:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2827:             my ($docuname,$docudom);
                   2828:             if ($destudom) {
                   2829:                 $docudom = $destudom;
                   2830:             } else {
                   2831:                 $docudom = $env{'user.domain'};
                   2832:             }
                   2833:             if ($destuname) {
                   2834:                 $docuname = $destuname;
                   2835:             } else {
                   2836:                 $docuname = $env{'user.name'};
                   2837:             }
                   2838:             if (exists($env{'form.group'})) {
                   2839:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2840:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2841:             }
                   2842:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2843:             if ($context eq 'canceloverwrite') {
                   2844:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2845:                 if (-e  $tempfile) {
                   2846:                     my @info = stat($tempfile);
                   2847:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2848:                         unlink($tempfile);
                   2849:                     }
                   2850:                 }
                   2851:                 return;
1.523     raeburn  2852:             }
                   2853:         }
1.1090    raeburn  2854:         # Create the directory if not present
1.741     raeburn  2855:         my @parts=split(/\//,$filepath);
                   2856:         my $fullpath = $perlvar{'lonDaemons'};
                   2857:         for (my $i=0;$i<@parts;$i++) {
                   2858:             $fullpath .= '/'.$parts[$i];
                   2859:             if ((-e $fullpath)!=1) {
                   2860:                 mkdir($fullpath,0777);
                   2861:             }
                   2862:         }
                   2863:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2864:         print $fh $env{'form.'.$formname};
                   2865:         close($fh);
1.1090    raeburn  2866:         if ($context eq 'existingfile') {
                   2867:             my @info = stat($fullpath.'/'.$fname);
                   2868:             return ($fullpath.'/'.$fname,$info[9]);
                   2869:         } else {
                   2870:             return $fullpath.'/'.$fname;
                   2871:         }
1.523     raeburn  2872:     }
1.995     raeburn  2873:     if ($subdir eq 'scantron') {
                   2874:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2875:     } else {
1.995     raeburn  2876:         $fname="$subdir/$fname";
                   2877:     }
1.1090    raeburn  2878:     if ($context eq 'coursedoc') {
1.638     albertel 2879: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2880: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2881:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2882:             return &finishuserfileupload($docuname,$docudom,
                   2883: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2884: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2885:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2886:         } else {
1.620     albertel 2887:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2888:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2889: 				       $fname,$formname,$parser,
1.1095    raeburn  2890: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2891:         }
1.719     banghart 2892:     } elsif (defined($destuname)) {
                   2893:         my $docuname=$destuname;
                   2894:         my $docudom=$destudom;
1.860     raeburn  2895: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2896: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2897:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2898:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2899:     } else {
1.638     albertel 2900:         my $docuname=$env{'user.name'};
                   2901:         my $docudom=$env{'user.domain'};
1.714     raeburn  2902:         if (exists($env{'form.group'})) {
                   2903:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2904:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2905:         }
1.860     raeburn  2906: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2907: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2908:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2909:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2910:     }
1.271     www      2911: }
                   2912: 
                   2913: sub finishuserfileupload {
1.860     raeburn  2914:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2915:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2916:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2917:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2918:   
1.860     raeburn  2919:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2920:     $file=$fname;
                   2921:     if ($fname=~m|/|) {
                   2922:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2923: 	$path.=$fnamepath.'/';
                   2924:     }
1.259     www      2925:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2926:     my $count;
                   2927:     for ($count=4;$count<=$#parts;$count++) {
                   2928:         $filepath.="/$parts[$count]";
                   2929:         if ((-e $filepath)!=1) {
                   2930: 	    mkdir($filepath,0777);
                   2931:         }
                   2932:     }
1.984     neumanie 2933: 
1.258     www      2934: # Save the file
                   2935:     {
1.701     albertel 2936: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2937: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2938: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2939: 	    return '/adm/notfound.html';
                   2940: 	}
1.1090    raeburn  2941:         if ($context eq 'overwrite') {
1.1117    foxr     2942:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2943:             my $target = $filepath.'/'.$file;
                   2944:             if (-e $source) {
                   2945:                 my @info = stat($source);
                   2946:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2947:                     unless (&File::Copy::move($source,$target)) {
                   2948:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2949:                         return "Moving from $source failed";
                   2950:                     }
                   2951:                 } else {
                   2952:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2953:                 }
                   2954:             } else {
                   2955:                 return "Temporary file: $source missing";
                   2956:             }
                   2957:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2958: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2959: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2960: 	    return '/adm/notfound.html';
                   2961: 	}
1.570     albertel 2962: 	close(FH);
1.1051    raeburn  2963:         if ($resizewidth && $resizeheight) {
                   2964:             my $mm = new File::MMagic;
                   2965:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2966:             if ($mime_type =~ m{^image/}) {
                   2967: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2968:             }  
1.977     amueller 2969: 	}
1.258     www      2970:     }
1.637     raeburn  2971:     if ($parser eq 'parse') {
1.1024    raeburn  2972:         my $mm = new File::MMagic;
1.1095    raeburn  2973:         my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2974:         if ($type eq 'text/html') {
1.1024    raeburn  2975:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2976:                                                        $allfiles,$codebase);
                   2977:             unless ($parse_result eq 'ok') {
                   2978:                 &logthis('Failed to parse '.$filepath.$file.
                   2979: 	   	         ' for embedded media: '.$parse_result); 
                   2980:             }
1.637     raeburn  2981:         }
1.1095    raeburn  2982:         if (ref($mimetype)) {
                   2983:             $$mimetype = $type;
                   2984:         }
1.637     raeburn  2985:     }
1.860     raeburn  2986:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   2987:         my $input = $filepath.'/'.$file;
                   2988:         my $output = $filepath.'/'.'tn-'.$file;
                   2989:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   2990:         system("convert -sample $thumbsize $input $output");
                   2991:         if (-e $filepath.'/'.'tn-'.$file) {
                   2992:             $fetchthumb  = 1; 
                   2993:         }
                   2994:     }
1.858     raeburn  2995:  
1.259     www      2996: # Notify homeserver to grep it
                   2997: #
1.984     neumanie 2998:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 2999:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3000:     if ($fetchresult eq 'ok') {
1.860     raeburn  3001:         if ($fetchthumb) {
                   3002:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3003:             if ($thumbresult ne 'ok') {
                   3004:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3005:                          $docuhome.': '.$thumbresult);
                   3006:             }
                   3007:         }
1.259     www      3008: #
1.258     www      3009: # Return the URL to it
1.494     albertel 3010:         return '/uploaded/'.$path.$file;
1.263     www      3011:     } else {
1.494     albertel 3012:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3013: 		 ': '.$fetchresult);
1.263     www      3014:         return '/adm/notfound.html';
1.858     raeburn  3015:     }
1.493     albertel 3016: }
                   3017: 
1.637     raeburn  3018: sub extract_embedded_items {
1.961     raeburn  3019:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3020:     my @state = ();
                   3021:     my %javafiles = (
                   3022:                       codebase => '',
                   3023:                       code => '',
                   3024:                       archive => ''
                   3025:                     );
                   3026:     my %mediafiles = (
                   3027:                       src => '',
                   3028:                       movie => '',
                   3029:                      );
1.648     raeburn  3030:     my $p;
                   3031:     if ($content) {
                   3032:         $p = HTML::LCParser->new($content);
                   3033:     } else {
1.961     raeburn  3034:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3035:     }
1.641     albertel 3036:     while (my $t=$p->get_token()) {
1.640     albertel 3037: 	if ($t->[0] eq 'S') {
                   3038: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3039: 	    push(@state, $tagname);
1.648     raeburn  3040:             if (lc($tagname) eq 'allow') {
                   3041:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3042:             }
1.640     albertel 3043: 	    if (lc($tagname) eq 'img') {
                   3044: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3045: 	    }
1.886     albertel 3046: 	    if (lc($tagname) eq 'a') {
                   3047: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3048: 	    }
1.645     raeburn  3049:             if (lc($tagname) eq 'script') {
                   3050:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3051:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3052:                 } else {
                   3053:                     &add_filetype($allfiles,$attr->{'src'},'src');
                   3054:                 }
                   3055:             }
                   3056:             if (lc($tagname) eq 'link') {
                   3057:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3058:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3059:                 }
                   3060:             }
1.640     albertel 3061: 	    if (lc($tagname) eq 'object' ||
                   3062: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3063: 		foreach my $item (keys(%javafiles)) {
                   3064: 		    $javafiles{$item} = '';
                   3065: 		}
                   3066: 	    }
                   3067: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3068: 		my $name = lc($attr->{'name'});
                   3069: 		foreach my $item (keys(%javafiles)) {
                   3070: 		    if ($name eq $item) {
                   3071: 			$javafiles{$item} = $attr->{'value'};
                   3072: 			last;
                   3073: 		    }
                   3074: 		}
                   3075: 		foreach my $item (keys(%mediafiles)) {
                   3076: 		    if ($name eq $item) {
                   3077: 			&add_filetype($allfiles, $attr->{'value'}, 'value');
                   3078: 			last;
                   3079: 		    }
                   3080: 		}
                   3081: 	    }
                   3082: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3083: 		foreach my $item (keys(%javafiles)) {
                   3084: 		    if ($attr->{$item}) {
                   3085: 			$javafiles{$item} = $attr->{$item};
                   3086: 			last;
                   3087: 		    }
                   3088: 		}
                   3089: 		foreach my $item (keys(%mediafiles)) {
                   3090: 		    if ($attr->{$item}) {
                   3091: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3092: 			last;
                   3093: 		    }
                   3094: 		}
                   3095: 	    }
                   3096: 	} elsif ($t->[0] eq 'E') {
                   3097: 	    my ($tagname) = ($t->[1]);
                   3098: 	    if ($javafiles{'codebase'} ne '') {
                   3099: 		$javafiles{'codebase'} .= '/';
                   3100: 	    }  
                   3101: 	    if (lc($tagname) eq 'applet' ||
                   3102: 		lc($tagname) eq 'object' ||
                   3103: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3104: 		) {
                   3105: 		foreach my $item (keys(%javafiles)) {
                   3106: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3107: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3108: 			&add_filetype($allfiles,$file,$item);
                   3109: 		    }
                   3110: 		}
                   3111: 	    } 
                   3112: 	    pop @state;
                   3113: 	}
                   3114:     }
1.637     raeburn  3115:     return 'ok';
                   3116: }
                   3117: 
1.639     albertel 3118: sub add_filetype {
                   3119:     my ($allfiles,$file,$type)=@_;
                   3120:     if (exists($allfiles->{$file})) {
                   3121: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3122: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3123: 	}
                   3124:     } else {
                   3125: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3126:     }
                   3127: }
                   3128: 
1.493     albertel 3129: sub removeuploadedurl {
1.984     neumanie 3130:     my ($url)=@_;	
                   3131:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3132:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3133: }
                   3134: 
                   3135: sub removeuserfile {
                   3136:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3137:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3138:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3139:     if ($result eq 'ok') {	
1.798     raeburn  3140:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3141:             my $metafile = $fname.'.meta';
                   3142:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3143: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3144:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3145:             my $sqlresult = 
1.823     albertel 3146:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3147:                                         'portfolio_metadata',$group,
                   3148:                                         'delete');
1.798     raeburn  3149:         }
                   3150:     }
                   3151:     return $result;
1.257     www      3152: }
1.15      www      3153: 
1.530     albertel 3154: sub mkdiruserfile {
                   3155:     my ($docuname,$docudom,$dir)=@_;
                   3156:     my $home=&homeserver($docuname,$docudom);
                   3157:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3158: }
                   3159: 
1.531     albertel 3160: sub renameuserfile {
                   3161:     my ($docuname,$docudom,$old,$new)=@_;
                   3162:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3163:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3164:                         &escape("$old").':'.&escape("$new"),$home);
                   3165:     if ($result eq 'ok') {
                   3166:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3167:             my $oldmeta = $old.'.meta';
                   3168:             my $newmeta = $new.'.meta';
                   3169:             my $metaresult = 
                   3170:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3171: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3172:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3173:             my $sqlresult = 
1.823     albertel 3174:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3175:                                         'portfolio_metadata',$group,
                   3176:                                         'delete');
1.798     raeburn  3177:         }
                   3178:     }
                   3179:     return $result;
1.531     albertel 3180: }
                   3181: 
1.14      www      3182: # ------------------------------------------------------------------------- Log
                   3183: 
                   3184: sub log {
                   3185:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3186:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3187: }
                   3188: 
                   3189: # ------------------------------------------------------------------ Course Log
1.352     www      3190: #
                   3191: # This routine flushes several buffers of non-mission-critical nature
                   3192: #
1.157     www      3193: 
                   3194: sub flushcourselogs {
1.352     www      3195:     &logthis('Flushing log buffers');
                   3196: #
                   3197: # course logs
                   3198: # This is a log of all transactions in a course, which can be used
                   3199: # for data mining purposes
                   3200: #
                   3201: # It also collects the courseid database, which lists last transaction
                   3202: # times and course titles for all courseids
                   3203: #
                   3204:     my %courseidbuffer=();
1.921     raeburn  3205:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3206:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3207: 		          &escape($courselogs{$crsid}),
                   3208: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3209: 	    delete $courselogs{$crsid};
                   3210:         } else {
                   3211:             &logthis('Failed to flush log buffer for '.$crsid);
                   3212:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3213:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3214:                         " exceeded maximum size, deleting.</font>");
                   3215:                delete $courselogs{$crsid};
                   3216:             }
1.352     www      3217:         }
1.920     raeburn  3218:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3219:             'description' => $coursedescrbuf{$crsid},
                   3220:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3221:             'type'        => $coursetypebuf{$crsid},
                   3222:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3223:         };
1.191     harris41 3224:     }
1.352     www      3225: #
                   3226: # Write course id database (reverse lookup) to homeserver of courses 
                   3227: # Is used in pickcourse
                   3228: #
1.840     albertel 3229:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3230:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3231:                                     $courseidbuffer{$crs_home},
                   3232:                                     $crs_home,'timeonly');
1.352     www      3233:     }
                   3234: #
                   3235: # File accesses
                   3236: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3237: #
1.449     matthew  3238:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3239:         if ($entry =~ /___count$/) {
                   3240:             my ($dom,$name);
1.807     albertel 3241:             ($dom,$name,undef)=
1.811     albertel 3242: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3243:             if (! defined($dom) || $dom eq '' || 
                   3244:                 ! defined($name) || $name eq '') {
1.620     albertel 3245:                 my $cid = $env{'request.course.id'};
                   3246:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3247:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3248:             }
1.450     matthew  3249:             my $value = $accesshash{$entry};
                   3250:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3251:             my %temphash=($url => $value);
1.449     matthew  3252:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3253:             if ($result eq 'ok') {
                   3254:                 delete $accesshash{$entry};
                   3255:             } elsif ($result eq 'unknown_cmd') {
                   3256:                 # Target server has old code running on it.
1.450     matthew  3257:                 my %temphash=($entry => $value);
1.449     matthew  3258:                 if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3259:                     delete $accesshash{$entry};
                   3260:                 }
                   3261:             }
                   3262:         } else {
1.811     albertel 3263:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450     matthew  3264:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3265:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3266:                 delete $accesshash{$entry};
                   3267:             }
1.185     www      3268:         }
1.191     harris41 3269:     }
1.352     www      3270: #
                   3271: # Roles
                   3272: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3273: #
1.800     albertel 3274:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3275:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3276: 	    split(/\:/,$entry);
                   3277:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3278:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3279:                 $rudom,$runame) eq 'ok') {
                   3280: 	    delete $userrolehash{$entry};
                   3281:         }
                   3282:     }
1.662     raeburn  3283: #
                   3284: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3285: #
                   3286:     my %domrolebuffer = ();
1.1000    raeburn  3287:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3288:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3289:         if ($domrolebuffer{$rudom}) {
                   3290:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3291:                       '='.&escape($domainrolehash{$entry});
                   3292:         } else {
                   3293:             $domrolebuffer{$rudom}.=&escape($entry).
                   3294:                       '='.&escape($domainrolehash{$entry});
                   3295:         }
                   3296:         delete $domainrolehash{$entry};
                   3297:     }
                   3298:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3299: 	my %servers = &get_servers($dom,'library');
                   3300: 	foreach my $tryserver (keys(%servers)) {
                   3301: 	    unless (&reply('domroleput:'.$dom.':'.
                   3302: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3303: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3304: 	    }
1.662     raeburn  3305:         }
                   3306:     }
1.186     www      3307:     $dumpcount++;
1.157     www      3308: }
                   3309: 
                   3310: sub courselog {
                   3311:     my $what=shift;
1.158     www      3312:     $what=time.':'.$what;
1.620     albertel 3313:     unless ($env{'request.course.id'}) { return ''; }
                   3314:     $coursedombuf{$env{'request.course.id'}}=
                   3315:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3316:     $coursenumbuf{$env{'request.course.id'}}=
                   3317:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3318:     $coursehombuf{$env{'request.course.id'}}=
                   3319:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3320:     $coursedescrbuf{$env{'request.course.id'}}=
                   3321:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3322:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3323:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3324:     $courseownerbuf{$env{'request.course.id'}}=
                   3325:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3326:     $coursetypebuf{$env{'request.course.id'}}=
                   3327:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3328:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3329: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3330:     } else {
1.620     albertel 3331: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3332:     }
1.620     albertel 3333:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3334: 	&flushcourselogs();
                   3335:     }
1.158     www      3336: }
                   3337: 
                   3338: sub courseacclog {
                   3339:     my $fnsymb=shift;
1.620     albertel 3340:     unless ($env{'request.course.id'}) { return ''; }
                   3341:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3342:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3343:         $what.=':POST';
1.583     matthew  3344:         # FIXME: Probably ought to escape things....
1.800     albertel 3345: 	foreach my $key (keys(%env)) {
                   3346:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3347:                 my $formitem = $1;
                   3348:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3349:                     $what.=':'.$formitem.'='.$env{$key};
                   3350:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3351:                     $what.=':'.$formitem.'='.$env{$key};
                   3352:                 }
1.158     www      3353:             }
1.191     harris41 3354:         }
1.583     matthew  3355:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3356:         # FIXME: We should not be depending on a form parameter that someone
                   3357:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3358:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3359:             $what.= ':POST';
                   3360:             # FIXME: Probably ought to escape things....
                   3361:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3362:                                  'crsdiscuss') {
1.620     albertel 3363:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3364:             }
                   3365:         }
1.158     www      3366:     }
                   3367:     &courselog($what);
1.149     www      3368: }
                   3369: 
1.185     www      3370: sub countacc {
                   3371:     my $url=&declutter(shift);
1.458     matthew  3372:     return if (! defined($url) || $url eq '');
1.620     albertel 3373:     unless ($env{'request.course.id'}) { return ''; }
                   3374:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281     www      3375:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3376:     $accesshash{$key}++;
1.185     www      3377: }
1.349     www      3378: 
1.361     www      3379: sub linklog {
                   3380:     my ($from,$to)=@_;
                   3381:     $from=&declutter($from);
                   3382:     $to=&declutter($to);
                   3383:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3384:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3385: }
                   3386:   
1.349     www      3387: sub userrolelog {
                   3388:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661     raeburn  3389:     if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662     raeburn  3390:         ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661     raeburn  3391:         ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041    raeburn  3392:         ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350     www      3393:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3394:        $userrolehash
                   3395:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3396:                     =$tend.':'.$tstart;
1.662     raeburn  3397:     }
1.898     albertel 3398:     if (($env{'request.role'} =~ /dc\./) &&
                   3399: 	(($trole=~/^au/) || ($trole=~/^in/) ||
                   3400: 	 ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041    raeburn  3401: 	 ($trole=~/^cr/) || ($trole=~/^ta/) ||
                   3402:          ($trole=~/^co/))) {
1.898     albertel 3403:        $userrolehash
                   3404:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3405:                     =$tend.':'.$tstart;
                   3406:     }
1.662     raeburn  3407:     if (($trole=~/^dc/) || ($trole=~/^ad/) ||
                   3408:         ($trole=~/^li/) || ($trole=~/^li/) ||
                   3409:         ($trole=~/^au/) || ($trole=~/^dg/) ||
                   3410:         ($trole=~/^sc/)) {
                   3411:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3412:        $domainrolehash
                   3413:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3414:                     = $tend.':'.$tstart;
                   3415:     }
1.351     www      3416: }
                   3417: 
1.957     raeburn  3418: sub courserolelog {
                   3419:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3420:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3421:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3422:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3423:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3424:         ($trole eq 'co')) {
1.957     raeburn  3425:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3426:             my $cdom = $1;
                   3427:             my $cnum = $2;
                   3428:             my $sec = $3;
                   3429:             my $namespace = 'rolelog';
                   3430:             my %storehash = (
                   3431:                                role    => $trole,
                   3432:                                start   => $tstart,
                   3433:                                end     => $tend,
                   3434:                                selfenroll => $selfenroll,
                   3435:                                context    => $context,
                   3436:                             );
                   3437:             if ($trole eq 'gr') {
                   3438:                 $namespace = 'groupslog';
                   3439:                 $storehash{'group'} = $sec;
                   3440:             } else {
                   3441:                 $storehash{'section'} = $sec;
                   3442:             }
                   3443:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3444:             if (($trole ne 'st') || ($sec ne '')) {
                   3445:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3446:             }
1.957     raeburn  3447:         }
                   3448:     }
                   3449:     return;
                   3450: }
                   3451: 
1.351     www      3452: sub get_course_adv_roles {
1.948     raeburn  3453:     my ($cid,$codes) = @_;
1.620     albertel 3454:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3455:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3456:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3457:     my %nothide=();
1.800     albertel 3458:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3459:         if ($user !~ /:/) {
                   3460: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3461:         } else {
                   3462:             $nothide{$user}=1;
                   3463:         }
1.470     www      3464:     }
1.351     www      3465:     my %returnhash=();
                   3466:     my %dumphash=
                   3467:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3468:     my $now=time;
1.997     raeburn  3469:     my %privileged;
1.1000    raeburn  3470:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3471: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3472:         if (($tstart) && ($tstart<0)) { next; }
                   3473:         if (($tend) && ($tend<$now)) { next; }
                   3474:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3475:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3476: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3477:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3478:             my %dompersonnel =
1.998     raeburn  3479:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3480:             $privileged{$domain} = {};
                   3481:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3482:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3483:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3484:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3485:                         $privileged{$udom}{$uname} = 1;
                   3486:                     }
                   3487:                 }
                   3488:             }
                   3489:         }
                   3490:         if ((exists($privileged{$domain}{$username})) && 
                   3491:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3492: 	if ($role eq 'cr') { next; }
1.948     raeburn  3493:         if ($codes) {
                   3494:             if ($section) { $role .= ':'.$section; }
                   3495:             if ($returnhash{$role}) {
                   3496:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3497:             } else {
                   3498:                 $returnhash{$role}=$username.':'.$domain;
                   3499:             }
1.351     www      3500:         } else {
1.988     raeburn  3501:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3502:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3503:             if ($returnhash{$key}) {
                   3504: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3505:             } else {
                   3506:                 $returnhash{$key}=$username.':'.$domain;
                   3507:             }
1.351     www      3508:         }
1.948     raeburn  3509:     }
1.400     www      3510:     return %returnhash;
                   3511: }
                   3512: 
                   3513: sub get_my_roles {
1.937     raeburn  3514:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3515:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3516:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3517:     my (%dumphash,%nothide);
1.1086    raeburn  3518:     if ($context eq 'userroles') {
                   3519:         my $extra = &freeze_escape({'skipcheck' => 1});
                   3520:         %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858     raeburn  3521:     } else {
                   3522:         %dumphash=
1.400     www      3523:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3524:         if ($hidepriv) {
                   3525:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3526:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3527:                 if ($user !~ /:/) {
                   3528:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3529:                 } else {
                   3530:                     $nothide{$user} = 1;
                   3531:                 }
                   3532:             }
                   3533:         }
1.858     raeburn  3534:     }
1.400     www      3535:     my %returnhash=();
                   3536:     my $now=time;
1.999     raeburn  3537:     my %privileged;
1.800     albertel 3538:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3539:         my ($role,$tend,$tstart);
                   3540:         if ($context eq 'userroles') {
                   3541: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3542:         } else {
                   3543:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3544:         }
1.400     www      3545:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3546:         my $status = 'active';
1.939     raeburn  3547:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3548:             $status = 'previous';
                   3549:         } 
                   3550:         if (($tstart) && ($now<$tstart)) {
                   3551:             $status = 'future';
                   3552:         }
                   3553:         if (ref($types) eq 'ARRAY') {
                   3554:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3555:                 next;
                   3556:             } 
                   3557:         } else {
                   3558:             if ($status ne 'active') {
                   3559:                 next;
                   3560:             }
                   3561:         }
1.867     raeburn  3562:         my ($rolecode,$username,$domain,$section,$area);
                   3563:         if ($context eq 'userroles') {
                   3564:             ($area,$rolecode) = split(/_/,$entry);
                   3565:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3566:         } else {
                   3567:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3568:         }
1.832     raeburn  3569:         if (ref($roledoms) eq 'ARRAY') {
                   3570:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3571:                 next;
                   3572:             }
                   3573:         }
                   3574:         if (ref($roles) eq 'ARRAY') {
                   3575:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3576:                 if ($role =~ /^cr\//) {
                   3577:                     if (!grep(/^cr$/,@{$roles})) {
                   3578:                         next;
                   3579:                     }
1.1104    raeburn  3580:                 } elsif ($role =~ /^gr\//) {
                   3581:                     if (!grep(/^gr$/,@{$roles})) {
                   3582:                         next;
                   3583:                     }
1.922     raeburn  3584:                 } else {
                   3585:                     next;
                   3586:                 }
1.832     raeburn  3587:             }
1.867     raeburn  3588:         }
1.937     raeburn  3589:         if ($hidepriv) {
1.999     raeburn  3590:             if ($context eq 'userroles') {
                   3591:                 if ((&privileged($username,$domain)) &&
                   3592:                     (!$nothide{$username.':'.$domain})) {
                   3593:                     next;
                   3594:                 }
                   3595:             } else {
                   3596:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3597:                     my %dompersonnel =
                   3598:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3599:                     $privileged{$domain} = {};
                   3600:                     if (keys(%dompersonnel)) {
                   3601:                         foreach my $server (keys(%dompersonnel)) {
                   3602:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3603:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3604:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3605:                                     $privileged{$udom}{$uname} = $trole;
                   3606:                                 }
                   3607:                             }
                   3608:                         }
                   3609:                     }
                   3610:                 }
                   3611:                 if (exists($privileged{$domain}{$username})) {
                   3612:                     if (!$nothide{$username.':'.$domain}) {
                   3613:                         next;
                   3614:                     }
                   3615:                 }
1.937     raeburn  3616:             }
                   3617:         }
1.933     raeburn  3618:         if ($withsec) {
                   3619:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3620:                 $tstart.':'.$tend;
                   3621:         } else {
                   3622:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3623:         }
1.832     raeburn  3624:     }
1.373     www      3625:     return %returnhash;
1.399     www      3626: }
                   3627: 
                   3628: # ----------------------------------------------------- Frontpage Announcements
                   3629: #
                   3630: #
                   3631: 
                   3632: sub postannounce {
                   3633:     my ($server,$text)=@_;
1.844     albertel 3634:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3635:     unless ($text=~/\w/) { $text=''; }
                   3636:     return &reply('setannounce:'.&escape($text),$server);
                   3637: }
                   3638: 
                   3639: sub getannounce {
1.448     albertel 3640: 
                   3641:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3642: 	my $announcement='';
1.800     albertel 3643: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3644: 	close($fh);
1.399     www      3645: 	if ($announcement=~/\w/) { 
                   3646: 	    return 
                   3647:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3648:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3649: 	} else {
                   3650: 	    return '';
                   3651: 	}
                   3652:     } else {
                   3653: 	return '';
                   3654:     }
1.351     www      3655: }
1.353     www      3656: 
                   3657: # ---------------------------------------------------------- Course ID routines
                   3658: # Deal with domain's nohist_courseid.db files
                   3659: #
                   3660: 
                   3661: sub courseidput {
1.921     raeburn  3662:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3663:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3664:     my $outcome;
                   3665:     if ($caller eq 'timeonly') {
                   3666:         my $cids = '';
                   3667:         foreach my $item (keys(%$storehash)) {
                   3668:             $cids.=&escape($item).'&';
                   3669:         }
                   3670:         $cids=~s/\&$//;
                   3671:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3672:                           $coursehome);       
                   3673:     } else {
                   3674:         my $items = '';
                   3675:         foreach my $item (keys(%$storehash)) {
                   3676:             $items.= &escape($item).'='.
                   3677:                      &freeze_escape($$storehash{$item}).'&';
                   3678:         }
                   3679:         $items=~s/\&$//;
                   3680:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3681:                           $coursehome);
1.918     raeburn  3682:     }
                   3683:     if ($outcome eq 'unknown_cmd') {
                   3684:         my $what;
                   3685:         foreach my $cid (keys(%$storehash)) {
                   3686:             $what .= &escape($cid).'=';
1.921     raeburn  3687:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3688:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3689:             }
                   3690:             $what =~ s/\:$/&/;
                   3691:         }
                   3692:         $what =~ s/\&$//;  
                   3693:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3694:     } else {
                   3695:         return $outcome;
                   3696:     }
1.353     www      3697: }
                   3698: 
                   3699: sub courseiddump {
1.921     raeburn  3700:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3701:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3702:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3703:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3704:     my $as_hash = 1;
                   3705:     my %returnhash;
                   3706:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3707:     my %libserv = &all_library();
                   3708:     foreach my $tryserver (keys(%libserv)) {
                   3709:         if ( (  $hostidflag == 1 
                   3710: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3711: 	     || (!defined($hostidflag)) ) {
                   3712: 
1.918     raeburn  3713: 	    if (($domfilter eq '') ||
                   3714: 		(&host_domain($tryserver) eq $domfilter)) {
                   3715:                 my $rep = 
                   3716:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3717:                          $sincefilter.':'.&escape($descfilter).':'.
                   3718:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3719:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3720:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3721:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3722:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3723:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3724:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3725:                          &escape($creationcontext).':'.$domcloner,
                   3726:                          $tryserver);
1.918     raeburn  3727:                 my @pairs=split(/\&/,$rep);
                   3728:                 foreach my $item (@pairs) {
                   3729:                     my ($key,$value)=split(/\=/,$item,2);
                   3730:                     $key = &unescape($key);
                   3731:                     next if ($key =~ /^error: 2 /);
                   3732:                     my $result = &thaw_unescape($value);
                   3733:                     if (ref($result) eq 'HASH') {
                   3734:                         $returnhash{$key}=$result;
                   3735:                     } else {
1.921     raeburn  3736:                         my @responses = split(/:/,$value);
                   3737:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3738:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3739:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3740:                         }
1.1008    raeburn  3741:                     }
1.353     www      3742:                 }
                   3743:             }
                   3744:         }
                   3745:     }
                   3746:     return %returnhash;
                   3747: }
                   3748: 
1.1055    raeburn  3749: sub courselastaccess {
                   3750:     my ($cdom,$cnum,$hostidref) = @_;
                   3751:     my %returnhash;
                   3752:     if ($cdom && $cnum) {
                   3753:         my $chome = &homeserver($cnum,$cdom);
                   3754:         if ($chome ne 'no_host') {
                   3755:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3756:             &extract_lastaccess(\%returnhash,$rep);
                   3757:         }
                   3758:     } else {
                   3759:         if (!$cdom) { $cdom=''; }
                   3760:         my %libserv = &all_library();
                   3761:         foreach my $tryserver (keys(%libserv)) {
                   3762:             if (ref($hostidref) eq 'ARRAY') {
                   3763:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3764:             } 
                   3765:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3766:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3767:                 &extract_lastaccess(\%returnhash,$rep);
                   3768:             }
                   3769:         }
                   3770:     }
                   3771:     return %returnhash;
                   3772: }
                   3773: 
                   3774: sub extract_lastaccess {
                   3775:     my ($returnhash,$rep) = @_;
                   3776:     if (ref($returnhash) eq 'HASH') {
                   3777:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3778:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3779:                  $rep eq '') {
                   3780:             my @pairs=split(/\&/,$rep);
                   3781:             foreach my $item (@pairs) {
                   3782:                 my ($key,$value)=split(/\=/,$item,2);
                   3783:                 $key = &unescape($key);
                   3784:                 next if ($key =~ /^error: 2 /);
                   3785:                 $returnhash->{$key} = &thaw_unescape($value);
                   3786:             }
                   3787:         }
                   3788:     }
                   3789:     return;
                   3790: }
                   3791: 
1.658     raeburn  3792: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3793: 
                   3794: sub dcmailput {
1.685     raeburn  3795:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3796:     my $status = &Apache::lonnet::critical(
1.740     www      3797:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3798:        &escape($message),$server);
1.662     raeburn  3799:     return $status;
                   3800: }
                   3801: 
1.658     raeburn  3802: sub dcmaildump {
                   3803:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3804:     my %returnhash=();
1.846     albertel 3805: 
                   3806:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3807:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3808:                                                          &escape($enddate).':';
                   3809: 	my @esc_senders=map { &escape($_)} @$senders;
                   3810: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3811: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3812:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3813:             if (($key) && ($value)) {
                   3814:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3815:             }
                   3816:         }
                   3817:     }
                   3818:     return %returnhash;
                   3819: }
1.662     raeburn  3820: # ---------------------------------------------------------- Domain roles
                   3821: 
                   3822: sub get_domain_roles {
                   3823:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3824:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3825:         $startdate = '.';
                   3826:     }
1.1018    raeburn  3827:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3828:         $enddate = '.';
                   3829:     }
1.922     raeburn  3830:     my $rolelist;
                   3831:     if (ref($roles) eq 'ARRAY') {
                   3832:         $rolelist = join(':',@{$roles});
                   3833:     }
1.662     raeburn  3834:     my %personnel = ();
1.841     albertel 3835: 
                   3836:     my %servers = &get_servers($dom,'library');
                   3837:     foreach my $tryserver (keys(%servers)) {
                   3838: 	%{$personnel{$tryserver}}=();
                   3839: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3840: 					    &escape($startdate).':'.
                   3841: 					    &escape($enddate).':'.
                   3842: 					    &escape($rolelist), $tryserver))) {
                   3843: 	    my ($key,$value) = split(/\=/,$line,2);
                   3844: 	    if (($key) && ($value)) {
                   3845: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3846: 	    }
                   3847: 	}
1.662     raeburn  3848:     }
                   3849:     return %personnel;
                   3850: }
1.658     raeburn  3851: 
1.1057    www      3852: # ----------------------------------------------------------- Interval timing 
1.149     www      3853: 
1.504     albertel 3854: sub get_first_access {
                   3855:     my ($type,$argsymb)=@_;
1.790     albertel 3856:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3857:     if ($argsymb) { $symb=$argsymb; }
                   3858:     my ($map,$id,$res)=&decode_symb($symb);
1.926     albertel 3859:     if ($type eq 'course') {
                   3860: 	$res='course';
                   3861:     } elsif ($type eq 'map') {
1.588     albertel 3862: 	$res=&symbread($map);
                   3863:     } else {
                   3864: 	$res=$symb;
                   3865:     }
                   3866:     my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
                   3867:     return $times{"$courseid\0$res"};
1.504     albertel 3868: }
                   3869: 
                   3870: sub set_first_access {
                   3871:     my ($type)=@_;
1.790     albertel 3872:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3873:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3874:     if ($type eq 'course') {
                   3875: 	$res='course';
                   3876:     } elsif ($type eq 'map') {
1.588     albertel 3877: 	$res=&symbread($map);
                   3878:     } else {
                   3879: 	$res=$symb;
                   3880:     }
                   3881:     my $firstaccess=&get_first_access($type,$symb);
1.505     albertel 3882:     if (!$firstaccess) {
1.588     albertel 3883: 	return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505     albertel 3884:     }
                   3885:     return 'already_set';
1.504     albertel 3886: }
                   3887: 
1.110     www      3888: # --------------------------------------------- Set Expire Date for Spreadsheet
                   3889: 
                   3890: sub expirespread {
                   3891:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 3892:     my $cid=$env{'request.course.id'}; 
1.110     www      3893:     if ($cid) {
                   3894:        my $now=time;
                   3895:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 3896:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   3897:                             $env{'course.'.$cid.'.num'}.
1.110     www      3898: 	        	    ':nohist_expirationdates:'.
                   3899:                             &escape($key).'='.$now,
1.620     albertel 3900:                             $env{'course.'.$cid.'.home'})
1.110     www      3901:     }
                   3902:     return 'ok';
1.14      www      3903: }
                   3904: 
1.109     www      3905: # ----------------------------------------------------- Devalidate Spreadsheets
                   3906: 
                   3907: sub devalidate {
1.325     www      3908:     my ($symb,$uname,$udom)=@_;
1.620     albertel 3909:     my $cid=$env{'request.course.id'}; 
1.109     www      3910:     if ($cid) {
1.391     matthew  3911:         # delete the stored spreadsheets for
                   3912:         # - the student level sheet of this user in course's homespace
                   3913:         # - the assessment level sheet for this resource 
                   3914:         #   for this user in user's homespace
1.553     albertel 3915: 	# - current conditional state info
1.325     www      3916: 	my $key=$uname.':'.$udom.':';
1.109     www      3917:         my $status=
1.299     matthew  3918: 	    &del('nohist_calculatedsheets',
1.391     matthew  3919: 		 [$key.'studentcalc:'],
1.620     albertel 3920: 		 $env{'course.'.$cid.'.domain'},
                   3921: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 3922: 		.' '.
                   3923: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  3924: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      3925:         unless ($status eq 'ok ok') {
                   3926:            &logthis('Could not devalidate spreadsheet '.
1.325     www      3927:                     $uname.' at '.$udom.' for '.
1.109     www      3928: 		    $symb.': '.$status);
1.133     albertel 3929:         }
1.553     albertel 3930: 	&delenv('user.state.'.$cid);
1.109     www      3931:     }
                   3932: }
                   3933: 
1.265     albertel 3934: sub get_scalar {
                   3935:     my ($string,$end) = @_;
                   3936:     my $value;
                   3937:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   3938: 	$value = $1;
                   3939:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   3940: 	$value = $1;
                   3941:     }
                   3942:     return &unescape($value);
                   3943: }
                   3944: 
                   3945: sub array2str {
                   3946:   my (@array) = @_;
                   3947:   my $result=&arrayref2str(\@array);
                   3948:   $result=~s/^__ARRAY_REF__//;
                   3949:   $result=~s/__END_ARRAY_REF__$//;
                   3950:   return $result;
                   3951: }
                   3952: 
1.204     albertel 3953: sub arrayref2str {
                   3954:   my ($arrayref) = @_;
1.265     albertel 3955:   my $result='__ARRAY_REF__';
1.204     albertel 3956:   foreach my $elem (@$arrayref) {
1.265     albertel 3957:     if(ref($elem) eq 'ARRAY') {
                   3958:       $result.=&arrayref2str($elem).'&';
                   3959:     } elsif(ref($elem) eq 'HASH') {
                   3960:       $result.=&hashref2str($elem).'&';
                   3961:     } elsif(ref($elem)) {
                   3962:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 3963:     } else {
                   3964:       $result.=&escape($elem).'&';
                   3965:     }
                   3966:   }
                   3967:   $result=~s/\&$//;
1.265     albertel 3968:   $result .= '__END_ARRAY_REF__';
1.204     albertel 3969:   return $result;
                   3970: }
                   3971: 
1.168     albertel 3972: sub hash2str {
1.204     albertel 3973:   my (%hash) = @_;
                   3974:   my $result=&hashref2str(\%hash);
1.265     albertel 3975:   $result=~s/^__HASH_REF__//;
                   3976:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 3977:   return $result;
                   3978: }
                   3979: 
                   3980: sub hashref2str {
                   3981:   my ($hashref)=@_;
1.265     albertel 3982:   my $result='__HASH_REF__';
1.800     albertel 3983:   foreach my $key (sort(keys(%$hashref))) {
                   3984:     if (ref($key) eq 'ARRAY') {
                   3985:       $result.=&arrayref2str($key).'=';
                   3986:     } elsif (ref($key) eq 'HASH') {
                   3987:       $result.=&hashref2str($key).'=';
                   3988:     } elsif (ref($key)) {
1.265     albertel 3989:       $result.='=';
1.800     albertel 3990:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 3991:     } else {
1.1132    raeburn  3992: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 3993:     }
                   3994: 
1.800     albertel 3995:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   3996:       $result.=&arrayref2str($hashref->{$key}).'&';
                   3997:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   3998:       $result.=&hashref2str($hashref->{$key}).'&';
                   3999:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4000:        $result.='&';
1.800     albertel 4001:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4002:     } else {
1.800     albertel 4003:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4004:     }
                   4005:   }
1.168     albertel 4006:   $result=~s/\&$//;
1.265     albertel 4007:   $result .= '__END_HASH_REF__';
1.168     albertel 4008:   return $result;
                   4009: }
                   4010: 
                   4011: sub str2hash {
1.265     albertel 4012:     my ($string)=@_;
                   4013:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4014:     return %$hash;
                   4015: }
                   4016: 
                   4017: sub str2hashref {
1.168     albertel 4018:   my ($string) = @_;
1.265     albertel 4019: 
                   4020:   my %hash;
                   4021: 
                   4022:   if($string !~ /^__HASH_REF__/) {
                   4023:       if (! ($string eq '' || !defined($string))) {
                   4024: 	  $hash{'error'}='Not hash reference';
                   4025:       }
                   4026:       return (\%hash, $string);
                   4027:   }
                   4028: 
                   4029:   $string =~ s/^__HASH_REF__//;
                   4030: 
                   4031:   while($string !~ /^__END_HASH_REF__/) {
                   4032:       #key
                   4033:       my $key='';
                   4034:       if($string =~ /^__HASH_REF__/) {
                   4035:           ($key, $string)=&str2hashref($string);
                   4036:           if(defined($key->{'error'})) {
                   4037:               $hash{'error'}='Bad data';
                   4038:               return (\%hash, $string);
                   4039:           }
                   4040:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4041:           ($key, $string)=&str2arrayref($string);
                   4042:           if($key->[0] eq 'Array reference error') {
                   4043:               $hash{'error'}='Bad data';
                   4044:               return (\%hash, $string);
                   4045:           }
                   4046:       } else {
                   4047:           $string =~ s/^(.*?)=//;
1.267     albertel 4048: 	  $key=&unescape($1);
1.265     albertel 4049:       }
                   4050:       $string =~ s/^=//;
                   4051: 
                   4052:       #value
                   4053:       my $value='';
                   4054:       if($string =~ /^__HASH_REF__/) {
                   4055:           ($value, $string)=&str2hashref($string);
                   4056:           if(defined($value->{'error'})) {
                   4057:               $hash{'error'}='Bad data';
                   4058:               return (\%hash, $string);
                   4059:           }
                   4060:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4061:           ($value, $string)=&str2arrayref($string);
                   4062:           if($value->[0] eq 'Array reference error') {
                   4063:               $hash{'error'}='Bad data';
                   4064:               return (\%hash, $string);
                   4065:           }
                   4066:       } else {
                   4067: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4068:       }
                   4069:       $string =~ s/^&//;
                   4070: 
                   4071:       $hash{$key}=$value;
1.204     albertel 4072:   }
1.265     albertel 4073: 
                   4074:   $string =~ s/^__END_HASH_REF__//;
                   4075: 
                   4076:   return (\%hash, $string);
1.204     albertel 4077: }
                   4078: 
                   4079: sub str2array {
1.265     albertel 4080:     my ($string)=@_;
                   4081:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4082:     return @$array;
                   4083: }
                   4084: 
                   4085: sub str2arrayref {
1.204     albertel 4086:   my ($string) = @_;
1.265     albertel 4087:   my @array;
                   4088: 
                   4089:   if($string !~ /^__ARRAY_REF__/) {
                   4090:       if (! ($string eq '' || !defined($string))) {
                   4091: 	  $array[0]='Array reference error';
                   4092:       }
                   4093:       return (\@array, $string);
                   4094:   }
                   4095: 
                   4096:   $string =~ s/^__ARRAY_REF__//;
                   4097: 
                   4098:   while($string !~ /^__END_ARRAY_REF__/) {
                   4099:       my $value='';
                   4100:       if($string =~ /^__HASH_REF__/) {
                   4101:           ($value, $string)=&str2hashref($string);
                   4102:           if(defined($value->{'error'})) {
                   4103:               $array[0] ='Array reference error';
                   4104:               return (\@array, $string);
                   4105:           }
                   4106:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4107:           ($value, $string)=&str2arrayref($string);
                   4108:           if($value->[0] eq 'Array reference error') {
                   4109:               $array[0] ='Array reference error';
                   4110:               return (\@array, $string);
                   4111:           }
                   4112:       } else {
                   4113: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4114:       }
                   4115:       $string =~ s/^&//;
                   4116: 
                   4117:       push(@array, $value);
1.191     harris41 4118:   }
1.265     albertel 4119: 
                   4120:   $string =~ s/^__END_ARRAY_REF__//;
                   4121: 
                   4122:   return (\@array, $string);
1.168     albertel 4123: }
                   4124: 
1.167     albertel 4125: # -------------------------------------------------------------------Temp Store
                   4126: 
1.168     albertel 4127: sub tmpreset {
                   4128:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4129:   if (!$symb) {
                   4130:     $symb=&symbread();
1.620     albertel 4131:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4132:   }
                   4133:   $symb=escape($symb);
                   4134: 
1.620     albertel 4135:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4136:   $namespace=~s/\//\_/g;
                   4137:   $namespace=~s/\W//g;
                   4138: 
1.620     albertel 4139:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4140:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4141:   if ($domain eq 'public' && $stuname eq 'public') {
                   4142:       $stuname=$ENV{'REMOTE_ADDR'};
                   4143:   }
1.1117    foxr     4144:   my $path=LONCAPA::tempdir();
1.168     albertel 4145:   my %hash;
                   4146:   if (tie(%hash,'GDBM_File',
                   4147: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4148: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4149:     foreach my $key (keys(%hash)) {
1.180     albertel 4150:       if ($key=~ /:$symb/) {
1.168     albertel 4151: 	delete($hash{$key});
                   4152:       }
                   4153:     }
                   4154:   }
                   4155: }
                   4156: 
1.167     albertel 4157: sub tmpstore {
1.168     albertel 4158:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4159: 
                   4160:   if (!$symb) {
                   4161:     $symb=&symbread();
1.620     albertel 4162:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4163:   }
                   4164:   $symb=escape($symb);
                   4165: 
                   4166:   if (!$namespace) {
                   4167:     # I don't think we would ever want to store this for a course.
                   4168:     # it seems this will only be used if we don't have a course.
1.620     albertel 4169:     #$namespace=$env{'request.course.id'};
1.168     albertel 4170:     #if (!$namespace) {
1.620     albertel 4171:       $namespace=$env{'request.state'};
1.168     albertel 4172:     #}
                   4173:   }
                   4174:   $namespace=~s/\//\_/g;
                   4175:   $namespace=~s/\W//g;
1.620     albertel 4176:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4177:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4178:   if ($domain eq 'public' && $stuname eq 'public') {
                   4179:       $stuname=$ENV{'REMOTE_ADDR'};
                   4180:   }
1.168     albertel 4181:   my $now=time;
                   4182:   my %hash;
1.1117    foxr     4183:   my $path=LONCAPA::tempdir();
1.168     albertel 4184:   if (tie(%hash,'GDBM_File',
                   4185: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4186: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4187:     $hash{"version:$symb"}++;
                   4188:     my $version=$hash{"version:$symb"};
                   4189:     my $allkeys=''; 
                   4190:     foreach my $key (keys(%$storehash)) {
                   4191:       $allkeys.=$key.':';
1.591     albertel 4192:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4193:     }
                   4194:     $hash{"$version:$symb:timestamp"}=$now;
                   4195:     $allkeys.='timestamp';
                   4196:     $hash{"$version:keys:$symb"}=$allkeys;
                   4197:     if (untie(%hash)) {
                   4198:       return 'ok';
                   4199:     } else {
                   4200:       return "error:$!";
                   4201:     }
                   4202:   } else {
                   4203:     return "error:$!";
                   4204:   }
                   4205: }
1.167     albertel 4206: 
1.168     albertel 4207: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4208: 
1.168     albertel 4209: sub tmprestore {
                   4210:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4211: 
1.168     albertel 4212:   if (!$symb) {
                   4213:     $symb=&symbread();
1.620     albertel 4214:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4215:   }
                   4216:   $symb=escape($symb);
                   4217: 
1.620     albertel 4218:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4219: 
1.620     albertel 4220:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4221:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4222:   if ($domain eq 'public' && $stuname eq 'public') {
                   4223:       $stuname=$ENV{'REMOTE_ADDR'};
                   4224:   }
1.168     albertel 4225:   my %returnhash;
                   4226:   $namespace=~s/\//\_/g;
                   4227:   $namespace=~s/\W//g;
                   4228:   my %hash;
1.1117    foxr     4229:   my $path=LONCAPA::tempdir();
1.168     albertel 4230:   if (tie(%hash,'GDBM_File',
                   4231: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4232: 	  &GDBM_READER(),0640)) {
1.168     albertel 4233:     my $version=$hash{"version:$symb"};
                   4234:     $returnhash{'version'}=$version;
                   4235:     my $scope;
                   4236:     for ($scope=1;$scope<=$version;$scope++) {
                   4237:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4238:       my @keys=split(/:/,$vkeys);
                   4239:       my $key;
                   4240:       $returnhash{"$scope:keys"}=$vkeys;
                   4241:       foreach $key (@keys) {
1.591     albertel 4242: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4243: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4244:       }
                   4245:     }
1.168     albertel 4246:     if (!(untie(%hash))) {
                   4247:       return "error:$!";
                   4248:     }
                   4249:   } else {
                   4250:     return "error:$!";
                   4251:   }
                   4252:   return %returnhash;
1.167     albertel 4253: }
                   4254: 
1.9       www      4255: # ----------------------------------------------------------------------- Store
                   4256: 
                   4257: sub store {
1.124     www      4258:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4259:     my $home='';
                   4260: 
1.168     albertel 4261:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4262: 
1.213     www      4263:     $symb=&symbclean($symb);
1.122     albertel 4264:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4265: 
1.620     albertel 4266:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4267:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4268: 
                   4269:     &devalidate($symb,$stuname,$domain);
1.109     www      4270: 
                   4271:     $symb=escape($symb);
1.187     www      4272:     if (!$namespace) { 
1.620     albertel 4273:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4274:           return ''; 
                   4275:        } 
                   4276:     }
1.620     albertel 4277:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4278: 
                   4279:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4280:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4281: 
1.12      www      4282:     my $namevalue='';
1.800     albertel 4283:     foreach my $key (keys(%$storehash)) {
                   4284:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4285:     }
1.12      www      4286:     $namevalue=~s/\&$//;
1.187     www      4287:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4288:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4289: }
                   4290: 
1.47      www      4291: # -------------------------------------------------------------- Critical Store
                   4292: 
                   4293: sub cstore {
1.124     www      4294:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4295:     my $home='';
                   4296: 
1.168     albertel 4297:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4298: 
1.213     www      4299:     $symb=&symbclean($symb);
1.122     albertel 4300:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4301: 
1.620     albertel 4302:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4303:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4304: 
                   4305:     &devalidate($symb,$stuname,$domain);
1.109     www      4306: 
                   4307:     $symb=escape($symb);
1.187     www      4308:     if (!$namespace) { 
1.620     albertel 4309:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4310:           return ''; 
                   4311:        } 
                   4312:     }
1.620     albertel 4313:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4314: 
                   4315:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4316:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4317: 
1.47      www      4318:     my $namevalue='';
1.800     albertel 4319:     foreach my $key (keys(%$storehash)) {
                   4320:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4321:     }
1.47      www      4322:     $namevalue=~s/\&$//;
1.187     www      4323:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4324:     return critical
                   4325:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4326: }
                   4327: 
1.9       www      4328: # --------------------------------------------------------------------- Restore
                   4329: 
                   4330: sub restore {
1.124     www      4331:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4332:     my $home='';
                   4333: 
1.168     albertel 4334:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4335: 
1.122     albertel 4336:     if (!$symb) {
                   4337:       unless ($symb=escape(&symbread())) { return ''; }
                   4338:     } else {
1.213     www      4339:       $symb=&escape(&symbclean($symb));
1.122     albertel 4340:     }
1.188     www      4341:     if (!$namespace) { 
1.620     albertel 4342:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4343:           return ''; 
                   4344:        } 
                   4345:     }
1.620     albertel 4346:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4347:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4348:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4349:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4350: 
1.12      www      4351:     my %returnhash=();
1.800     albertel 4352:     foreach my $line (split(/\&/,$answer)) {
                   4353: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4354:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4355:     }
1.75      www      4356:     my $version;
                   4357:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4358:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4359:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4360:        }
1.75      www      4361:     }
1.13      www      4362:     return %returnhash;
1.34      www      4363: }
                   4364: 
                   4365: # ---------------------------------------------------------- Course Description
1.1118    foxr     4366: #
                   4367: #  
1.34      www      4368: 
                   4369: sub coursedescription {
1.731     albertel 4370:     my ($courseid,$args)=@_;
1.34      www      4371:     $courseid=~s/^\///;
1.49      www      4372:     $courseid=~s/\_/\//g;
1.34      www      4373:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4374:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4375:     my $normalid=$cdomain.'_'.$cnum;
                   4376:     # need to always cache even if we get errors otherwise we keep 
                   4377:     # trying and trying and trying to get the course description.
                   4378:     my %envhash=();
                   4379:     my %returnhash=();
1.731     albertel 4380:     
                   4381:     my $expiretime=600;
                   4382:     if ($env{'request.course.id'} eq $normalid) {
                   4383: 	$expiretime=120;
                   4384:     }
                   4385: 
                   4386:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4387:     if (!$args->{'freshen_cache'}
                   4388: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4389: 	foreach my $key (keys(%env)) {
                   4390: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4391: 	    my ($setting) = $1;
                   4392: 	    $returnhash{$setting} = $env{$key};
                   4393: 	}
                   4394: 	return %returnhash;
                   4395:     }
                   4396: 
1.1118    foxr     4397:     # get the data again
                   4398: 
1.731     albertel 4399:     if (!$args->{'one_time'}) {
                   4400: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4401:     }
1.811     albertel 4402: 
1.34      www      4403:     if ($chome ne 'no_host') {
1.302     albertel 4404:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4405:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4406: 	   my $username = $env{'user.name'}; # Defult username
                   4407: 	   if(defined $args->{'user'}) {
                   4408: 	       $username = $args->{'user'};
                   4409: 	   }
1.129     albertel 4410:            $returnhash{'home'}= $chome;
                   4411: 	   $returnhash{'domain'} = $cdomain;
                   4412: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4413:            if (!defined($returnhash{'type'})) {
                   4414:                $returnhash{'type'} = 'Course';
                   4415:            }
1.130     albertel 4416:            while (my ($name,$value) = each %returnhash) {
1.53      www      4417:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4418:            }
1.270     www      4419:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4420:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4421: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4422:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4423:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4424:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4425:        }
                   4426:     }
1.731     albertel 4427:     if (!$args->{'one_time'}) {
1.949     raeburn  4428: 	&appenv(\%envhash);
1.731     albertel 4429:     }
1.302     albertel 4430:     return %returnhash;
1.461     www      4431: }
                   4432: 
1.1080    raeburn  4433: sub update_released_required {
                   4434:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4435:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4436:         $cid = $env{'request.course.id'};
                   4437:         $cdom = $env{'course.'.$cid.'.domain'};
                   4438:         $cnum = $env{'course.'.$cid.'.num'};
                   4439:         $chome = $env{'course.'.$cid.'.home'};
                   4440:     }
                   4441:     if ($needsrelease) {
                   4442:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4443:         my $needsupdate;
                   4444:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4445:             $needsupdate = 1;
                   4446:         } else {
                   4447:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4448:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4449:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4450:                 $needsupdate = 1;
                   4451:             }
                   4452:         }
                   4453:         if ($needsupdate) {
                   4454:             my %needshash = (
                   4455:                              'internal.releaserequired' => $needsrelease,
                   4456:                             );
                   4457:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4458:             if ($putresult eq 'ok') {
                   4459:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4460:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4461:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4462:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4463:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4464:                 }
                   4465:             }
                   4466:         }
                   4467:     }
                   4468:     return;
                   4469: }
                   4470: 
1.461     www      4471: # -------------------------------------------------See if a user is privileged
                   4472: 
                   4473: sub privileged {
                   4474:     my ($username,$domain)=@_;
                   4475:     my $rolesdump=&reply("dump:$domain:$username:roles",
                   4476: 			&homeserver($username,$domain));
1.1033    raeburn  4477:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
                   4478:         ($rolesdump =~ /^error:/)) {
                   4479:         return 0;
                   4480:     }
1.461     www      4481:     my $now=time;
                   4482:     if ($rolesdump ne '') {
1.800     albertel 4483:         foreach my $entry (split(/&/,$rolesdump)) {
                   4484: 	    if ($entry!~/^rolesdef_/) {
                   4485: 		my ($area,$role)=split(/=/,$entry);
1.461     www      4486: 		$area=~s/\_\w\w$//;
                   4487: 		my ($trole,$tend,$tstart)=split(/_/,$role);
                   4488: 		if (($trole eq 'dc') || ($trole eq 'su')) {
                   4489: 		    my $active=1;
                   4490: 		    if ($tend) {
                   4491: 			if ($tend<$now) { $active=0; }
                   4492: 		    }
                   4493: 		    if ($tstart) {
                   4494: 			if ($tstart>$now) { $active=0; }
                   4495: 		    }
                   4496: 		    if ($active) { return 1; }
                   4497: 		}
                   4498: 	    }
                   4499: 	}
                   4500:     }
                   4501:     return 0;
1.9       www      4502: }
1.1       albertel 4503: 
1.103     harris41 4504: # -------------------------------------------------------- Get user privileges
1.11      www      4505: 
                   4506: sub rolesinit {
                   4507:     my ($domain,$username,$authhost)=@_;
1.1034    raeburn  4508:     my $now=time;
                   4509:     my %userroles = ('user.login.time' => $now);
1.1086    raeburn  4510:     my $extra = &freeze_escape({'skipcheck' => 1});
1.1078    raeburn  4511:     my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033    raeburn  4512:     if (($rolesdump eq 'con_lost') || ($rolesdump eq '') || 
1.1078    raeburn  4513:         ($rolesdump =~ /^error:/)) {
1.1033    raeburn  4514:         return \%userroles;
                   4515:     }
1.11      www      4516:     my %allroles=();
1.678     raeburn  4517:     my %allgroups=();   
1.11      www      4518: 
                   4519:     if ($rolesdump ne '') {
1.800     albertel 4520:         foreach my $entry (split(/&/,$rolesdump)) {
                   4521: 	  if ($entry!~/^rolesdef_/) {
                   4522:             my ($area,$role)=split(/=/,$entry);
1.587     albertel 4523: 	    $area=~s/\_\w\w$//;
1.678     raeburn  4524:             my ($trole,$tend,$tstart,$group_privs);
1.587     albertel 4525: 	    if ($role=~/^cr/) { 
1.807     albertel 4526: 		if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4527: 		    ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655     albertel 4528: 		    ($tend,$tstart)=split('_',$trest);
                   4529: 		} else {
                   4530: 		    $trole=$role;
                   4531: 		}
1.678     raeburn  4532:             } elsif ($role =~ m|^gr/|) {
                   4533:                 ($trole,$tend,$tstart) = split(/_/,$role);
1.1104    raeburn  4534:                 next if ($tstart eq '-1');
1.678     raeburn  4535:                 ($trole,$group_privs) = split(/\//,$trole);
                   4536:                 $group_privs = &unescape($group_privs);
1.587     albertel 4537: 	    } else {
                   4538: 		($trole,$tend,$tstart)=split(/_/,$role);
                   4539: 	    }
1.743     albertel 4540: 	    my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4541: 					 $username);
                   4542: 	    @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567     raeburn  4543:             if (($tend!=0) && ($tend<$now)) { $trole=''; }
                   4544:             if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11      www      4545:             if (($area ne '') && ($trole ne '')) {
1.347     albertel 4546: 		my $spec=$trole.'.'.$area;
                   4547: 		my ($tdummy,$tdomain,$trest)=split(/\//,$area);
                   4548: 		if ($trole =~ /^cr\//) {
1.567     raeburn  4549:                     &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678     raeburn  4550:                 } elsif ($trole eq 'gr') {
                   4551:                     &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347     albertel 4552: 		} else {
1.567     raeburn  4553:                     &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347     albertel 4554: 		}
1.12      www      4555:             }
1.662     raeburn  4556:           }
1.191     harris41 4557:         }
1.743     albertel 4558:         my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
                   4559:         $userroles{'user.adv'}    = $adv;
                   4560: 	$userroles{'user.author'} = $author;
1.620     albertel 4561:         $env{'user.adv'}=$adv;
1.11      www      4562:     }
1.743     albertel 4563:     return \%userroles;  
1.11      www      4564: }
                   4565: 
1.567     raeburn  4566: sub set_arearole {
                   4567:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4568: # log the associated role with the area
                   4569:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4570:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4571: }
                   4572: 
                   4573: sub custom_roleprivs {
                   4574:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4575:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4576:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4577:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4578:         my ($rdummy,$roledef)=
                   4579:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4580:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4581:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4582:             if (defined($syspriv)) {
1.1043    raeburn  4583:                 if ($trest =~ /^$match_community$/) {
                   4584:                     $syspriv =~ s/bre\&S//; 
                   4585:                 }
1.567     raeburn  4586:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4587:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4588:             }
                   4589:             if ($tdomain ne '') {
                   4590:                 if (defined($dompriv)) {
                   4591:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4592:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4593:                 }
                   4594:                 if (($trest ne '') && (defined($coursepriv))) {
                   4595:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4596:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4597:                 }
                   4598:             }
                   4599:         }
                   4600:     }
                   4601: }
                   4602: 
1.678     raeburn  4603: sub group_roleprivs {
                   4604:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4605:     my $access = 1;
                   4606:     my $now = time;
                   4607:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4608:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4609:     if ($access) {
1.811     albertel 4610:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4611:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4612:     }
                   4613: }
1.567     raeburn  4614: 
                   4615: sub standard_roleprivs {
                   4616:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4617:     if (defined($pr{$trole.':s'})) {
                   4618:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4619:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4620:     }
                   4621:     if ($tdomain ne '') {
                   4622:         if (defined($pr{$trole.':d'})) {
                   4623:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4624:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4625:         }
                   4626:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4627:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4628:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4629:         }
                   4630:     }
                   4631: }
                   4632: 
                   4633: sub set_userprivs {
1.1064    raeburn  4634:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4635:     my $author=0;
                   4636:     my $adv=0;
1.678     raeburn  4637:     my %grouproles = ();
                   4638:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4639:         my @groupkeys; 
1.1000    raeburn  4640:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4641:             push(@groupkeys,$role);
                   4642:         }
                   4643:         if (ref($groups_roles) eq 'HASH') {
                   4644:             foreach my $key (keys(%{$groups_roles})) {
                   4645:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4646:                     push(@groupkeys,$key);
                   4647:                 }
                   4648:             }
                   4649:         }
                   4650:         if (@groupkeys > 0) {
                   4651:             foreach my $role (@groupkeys) {
                   4652:                 my ($trole,$area,$sec,$extendedarea);
                   4653:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4654:                     $trole = $1;
                   4655:                     $area = $2;
                   4656:                     $sec = $3;
                   4657:                     $extendedarea = $area.$sec;
                   4658:                     if (exists($$allgroups{$area})) {
                   4659:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4660:                             my $spec = $trole.'.'.$extendedarea;
                   4661:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4662:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4663:                         }
1.678     raeburn  4664:                     }
                   4665:                 }
                   4666:             }
                   4667:         }
                   4668:     }
1.800     albertel 4669:     foreach my $group (keys(%grouproles)) {
                   4670:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4671:     }
1.800     albertel 4672:     foreach my $role (keys(%{$allroles})) {
                   4673:         my %thesepriv;
1.941     raeburn  4674:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4675:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4676:             if ($item ne '') {
                   4677:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4678:                 if ($restrictions eq '') {
                   4679:                     $thesepriv{$privilege}='F';
                   4680:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4681:                     $thesepriv{$privilege}.=$restrictions;
                   4682:                 }
                   4683:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4684:             }
                   4685:         }
                   4686:         my $thesestr='';
1.1104    raeburn  4687:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4688: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4689: 	}
                   4690:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4691:     }
                   4692:     return ($author,$adv);
                   4693: }
                   4694: 
1.994     raeburn  4695: sub role_status {
1.1104    raeburn  4696:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4697:     my @pwhere = ();
                   4698:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4699:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4700:         unless (!defined($$role) || $$role eq '') {
                   4701:             $$where=join('.',@pwhere);
                   4702:             $$trolecode=$$role.'.'.$$where;
                   4703:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4704:             $$tstatus='is';
1.1104    raeburn  4705:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4706:                 $$tstatus='future';
1.1034    raeburn  4707:                 if ($$tstart<$now) {
                   4708:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4709:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4710:                             my (%allroles,%allgroups,$group_privs,
                   4711:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4712:                             my %userroles = (
                   4713:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4714:                             );
1.1064    raeburn  4715:                             @rolecodes = ('cm'); 
1.1002    raeburn  4716:                             my $spec=$$role.'.'.$$where;
                   4717:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4718:                             if ($$role =~ /^cr\//) {
                   4719:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4720:                                 push(@rolecodes,'cr');
1.1002    raeburn  4721:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4722:                                 push(@rolecodes,$$role);
1.1002    raeburn  4723:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4724:                                                     $env{'user.name'});
1.1064    raeburn  4725:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4726:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4727:                                 $group_privs = &unescape($group_privs);
                   4728:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4729:                                 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  4730:                                 &get_groups_roles($tdomain,$trest,
                   4731:                                                   \%course_roles,\@rolecodes,
                   4732:                                                   \%groups_roles);
1.1002    raeburn  4733:                             } else {
1.1064    raeburn  4734:                                 push(@rolecodes,$$role);
1.1002    raeburn  4735:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4736:                             }
1.1064    raeburn  4737:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4738:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4739:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4740:                         }
                   4741:                     }
1.1034    raeburn  4742:                     $$tstatus = 'is';
1.1002    raeburn  4743:                 }
1.994     raeburn  4744:             }
                   4745:             if ($$tend) {
1.1104    raeburn  4746:                 if ($$tend<$update) {
1.994     raeburn  4747:                     $$tstatus='expired';
                   4748:                 } elsif ($$tend<$now) {
                   4749:                     $$tstatus='will_not';
                   4750:                 }
                   4751:             }
                   4752:         }
                   4753:     }
                   4754: }
                   4755: 
1.1104    raeburn  4756: sub get_groups_roles {
                   4757:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4758:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4759:                   (ref($rolecodes) eq 'ARRAY') && 
                   4760:                   (ref($groups_roles) eq 'HASH')); 
                   4761:     if (keys(%{$cdom_courseroles}) > 0) {
                   4762:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4763:         if ($cdom ne '' && $cnum ne '') {
                   4764:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4765:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4766:                     my $crsrole = $1;
                   4767:                     my $crssec = $2;
                   4768:                     if ($crsrole =~ /^cr/) {
                   4769:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4770:                             push(@{$rolecodes},'cr');
                   4771:                         }
                   4772:                     } else {
                   4773:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4774:                             push(@{$rolecodes},$crsrole);
                   4775:                         }
                   4776:                     }
                   4777:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4778:                     if ($crssec ne '') {
                   4779:                         $rolekey .= "/$crssec";
                   4780:                     }
                   4781:                     $rolekey .= './';
                   4782:                     $groups_roles->{$rolekey} = $rolecodes;
                   4783:                 }
                   4784:             }
                   4785:         }
                   4786:     }
                   4787:     return;
                   4788: }
                   4789: 
                   4790: sub delete_env_groupprivs {
                   4791:     my ($where,$courseroles,$possroles) = @_;
                   4792:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4793:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4794:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4795:         %{$courseroles->{$udom}} =
                   4796:             &get_my_roles('','','userroles',['active'],
                   4797:                           $possroles,[$udom],1);
                   4798:     }
                   4799:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4800:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4801:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4802:             my $area = '/'.$cdom.'/'.$cnum;
                   4803:             my $privkey = "user.priv.$crsrole.$area";
                   4804:             if ($crssec ne '') {
                   4805:                 $privkey .= '/'.$crssec;
                   4806:             }
                   4807:             $privkey .= ".$area/$group";
                   4808:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4809:         }
                   4810:     }
                   4811:     return;
                   4812: }
                   4813: 
1.994     raeburn  4814: sub check_adhoc_privs {
1.1104    raeburn  4815:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4816:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4817:     if ($env{$cckey}) {
                   4818:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4819:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4820:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4821:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4822:         }
                   4823:     } else {
1.1088    raeburn  4824:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4825:     }
                   4826: }
                   4827: 
                   4828: sub set_adhoc_privileges {
                   4829: # role can be cc or ca
1.1088    raeburn  4830:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  4831:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   4832:     my $spec = $role.'.'.$area;
                   4833:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   4834:                                   $env{'user.name'});
                   4835:     my %ccrole = ();
                   4836:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   4837:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   4838:     &appenv(\%userroles,[$role,'cm']);
                   4839:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  4840:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   4841:         &appenv( {'request.role'        => $spec,
                   4842:                   'request.role.domain' => $dcdom,
                   4843:                   'request.course.sec'  => ''
                   4844:                  }
                   4845:                );
                   4846:         my $tadv=0;
                   4847:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   4848:         &appenv({'request.role.adv'    => $tadv});
                   4849:     }
1.994     raeburn  4850: }
                   4851: 
1.12      www      4852: # --------------------------------------------------------------- get interface
                   4853: 
                   4854: sub get {
1.131     albertel 4855:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      4856:    my $items='';
1.800     albertel 4857:    foreach my $item (@$storearr) {
                   4858:        $items.=&escape($item).'&';
1.191     harris41 4859:    }
1.12      www      4860:    $items=~s/\&$//;
1.620     albertel 4861:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4862:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 4863:    my $uhome=&homeserver($uname,$udomain);
                   4864: 
1.133     albertel 4865:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4866:    my @pairs=split(/\&/,$rep);
1.273     albertel 4867:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   4868:      return @pairs;
                   4869:    }
1.15      www      4870:    my %returnhash=();
1.42      www      4871:    my $i=0;
1.800     albertel 4872:    foreach my $item (@$storearr) {
                   4873:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      4874:       $i++;
1.191     harris41 4875:    }
1.15      www      4876:    return %returnhash;
1.27      www      4877: }
                   4878: 
                   4879: # --------------------------------------------------------------- del interface
                   4880: 
                   4881: sub del {
1.133     albertel 4882:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      4883:    my $items='';
1.800     albertel 4884:    foreach my $item (@$storearr) {
                   4885:        $items.=&escape($item).'&';
1.191     harris41 4886:    }
1.984     neumanie 4887: 
1.27      www      4888:    $items=~s/\&$//;
1.620     albertel 4889:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4890:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 4891:    my $uhome=&homeserver($uname,$udomain);
                   4892:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      4893: }
                   4894: 
                   4895: # -------------------------------------------------------------- dump interface
                   4896: 
                   4897: sub dump {
1.1086    raeburn  4898:     my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755     albertel 4899:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4900:     if (!$uname) { $uname=$env{'user.name'}; }
                   4901:     my $uhome=&homeserver($uname,$udomain);
                   4902:     if ($regexp) {
                   4903: 	$regexp=&escape($regexp);
                   4904:     } else {
                   4905: 	$regexp='.';
                   4906:     }
1.1086    raeburn  4907:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755     albertel 4908:     my @pairs=split(/\&/,$rep);
                   4909:     my %returnhash=();
1.1098    foxr     4910:     if (!($rep =~ /^error/ )) {
                   4911: 	foreach my $item (@pairs) {
                   4912: 	    my ($key,$value)=split(/=/,$item,2);
                   4913: 	    $key = &unescape($key);
                   4914: 	    next if ($key =~ /^error: 2 /);
                   4915: 	    $returnhash{$key}=&thaw_unescape($value);
                   4916: 	}
1.755     albertel 4917:     }
                   4918:     return %returnhash;
1.407     www      4919: }
                   4920: 
1.1098    foxr     4921: 
1.717     albertel 4922: # --------------------------------------------------------- dumpstore interface
                   4923: 
                   4924: sub dumpstore {
                   4925:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 4926:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4927:    if (!$uname) { $uname=$env{'user.name'}; }
                   4928:    my $uhome=&homeserver($uname,$udomain);
                   4929:    if ($regexp) {
                   4930:        $regexp=&escape($regexp);
                   4931:    } else {
                   4932:        $regexp='.';
                   4933:    }
                   4934:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   4935:    my @pairs=split(/\&/,$rep);
                   4936:    my %returnhash=();
                   4937:    foreach my $item (@pairs) {
                   4938:        my ($key,$value)=split(/=/,$item,2);
                   4939:        next if ($key =~ /^error: 2 /);
                   4940:        $returnhash{$key}=&thaw_unescape($value);
                   4941:    }
                   4942:    return %returnhash;
1.717     albertel 4943: }
                   4944: 
1.407     www      4945: # -------------------------------------------------------------- keys interface
                   4946: 
                   4947: sub getkeys {
                   4948:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 4949:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   4950:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      4951:    my $uhome=&homeserver($uname,$udomain);
                   4952:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   4953:    my @keyarray=();
1.800     albertel 4954:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  4955:       next if ($key =~ /^error: 2 /);
1.800     albertel 4956:       push(@keyarray,&unescape($key));
1.407     www      4957:    }
                   4958:    return @keyarray;
1.318     matthew  4959: }
                   4960: 
1.319     matthew  4961: # --------------------------------------------------------------- currentdump
                   4962: sub currentdump {
1.328     matthew  4963:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 4964:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   4965:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   4966:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  4967:    my $uhome = &homeserver($sname,$sdom);
                   4968:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  4969:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  4970:    #
1.318     matthew  4971:    my %returnhash=();
1.319     matthew  4972:    #
                   4973:    if ($rep eq "unknown_cmd") { 
                   4974:        # an old lond will not know currentdump
                   4975:        # Do a dump and make it look like a currentdump
1.822     albertel 4976:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  4977:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   4978:        my %hash = @tmp;
                   4979:        @tmp=();
1.424     matthew  4980:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  4981:    } else {
                   4982:        my @pairs=split(/\&/,$rep);
1.800     albertel 4983:        foreach my $pair (@pairs) {
                   4984:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  4985:            my ($symb,$param) = split(/:/,$key);
                   4986:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 4987:                                                         &thaw_unescape($value);
1.319     matthew  4988:        }
1.191     harris41 4989:    }
1.12      www      4990:    return %returnhash;
1.424     matthew  4991: }
                   4992: 
                   4993: sub convert_dump_to_currentdump{
                   4994:     my %hash = %{shift()};
                   4995:     my %returnhash;
                   4996:     # Code ripped from lond, essentially.  The only difference
                   4997:     # here is the unescaping done by lonnet::dump().  Conceivably
                   4998:     # we might run in to problems with parameter names =~ /^v\./
                   4999:     while (my ($key,$value) = each(%hash)) {
                   5000:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5001: 	$symb  = &unescape($symb);
                   5002: 	$param = &unescape($param);
1.424     matthew  5003:         next if ($v eq 'version' || $symb eq 'keys');
                   5004:         next if (exists($returnhash{$symb}) &&
                   5005:                  exists($returnhash{$symb}->{$param}) &&
                   5006:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5007:         $returnhash{$symb}->{$param}=$value;
                   5008:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5009:     }
                   5010:     #
                   5011:     # Remove all of the keys in the hashes which keep track of
                   5012:     # the version of the parameter.
                   5013:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5014:         # use a foreach because we are going to delete from the hash.
                   5015:         foreach my $key (keys(%$param_hash)) {
                   5016:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5017:         }
                   5018:     }
                   5019:     return \%returnhash;
1.12      www      5020: }
                   5021: 
1.627     albertel 5022: # ------------------------------------------------------ critical inc interface
                   5023: 
                   5024: sub cinc {
                   5025:     return &inc(@_,'critical');
                   5026: }
                   5027: 
1.449     matthew  5028: # --------------------------------------------------------------- inc interface
                   5029: 
                   5030: sub inc {
1.627     albertel 5031:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5032:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5033:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5034:     my $uhome=&homeserver($uname,$udomain);
                   5035:     my $items='';
                   5036:     if (! ref($store)) {
                   5037:         # got a single value, so use that instead
                   5038:         $items = &escape($store).'=&';
                   5039:     } elsif (ref($store) eq 'SCALAR') {
                   5040:         $items = &escape($$store).'=&';        
                   5041:     } elsif (ref($store) eq 'ARRAY') {
                   5042:         $items = join('=&',map {&escape($_);} @{$store});
                   5043:     } elsif (ref($store) eq 'HASH') {
                   5044:         while (my($key,$value) = each(%{$store})) {
                   5045:             $items.= &escape($key).'='.&escape($value).'&';
                   5046:         }
                   5047:     }
                   5048:     $items=~s/\&$//;
1.627     albertel 5049:     if ($critical) {
                   5050: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5051:     } else {
                   5052: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5053:     }
1.449     matthew  5054: }
                   5055: 
1.12      www      5056: # --------------------------------------------------------------- put interface
                   5057: 
                   5058: sub put {
1.134     albertel 5059:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5060:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5061:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5062:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5063:    my $items='';
1.800     albertel 5064:    foreach my $item (keys(%$storehash)) {
                   5065:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5066:    }
1.12      www      5067:    $items=~s/\&$//;
1.134     albertel 5068:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5069: }
                   5070: 
1.631     albertel 5071: # ------------------------------------------------------------ newput interface
                   5072: 
                   5073: sub newput {
                   5074:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5075:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5076:    if (!$uname) { $uname=$env{'user.name'}; }
                   5077:    my $uhome=&homeserver($uname,$udomain);
                   5078:    my $items='';
                   5079:    foreach my $key (keys(%$storehash)) {
                   5080:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5081:    }
                   5082:    $items=~s/\&$//;
                   5083:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5084: }
                   5085: 
                   5086: # ---------------------------------------------------------  putstore interface
                   5087: 
1.524     raeburn  5088: sub putstore {
1.715     albertel 5089:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5090:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5091:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5092:    my $uhome=&homeserver($uname,$udomain);
                   5093:    my $items='';
1.715     albertel 5094:    foreach my $key (keys(%$storehash)) {
                   5095:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5096:    }
1.715     albertel 5097:    $items=~s/\&$//;
1.716     albertel 5098:    my $esc_symb=&escape($symb);
                   5099:    my $esc_v=&escape($version);
1.715     albertel 5100:    my $reply =
1.716     albertel 5101:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5102: 	      $uhome);
                   5103:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5104:        # gfall back to way things use to be done
1.715     albertel 5105:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5106: 			    $uname);
1.524     raeburn  5107:    }
1.715     albertel 5108:    return $reply;
                   5109: }
                   5110: 
                   5111: sub old_putstore {
1.716     albertel 5112:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5113:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5114:     if (!$uname) { $uname=$env{'user.name'}; }
                   5115:     my $uhome=&homeserver($uname,$udomain);
                   5116:     my %newstorehash;
1.800     albertel 5117:     foreach my $item (keys(%$storehash)) {
                   5118: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5119: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5120:     }
                   5121:     my $items='';
                   5122:     my %allitems = ();
1.800     albertel 5123:     foreach my $item (keys(%newstorehash)) {
                   5124: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5125: 	    my $key = $1.':keys:'.$2;
                   5126: 	    $allitems{$key} .= $3.':';
                   5127: 	}
1.800     albertel 5128: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5129:     }
1.800     albertel 5130:     foreach my $item (keys(%allitems)) {
                   5131: 	$allitems{$item} =~ s/\:$//;
                   5132: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5133:     }
                   5134:     $items=~s/\&$//;
                   5135:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5136: }
                   5137: 
1.47      www      5138: # ------------------------------------------------------ critical put interface
                   5139: 
                   5140: sub cput {
1.134     albertel 5141:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5142:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5143:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5144:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5145:    my $items='';
1.800     albertel 5146:    foreach my $item (keys(%$storehash)) {
                   5147:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5148:    }
1.47      www      5149:    $items=~s/\&$//;
1.134     albertel 5150:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5151: }
                   5152: 
                   5153: # -------------------------------------------------------------- eget interface
                   5154: 
                   5155: sub eget {
1.133     albertel 5156:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5157:    my $items='';
1.800     albertel 5158:    foreach my $item (@$storearr) {
                   5159:        $items.=&escape($item).'&';
1.191     harris41 5160:    }
1.12      www      5161:    $items=~s/\&$//;
1.620     albertel 5162:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5163:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5164:    my $uhome=&homeserver($uname,$udomain);
                   5165:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5166:    my @pairs=split(/\&/,$rep);
                   5167:    my %returnhash=();
1.42      www      5168:    my $i=0;
1.800     albertel 5169:    foreach my $item (@$storearr) {
                   5170:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5171:       $i++;
1.191     harris41 5172:    }
1.12      www      5173:    return %returnhash;
                   5174: }
                   5175: 
1.667     albertel 5176: # ------------------------------------------------------------ tmpput interface
                   5177: sub tmpput {
1.802     raeburn  5178:     my ($storehash,$server,$context)=@_;
1.667     albertel 5179:     my $items='';
1.800     albertel 5180:     foreach my $item (keys(%$storehash)) {
                   5181: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5182:     }
                   5183:     $items=~s/\&$//;
1.802     raeburn  5184:     if (defined($context)) {
                   5185:         $items .= ':'.&escape($context);
                   5186:     }
1.667     albertel 5187:     return &reply("tmpput:$items",$server);
                   5188: }
                   5189: 
                   5190: # ------------------------------------------------------------ tmpget interface
                   5191: sub tmpget {
1.688     albertel 5192:     my ($token,$server)=@_;
                   5193:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5194:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5195:     my %returnhash;
                   5196:     foreach my $item (split(/\&/,$rep)) {
                   5197: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5198:         next if ($key =~ /^error: 2 /);
1.667     albertel 5199: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5200:     }
                   5201:     return %returnhash;
                   5202: }
                   5203: 
1.1113    raeburn  5204: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5205: sub tmpdel {
                   5206:     my ($token,$server)=@_;
                   5207:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5208:     return &reply("tmpdel:$token",$server);
                   5209: }
                   5210: 
1.765     albertel 5211: # -------------------------------------------------- portfolio access checking
                   5212: 
                   5213: sub portfolio_access {
1.766     albertel 5214:     my ($requrl) = @_;
1.765     albertel 5215:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5216:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5217:     if ($result) {
                   5218:         my %setters;
                   5219:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5220:             my ($startblock,$endblock) =
                   5221:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5222:             if ($startblock && $endblock) {
                   5223:                 return 'B';
                   5224:             }
                   5225:         } else {
                   5226:             my ($startblock,$endblock) =
                   5227:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5228:             if ($startblock && $endblock) {
                   5229:                 return 'B';
                   5230:             }
                   5231:         }
                   5232:     }
1.765     albertel 5233:     if ($result eq 'ok') {
1.766     albertel 5234:        return 'F';
1.765     albertel 5235:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5236:        return 'A';
1.765     albertel 5237:     }
1.766     albertel 5238:     return '';
1.765     albertel 5239: }
                   5240: 
                   5241: sub get_portfolio_access {
1.767     albertel 5242:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5243: 
                   5244:     if (!ref($access_hash)) {
                   5245: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5246: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5247: 						   $file_name);
                   5248: 	$access_hash = $access_controls{$file_name};
                   5249:     }
                   5250: 
1.765     albertel 5251:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5252:     my $now = time;
                   5253:     if (ref($access_hash) eq 'HASH') {
                   5254:         foreach my $key (keys(%{$access_hash})) {
                   5255:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5256:             if ($start > $now) {
                   5257:                 next;
                   5258:             }
                   5259:             if ($end && $end<$now) {
                   5260:                 next;
                   5261:             }
                   5262:             if ($scope eq 'public') {
                   5263:                 $public = $key;
                   5264:                 last;
                   5265:             } elsif ($scope eq 'guest') {
                   5266:                 $guest = $key;
                   5267:             } elsif ($scope eq 'domains') {
                   5268:                 push(@domains,$key);
                   5269:             } elsif ($scope eq 'users') {
                   5270:                 push(@users,$key);
                   5271:             } elsif ($scope eq 'course') {
                   5272:                 push(@courses,$key);
                   5273:             } elsif ($scope eq 'group') {
                   5274:                 push(@groups,$key);
                   5275:             }
                   5276:         }
                   5277:         if ($public) {
                   5278:             return 'ok';
                   5279:         }
                   5280:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5281:             if ($guest) {
                   5282:                 return $guest;
                   5283:             }
                   5284:         } else {
                   5285:             if (@domains > 0) {
                   5286:                 foreach my $domkey (@domains) {
                   5287:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5288:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5289:                             return 'ok';
                   5290:                         }
                   5291:                     }
                   5292:                 }
                   5293:             }
                   5294:             if (@users > 0) {
                   5295:                 foreach my $userkey (@users) {
1.865     raeburn  5296:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5297:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5298:                             if (ref($item) eq 'HASH') {
                   5299:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5300:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5301:                                     return 'ok';
                   5302:                                 }
                   5303:                             }
                   5304:                         }
                   5305:                     } 
1.765     albertel 5306:                 }
                   5307:             }
                   5308:             my %roleshash;
                   5309:             my @courses_and_groups = @courses;
                   5310:             push(@courses_and_groups,@groups); 
                   5311:             if (@courses_and_groups > 0) {
                   5312:                 my (%allgroups,%allroles); 
                   5313:                 my ($start,$end,$role,$sec,$group);
                   5314:                 foreach my $envkey (%env) {
1.1060    raeburn  5315:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5316:                         my $cid = $2.'_'.$3; 
                   5317:                         if ($1 eq 'gr') {
                   5318:                             $group = $4;
                   5319:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5320:                         } else {
                   5321:                             if ($4 eq '') {
                   5322:                                 $sec = 'none';
                   5323:                             } else {
                   5324:                                 $sec = $4;
                   5325:                             }
                   5326:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5327:                         }
1.811     albertel 5328:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5329:                         my $cid = $2.'_'.$3;
                   5330:                         if ($4 eq '') {
                   5331:                             $sec = 'none';
                   5332:                         } else {
                   5333:                             $sec = $4;
                   5334:                         }
                   5335:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5336:                     }
                   5337:                 }
                   5338:                 if (keys(%allroles) == 0) {
                   5339:                     return;
                   5340:                 }
                   5341:                 foreach my $key (@courses_and_groups) {
                   5342:                     my %content = %{$$access_hash{$key}};
                   5343:                     my $cnum = $content{'number'};
                   5344:                     my $cdom = $content{'domain'};
                   5345:                     my $cid = $cdom.'_'.$cnum;
                   5346:                     if (!exists($allroles{$cid})) {
                   5347:                         next;
                   5348:                     }    
                   5349:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5350:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5351:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5352:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5353:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5354:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5355:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5356:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5357:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5358:                                         if (grep/^all$/,@sections) {
                   5359:                                             return 'ok';
                   5360:                                         } else {
                   5361:                                             if (grep/^$sec$/,@sections) {
                   5362:                                                 return 'ok';
                   5363:                                             }
                   5364:                                         }
                   5365:                                     }
                   5366:                                 }
                   5367:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5368:                                     if (grep/^none$/,@groups) {
                   5369:                                         return 'ok';
                   5370:                                     }
                   5371:                                 } else {
                   5372:                                     if (grep/^all$/,@groups) {
                   5373:                                         return 'ok';
                   5374:                                     } 
                   5375:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5376:                                         if (grep/^$group$/,@groups) {
                   5377:                                             return 'ok';
                   5378:                                         }
                   5379:                                     }
                   5380:                                 } 
                   5381:                             }
                   5382:                         }
                   5383:                     }
                   5384:                 }
                   5385:             }
                   5386:             if ($guest) {
                   5387:                 return $guest;
                   5388:             }
                   5389:         }
                   5390:     }
                   5391:     return;
                   5392: }
                   5393: 
                   5394: sub course_group_datechecker {
                   5395:     my ($dates,$now,$status) = @_;
                   5396:     my ($start,$end) = split(/\./,$dates);
                   5397:     if (!$start && !$end) {
                   5398:         return 'ok';
                   5399:     }
                   5400:     if (grep/^active$/,@{$status}) {
                   5401:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5402:             return 'ok';
                   5403:         }
                   5404:     }
                   5405:     if (grep/^previous$/,@{$status}) {
                   5406:         if ($end > $now ) {
                   5407:             return 'ok';
                   5408:         }
                   5409:     }
                   5410:     if (grep/^future$/,@{$status}) {
                   5411:         if ($start > $now) {
                   5412:             return 'ok';
                   5413:         }
                   5414:     }
                   5415:     return; 
                   5416: }
                   5417: 
                   5418: sub parse_portfolio_url {
                   5419:     my ($url) = @_;
                   5420: 
                   5421:     my ($type,$udom,$unum,$group,$file_name);
                   5422:     
1.823     albertel 5423:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5424: 	$type = 1;
                   5425:         $udom = $1;
                   5426:         $unum = $2;
                   5427:         $file_name = $3;
1.823     albertel 5428:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5429: 	$type = 2;
                   5430:         $udom = $1;
                   5431:         $unum = $2;
                   5432:         $group = $3;
                   5433:         $file_name = $3.'/'.$4;
                   5434:     }
                   5435:     if (wantarray) {
                   5436: 	return ($type,$udom,$unum,$file_name,$group);
                   5437:     }
                   5438:     return $type;
                   5439: }
                   5440: 
                   5441: sub is_portfolio_url {
                   5442:     my ($url) = @_;
                   5443:     return scalar(&parse_portfolio_url($url));
                   5444: }
                   5445: 
1.798     raeburn  5446: sub is_portfolio_file {
                   5447:     my ($file) = @_;
1.820     raeburn  5448:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5449:         return 1;
                   5450:     }
                   5451:     return;
                   5452: }
                   5453: 
1.976     raeburn  5454: sub usertools_access {
1.1084    raeburn  5455:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5456:     my ($access,%tools);
                   5457:     if ($context eq '') {
                   5458:         $context = 'tools';
                   5459:     }
                   5460:     if ($context eq 'requestcourses') {
                   5461:         %tools = (
                   5462:                       official   => 1,
                   5463:                       unofficial => 1,
1.1006    raeburn  5464:                       community  => 1,
1.985     raeburn  5465:                  );
                   5466:     } else {
                   5467:         %tools = (
                   5468:                       aboutme   => 1,
                   5469:                       blog      => 1,
                   5470:                       portfolio => 1,
                   5471:                  );
                   5472:     }
1.976     raeburn  5473:     return if (!defined($tools{$tool}));
                   5474: 
                   5475:     if ((!defined($udom)) || (!defined($uname))) {
                   5476:         $udom = $env{'user.domain'};
                   5477:         $uname = $env{'user.name'};
                   5478:     }
                   5479: 
1.978     raeburn  5480:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5481:         if ($action ne 'reload') {
1.985     raeburn  5482:             if ($context eq 'requestcourses') {
                   5483:                 return $env{'environment.canrequest.'.$tool};
                   5484:             } else {
                   5485:                 return $env{'environment.availabletools.'.$tool};
                   5486:             }
                   5487:         }
1.976     raeburn  5488:     }
                   5489: 
                   5490:     my ($toolstatus,$inststatus);
                   5491: 
1.985     raeburn  5492:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5493:          ($action ne 'reload')) {
                   5494:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5495:         $inststatus = $env{'environment.inststatus'};
                   5496:     } else {
1.1084    raeburn  5497:         if (ref($userenvref) eq 'HASH') {
                   5498:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5499:             $inststatus = $userenvref->{'inststatus'};
                   5500:         } else {
                   5501:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5502:             $toolstatus = $userenv{$context.'.'.$tool};
                   5503:             $inststatus = $userenv{'inststatus'};
                   5504:         }
1.976     raeburn  5505:     }
                   5506: 
                   5507:     if ($toolstatus ne '') {
                   5508:         if ($toolstatus) {
                   5509:             $access = 1;
                   5510:         } else {
                   5511:             $access = 0;
                   5512:         }
                   5513:         return $access;
                   5514:     }
                   5515: 
1.1084    raeburn  5516:     my ($is_adv,%domdef);
                   5517:     if (ref($is_advref) eq 'HASH') {
                   5518:         $is_adv = $is_advref->{'is_adv'};
                   5519:     } else {
                   5520:         $is_adv = &is_advanced_user($udom,$uname);
                   5521:     }
                   5522:     if (ref($domdefref) eq 'HASH') {
                   5523:         %domdef = %{$domdefref};
                   5524:     } else {
                   5525:         %domdef = &get_domain_defaults($udom);
                   5526:     }
1.976     raeburn  5527:     if (ref($domdef{$tool}) eq 'HASH') {
                   5528:         if ($is_adv) {
                   5529:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5530:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5531:                     $access = 1;
                   5532:                 } else {
                   5533:                     $access = 0;
                   5534:                 }
                   5535:                 return $access;
                   5536:             }
                   5537:         }
                   5538:         if ($inststatus ne '') {
                   5539:             my ($hasaccess,$hasnoaccess);
                   5540:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5541:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5542:                     if ($domdef{$tool}{$affiliation}) {
                   5543:                         $hasaccess = 1;
                   5544:                     } else {
                   5545:                         $hasnoaccess = 1;
                   5546:                     }
                   5547:                 }
                   5548:             }
                   5549:             if ($hasaccess || $hasnoaccess) {
                   5550:                 if ($hasaccess) {
                   5551:                     $access = 1;
                   5552:                 } elsif ($hasnoaccess) {
                   5553:                     $access = 0; 
                   5554:                 }
                   5555:                 return $access;
                   5556:             }
                   5557:         } else {
                   5558:             if ($domdef{$tool}{'default'} ne '') {
                   5559:                 if ($domdef{$tool}{'default'}) {
                   5560:                     $access = 1;
                   5561:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5562:                     $access = 0;
                   5563:                 }
                   5564:                 return $access;
                   5565:             }
                   5566:         }
                   5567:     } else {
1.985     raeburn  5568:         if ($context eq 'tools') {
                   5569:             $access = 1;
                   5570:         } else {
                   5571:             $access = 0;
                   5572:         }
1.976     raeburn  5573:         return $access;
                   5574:     }
                   5575: }
                   5576: 
1.1050    raeburn  5577: sub is_course_owner {
                   5578:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5579:     if (($udom eq '') || ($uname eq '')) {
                   5580:         $udom = $env{'user.domain'};
                   5581:         $uname = $env{'user.name'};
                   5582:     }
                   5583:     unless (($udom eq '') || ($uname eq '')) {
                   5584:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5585:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5586:                 return 1;
                   5587:             } else {
                   5588:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5589:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5590:                     return 1;
                   5591:                 }
                   5592:             }
                   5593:         }
                   5594:     }
                   5595:     return;
                   5596: }
                   5597: 
1.976     raeburn  5598: sub is_advanced_user {
                   5599:     my ($udom,$uname) = @_;
1.1085    raeburn  5600:     if ($udom ne '' && $uname ne '') {
                   5601:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5602:             if (wantarray) {
                   5603:                 return ($env{'user.adv'},$env{'user.author'});
                   5604:             } else {
                   5605:                 return $env{'user.adv'};
                   5606:             }
1.1085    raeburn  5607:         }
                   5608:     }
1.976     raeburn  5609:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5610:     my %allroles;
1.1128    raeburn  5611:     my ($is_adv,$is_author);
1.976     raeburn  5612:     foreach my $role (keys(%roleshash)) {
                   5613:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5614:         my $area = '/'.$tdomain.'/'.$trest;
                   5615:         if ($sec ne '') {
                   5616:             $area .= '/'.$sec;
                   5617:         }
                   5618:         if (($area ne '') && ($trole ne '')) {
                   5619:             my $spec=$trole.'.'.$area;
                   5620:             if ($trole =~ /^cr\//) {
                   5621:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5622:             } elsif ($trole ne 'gr') {
                   5623:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5624:             }
1.1128    raeburn  5625:             if ($trole eq 'au') {
                   5626:                 $is_author = 1;
                   5627:             }
1.976     raeburn  5628:         }
                   5629:     }
                   5630:     foreach my $role (keys(%allroles)) {
                   5631:         last if ($is_adv);
                   5632:         foreach my $item (split(/:/,$allroles{$role})) {
                   5633:             if ($item ne '') {
                   5634:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5635:                 if ($privilege eq 'adv') {
                   5636:                     $is_adv = 1;
                   5637:                     last;
                   5638:                 }
                   5639:             }
                   5640:         }
                   5641:     }
1.1128    raeburn  5642:     if (wantarray) {
                   5643:         return ($is_adv,$is_author);
                   5644:     }
1.976     raeburn  5645:     return $is_adv;
                   5646: }
1.798     raeburn  5647: 
1.1035    raeburn  5648: sub check_can_request {
1.1036    raeburn  5649:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5650:     my $canreq = 0;
                   5651:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5652:     my @options = ('approval','validate','autolimit');
                   5653:     my $optregex = join('|',@options);
                   5654:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5655:         foreach my $type (@{$types}) {
                   5656:             if (&usertools_access($env{'user.name'},
                   5657:                                   $env{'user.domain'},
                   5658:                                   $type,undef,'requestcourses')) {
                   5659:                 $canreq ++;
1.1036    raeburn  5660:                 if (ref($request_domains) eq 'HASH') {
                   5661:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5662:                 }
1.1035    raeburn  5663:                 if ($dom eq $env{'user.domain'}) {
                   5664:                     $can_request->{$type} = 1;
                   5665:                 }
                   5666:             }
                   5667:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5668:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5669:                 if (@curr > 0) {
1.1036    raeburn  5670:                     foreach my $item (@curr) {
                   5671:                         if (ref($request_domains) eq 'HASH') {
                   5672:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5673:                             if ($otherdom ne '') {
                   5674:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5675:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5676:                                         push(@{$request_domains->{$type}},$otherdom);
                   5677:                                     }
                   5678:                                 } else {
                   5679:                                     push(@{$request_domains->{$type}},$otherdom);
                   5680:                                 }
                   5681:                             }
                   5682:                         }
                   5683:                     }
                   5684:                     unless($dom eq $env{'user.domain'}) {
                   5685:                         $canreq ++;
1.1035    raeburn  5686:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5687:                             $can_request->{$type} = 1;
                   5688:                         }
                   5689:                     }
                   5690:                 }
                   5691:             }
                   5692:         }
                   5693:     }
                   5694:     return $canreq;
                   5695: }
                   5696: 
1.341     www      5697: # ---------------------------------------------- Custom access rule evaluation
                   5698: 
                   5699: sub customaccess {
                   5700:     my ($priv,$uri)=@_;
1.807     albertel 5701:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5702:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5703:     $udom = &LONCAPA::clean_domain($udom);
                   5704:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5705:     my $access=0;
1.800     albertel 5706:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5707: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5708: 	if ($type eq 'user') {
                   5709: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5710: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5711: 		if ($tdom) {
                   5712: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5713: 		}
1.896     albertel 5714: 		if ($tuname) {
                   5715: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5716: 		}
                   5717: 		$access=($effect eq 'allow');
                   5718: 		last;
                   5719: 	    }
                   5720: 	} else {
                   5721: 	    if ($role) {
                   5722: 		if ($role ne $urole) { next; }
                   5723: 	    }
                   5724: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5725: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5726: 		if ($tdom) {
                   5727: 		    if ($tdom ne $udom) { next; }
                   5728: 		}
                   5729: 		if ($tcrs) {
                   5730: 		    if ($tcrs ne $ucrs) { next; }
                   5731: 		}
                   5732: 		if ($tsec) {
                   5733: 		    if ($tsec ne $usec) { next; }
                   5734: 		}
                   5735: 		$access=($effect eq 'allow');
                   5736: 		last;
                   5737: 	    }
                   5738: 	    if ($realm eq '' && $role eq '') {
                   5739: 		$access=($effect eq 'allow');
                   5740: 	    }
1.402     bowersj2 5741: 	}
1.341     www      5742:     }
                   5743:     return $access;
                   5744: }
                   5745: 
1.103     harris41 5746: # ------------------------------------------------- Check for a user privilege
1.12      www      5747: 
                   5748: sub allowed {
1.810     raeburn  5749:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5750:     my $ver_orguri=$uri;
1.439     www      5751:     $uri=&deversion($uri);
1.152     www      5752:     my $orguri=$uri;
1.52      www      5753:     $uri=&declutter($uri);
1.809     raeburn  5754: 
1.810     raeburn  5755:     if ($priv eq 'evb') {
                   5756: # Evade communication block restrictions for specified role in a course
                   5757:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5758:             return $1;
                   5759:         } else {
                   5760:             return;
                   5761:         }
                   5762:     }
                   5763: 
1.620     albertel 5764:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5765: # Free bre access to adm and meta resources
1.775     albertel 5766:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5767: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5768: 	&& ($priv eq 'bre')) {
1.14      www      5769: 	return 'F';
1.159     www      5770:     }
                   5771: 
1.545     banghart 5772: # Free bre access to user's own portfolio contents
1.714     raeburn  5773:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5774:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5775: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5776:         my %setters;
                   5777:         my ($startblock,$endblock) = 
                   5778:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5779:         if ($startblock && $endblock) {
                   5780:             return 'B';
                   5781:         } else {
                   5782:             return 'F';
                   5783:         }
1.545     banghart 5784:     }
                   5785: 
1.762     raeburn  5786: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5787:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5788:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5789:         if (exists($env{'request.course.id'})) {
                   5790:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5791:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5792:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5793:                 my $courseprivid=$env{'request.course.id'};
                   5794:                 $courseprivid=~s/\_/\//;
                   5795:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5796:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5797:                     return $1; 
1.762     raeburn  5798:                 } else {
                   5799:                     if ($env{'request.course.sec'}) {
                   5800:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5801:                     }
                   5802:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5803:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5804:                         return $2;
                   5805:                     }
1.714     raeburn  5806:                 }
                   5807:             }
                   5808:         }
                   5809:     }
                   5810: 
1.159     www      5811: # Free bre to public access
                   5812: 
                   5813:     if ($priv eq 'bre') {
1.238     www      5814:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5815: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5816:            return 'F'; 
                   5817:         }
1.238     www      5818:         if ($copyright eq 'priv') {
                   5819:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5820: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5821: 		return '';
                   5822:             }
                   5823:         }
                   5824:         if ($copyright eq 'domain') {
                   5825:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5826: 	    unless (($env{'user.domain'} eq $1) ||
                   5827:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5828: 		return '';
                   5829:             }
1.262     matthew  5830:         }
1.620     albertel 5831:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  5832:             # Library role, so allow browsing of resources in this domain.
                   5833:             return 'F';
1.238     www      5834:         }
1.341     www      5835:         if ($copyright eq 'custom') {
                   5836: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   5837:         }
1.14      www      5838:     }
1.264     matthew  5839:     # Domain coordinator is trying to create a course
1.620     albertel 5840:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  5841:         # uri is the requested domain in this case.
                   5842:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  5843:         # a role of dc for the domain in question.
1.620     albertel 5844:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  5845:     }
1.29      www      5846: 
1.52      www      5847:     my $thisallowed='';
                   5848:     my $statecond=0;
                   5849:     my $courseprivid='';
                   5850: 
1.1039    raeburn  5851:     my $ownaccess;
1.1043    raeburn  5852:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  5853:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   5854:         if ($uri eq '') {
                   5855:             $ownaccess = 1;
                   5856:         } else {
                   5857:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   5858:                 my $udom = $env{'user.domain'};
                   5859:                 my $uname = $env{'user.name'};
                   5860:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   5861:                     $ownaccess = 1;
1.1040    raeburn  5862:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  5863:                     unless ($uri =~ m{\.\./}) {
                   5864:                         $ownaccess = 1;
                   5865:                     }
                   5866:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   5867:                     my $now = time;
                   5868:                     if ($uri =~ m{^([^/]+)/?$}) {
                   5869:                         my $adom = $1;
                   5870:                         foreach my $key (keys(%env)) {
1.1042    raeburn  5871:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  5872:                                 my ($start,$end) = split('.',$env{$key});
                   5873:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5874:                                     $ownaccess = 1;
                   5875:                                     last;
                   5876:                                 }
                   5877:                             }
                   5878:                         }
                   5879:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   5880:                         my $adom = $1;
                   5881:                         my $aname = $2;
1.1042    raeburn  5882:                         foreach my $role ('ca','aa') { 
                   5883:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   5884:                                 my ($start,$end) =
                   5885:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   5886:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   5887:                                     $ownaccess = 1;
                   5888:                                     last;
                   5889:                                 }
1.1039    raeburn  5890:                             }
                   5891:                         }
                   5892:                     }
                   5893:                 }
                   5894:             }
                   5895:         }
                   5896:     }
                   5897: 
1.52      www      5898: # Course
                   5899: 
1.620     albertel 5900:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5901:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5902:             $thisallowed.=$1;
                   5903:         }
1.52      www      5904:     }
1.29      www      5905: 
1.52      www      5906: # Domain
                   5907: 
1.620     albertel 5908:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 5909:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5910:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5911:             $thisallowed.=$1;
                   5912:         }
1.12      www      5913:     }
1.52      www      5914: 
1.1141    raeburn  5915: # User who is not author or co-author might still be able to edit
                   5916: # resource of an author in the domain (e.g., if Domain Coordinator).
                   5917:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   5918:         (&allowed('mdc',$env{'request.course.id'}))) {
                   5919:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   5920:             $thisallowed.=$1;
                   5921:         }
                   5922:     }
                   5923: 
1.52      www      5924: # Course: uri itself is a course
1.66      www      5925:     my $courseuri=$uri;
                   5926:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      5927:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      5928: 
1.620     albertel 5929:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 5930:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  5931:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  5932:             $thisallowed.=$1;
                   5933:         }
1.12      www      5934:     }
1.29      www      5935: 
1.665     albertel 5936: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 5937: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 5938:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 5939: 	$thisallowed='';
1.671     raeburn  5940:         my ($match)=&is_on_map($uri);
                   5941:         if ($match) {
                   5942:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   5943:                   =~/\Q$priv\E\&([^\:]*)/) {
                   5944:                 $thisallowed.=$1;
                   5945:             }
                   5946:         } else {
1.705     albertel 5947:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  5948:             if ($refuri) {
                   5949:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  5950:                     $thisallowed='F';
1.671     raeburn  5951:                 } else {
                   5952:                     $refuri=&declutter($refuri);
                   5953:                     my ($match) = &is_on_map($refuri);
                   5954:                     if ($match) {
                   5955:                         $thisallowed='F';
                   5956:                     }
1.669     raeburn  5957:                 }
1.671     raeburn  5958:             }
                   5959:         }
1.314     www      5960:     }
1.492     albertel 5961: 
1.766     albertel 5962:     if ($priv eq 'bre'
                   5963: 	&& $thisallowed ne 'F' 
                   5964: 	&& $thisallowed ne '2'
                   5965: 	&& &is_portfolio_url($uri)) {
                   5966: 	$thisallowed = &portfolio_access($uri);
                   5967:     }
                   5968:     
1.52      www      5969: # Full access at system, domain or course-wide level? Exit.
1.29      www      5970:     if ($thisallowed=~/F/) {
                   5971: 	return 'F';
                   5972:     }
                   5973: 
1.52      www      5974: # If this is generating or modifying users, exit with special codes
1.29      www      5975: 
1.643     www      5976:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   5977: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 5978: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      5979: # no author name given, so this just checks on the general right to make a co-author in this domain
                   5980: 	    unless ($auname) { return $thisallowed; }
                   5981: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 5982: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   5983: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   5984: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   5985: 	}
1.52      www      5986: 	return $thisallowed;
                   5987:     }
                   5988: #
1.103     harris41 5989: # Gathered so far: system, domain and course wide privileges
1.52      www      5990: #
                   5991: # Course: See if uri or referer is an individual resource that is part of 
                   5992: # the course
                   5993: 
1.620     albertel 5994:     if ($env{'request.course.id'}) {
1.232     www      5995: 
1.620     albertel 5996:        $courseprivid=$env{'request.course.id'};
                   5997:        if ($env{'request.course.sec'}) {
                   5998:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      5999:        }
                   6000:        $courseprivid=~s/\_/\//;
                   6001:        my $checkreferer=1;
1.232     www      6002:        my ($match,$cond)=&is_on_map($uri);
                   6003:        if ($match) {
                   6004:            $statecond=$cond;
1.620     albertel 6005:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6006:                =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      6007:                $thisallowed.=$1;
                   6008:                $checkreferer=0;
                   6009:            }
1.29      www      6010:        }
1.83      www      6011:        
1.148     www      6012:        if ($checkreferer) {
1.620     albertel 6013: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6014:             unless ($refuri) {
1.800     albertel 6015:                 foreach my $key (keys(%env)) {
                   6016: 		    if ($key=~/^httpref\..*\*/) {
                   6017: 			my $pattern=$key;
1.156     www      6018:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6019:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6020:                         $pattern=~s/\//\\\//g;
1.152     www      6021:                         if ($orguri=~/$pattern/) {
1.800     albertel 6022: 			    $refuri=$env{$key};
1.148     www      6023:                         }
                   6024:                     }
1.191     harris41 6025:                 }
1.148     www      6026:             }
1.232     www      6027: 
1.148     www      6028:          if ($refuri) { 
1.152     www      6029: 	  $refuri=&declutter($refuri);
1.232     www      6030:           my ($match,$cond)=&is_on_map($refuri);
                   6031:             if ($match) {
                   6032:               my $refstatecond=$cond;
1.620     albertel 6033:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6034:                   =~/\Q$priv\E\&([^\:]*)/) {
1.52      www      6035:                   $thisallowed.=$1;
1.53      www      6036:                   $uri=$refuri;
                   6037:                   $statecond=$refstatecond;
1.52      www      6038:               }
                   6039:           }
1.148     www      6040:         }
1.29      www      6041:        }
1.52      www      6042:    }
1.29      www      6043: 
1.52      www      6044: #
1.103     harris41 6045: # Gathered now: all privileges that could apply, and condition number
1.52      www      6046: # 
                   6047: #
                   6048: # Full or no access?
                   6049: #
1.29      www      6050: 
1.52      www      6051:     if ($thisallowed=~/F/) {
                   6052: 	return 'F';
                   6053:     }
1.29      www      6054: 
1.52      www      6055:     unless ($thisallowed) {
                   6056:         return '';
                   6057:     }
1.29      www      6058: 
1.52      www      6059: # Restrictions exist, deal with them
                   6060: #
                   6061: #   C:according to course preferences
                   6062: #   R:according to resource settings
                   6063: #   L:unless locked
                   6064: #   X:according to user session state
                   6065: #
                   6066: 
                   6067: # Possibly locked functionality, check all courses
1.54      www      6068: # Locks might take effect only after 10 minutes cache expiration for other
                   6069: # courses, and 2 minutes for current course
1.52      www      6070: 
                   6071:     my $envkey;
                   6072:     if ($thisallowed=~/L/) {
1.1000    raeburn  6073:         foreach $envkey (keys(%env)) {
1.54      www      6074:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6075:                my $courseid=$2;
                   6076:                my $roleid=$1.'.'.$2;
1.92      www      6077:                $courseid=~s/^\///;
1.54      www      6078:                my $expiretime=600;
1.620     albertel 6079:                if ($env{'request.role'} eq $roleid) {
1.54      www      6080: 		  $expiretime=120;
                   6081:                }
                   6082: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6083:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6084:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6085: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6086:                }
1.620     albertel 6087:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6088:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6089: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6090:                        &log($env{'user.domain'},$env{'user.name'},
                   6091:                             $env{'user.home'},
1.57      www      6092:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6093:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6094:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6095: 		       return '';
                   6096:                    }
                   6097:                }
1.620     albertel 6098:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6099:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6100: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6101:                        &log($env{'user.domain'},$env{'user.name'},
                   6102:                             $env{'user.home'},
1.57      www      6103:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6104:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6105:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6106: 		       return '';
                   6107:                    }
                   6108:                }
                   6109: 	   }
1.29      www      6110:        }
1.52      www      6111:     }
                   6112:    
                   6113: #
                   6114: # Rest of the restrictions depend on selected course
                   6115: #
                   6116: 
1.620     albertel 6117:     unless ($env{'request.course.id'}) {
1.766     albertel 6118: 	if ($thisallowed eq 'A') {
                   6119: 	    return 'A';
1.814     raeburn  6120:         } elsif ($thisallowed eq 'B') {
                   6121:             return 'B';
1.766     albertel 6122: 	} else {
                   6123: 	    return '1';
                   6124: 	}
1.52      www      6125:     }
1.29      www      6126: 
1.52      www      6127: #
                   6128: # Now user is definitely in a course
                   6129: #
1.53      www      6130: 
                   6131: 
                   6132: # Course preferences
                   6133: 
                   6134:    if ($thisallowed=~/C/) {
1.620     albertel 6135:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6136:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6137:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6138: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6139: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6140: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6141: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6142: 			$env{'request.course.id'});
                   6143: 	   }
1.237     www      6144:            return '';
                   6145:        }
                   6146: 
1.620     albertel 6147:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6148: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6149: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6150: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6151: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6152: 			$env{'request.course.id'});
                   6153: 	   }
1.54      www      6154:            return '';
                   6155:        }
1.53      www      6156:    }
                   6157: 
                   6158: # Resource preferences
                   6159: 
                   6160:    if ($thisallowed=~/R/) {
1.620     albertel 6161:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6162:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6163: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6164: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6165: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6166: 	   }
                   6167: 	   return '';
1.54      www      6168:        }
1.53      www      6169:    }
1.30      www      6170: 
1.246     www      6171: # Restricted by state or randomout?
1.30      www      6172: 
1.52      www      6173:    if ($thisallowed=~/X/) {
1.620     albertel 6174:       if ($env{'acc.randomout'}) {
1.579     albertel 6175: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6176:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6177:             return ''; 
                   6178:          }
1.247     www      6179:       }
                   6180:       if (&condval($statecond)) {
1.52      www      6181: 	 return '2';
                   6182:       } else {
                   6183:          return '';
                   6184:       }
                   6185:    }
1.30      www      6186: 
1.766     albertel 6187:     if ($thisallowed eq 'A') {
                   6188: 	return 'A';
1.814     raeburn  6189:     } elsif ($thisallowed eq 'B') {
                   6190:         return 'B';
1.766     albertel 6191:     }
1.52      www      6192:    return 'F';
1.232     www      6193: }
1.1133    foxr     6194: #
                   6195: #   Removes the versino from a URI and
                   6196: #   splits it in to its filename and path to the filename.
                   6197: #   Seems like File::Basename could have done this more clearly.
                   6198: #   Parameters:
                   6199: #      $uri   - input URI
                   6200: #   Returns:
                   6201: #     Two element list consisting of 
                   6202: #     $pathname  - the URI up to and excluding the trailing /
                   6203: #     $filename  - The part of the URI following the last /
                   6204: #  NOTE:
                   6205: #    Another realization of this is simply:
                   6206: #    use File::Basename;
                   6207: #    ...
                   6208: #    $uri = shift;
                   6209: #    $filename = basename($uri);
                   6210: #    $path     = dirname($uri);
                   6211: #    return ($filename, $path);
                   6212: #
                   6213: #     The implementation below is probably faster however.
                   6214: #
1.710     albertel 6215: sub split_uri_for_cond {
                   6216:     my $uri=&deversion(&declutter(shift));
                   6217:     my @uriparts=split(/\//,$uri);
                   6218:     my $filename=pop(@uriparts);
                   6219:     my $pathname=join('/',@uriparts);
                   6220:     return ($pathname,$filename);
                   6221: }
1.232     www      6222: # --------------------------------------------------- Is a resource on the map?
                   6223: 
                   6224: sub is_on_map {
1.710     albertel 6225:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6226:     #Trying to find the conditional for the file
1.620     albertel 6227:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6228: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6229:     if ($match) {
1.289     bowersj2 6230: 	return (1,$1);
                   6231:     } else {
1.434     www      6232: 	return (0,0);
1.289     bowersj2 6233:     }
1.12      www      6234: }
                   6235: 
1.427     www      6236: # --------------------------------------------------------- Get symb from alias
                   6237: 
                   6238: sub get_symb_from_alias {
                   6239:     my $symb=shift;
                   6240:     my ($map,$resid,$url)=&decode_symb($symb);
                   6241: # Already is a symb
                   6242:     if ($url) { return $symb; }
                   6243: # Must be an alias
                   6244:     my $aliassymb='';
                   6245:     my %bighash;
1.620     albertel 6246:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6247:                             &GDBM_READER(),0640)) {
                   6248:         my $rid=$bighash{'mapalias_'.$symb};
                   6249: 	if ($rid) {
                   6250: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6251: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6252: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6253: 	}
                   6254:         untie %bighash;
                   6255:     }
                   6256:     return $aliassymb;
                   6257: }
                   6258: 
1.12      www      6259: # ----------------------------------------------------------------- Define Role
                   6260: 
                   6261: sub definerole {
                   6262:   if (allowed('mcr','/')) {
                   6263:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6264:     foreach my $role (split(':',$sysrole)) {
                   6265: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6266:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6267:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6268: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6269:                return "refused:s:$crole&$cqual"; 
                   6270:             }
                   6271:         }
1.191     harris41 6272:     }
1.800     albertel 6273:     foreach my $role (split(':',$domrole)) {
                   6274: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6275:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6276:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6277: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6278:                return "refused:d:$crole&$cqual"; 
                   6279:             }
                   6280:         }
1.191     harris41 6281:     }
1.800     albertel 6282:     foreach my $role (split(':',$courole)) {
                   6283: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6284:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6285:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6286: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6287:                return "refused:c:$crole&$cqual"; 
                   6288:             }
                   6289:         }
1.191     harris41 6290:     }
1.620     albertel 6291:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6292:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6293: 	        "rolesdef_$rolename=".
                   6294:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6295:     return reply($command,$env{'user.home'});
1.12      www      6296:   } else {
                   6297:     return 'refused';
                   6298:   }
1.105     harris41 6299: }
                   6300: 
                   6301: # ---------------- Make a metadata query against the network of library servers
                   6302: 
                   6303: sub metadata_query {
1.244     matthew  6304:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6305:     my %rhash;
1.845     albertel 6306:     my %libserv = &all_library();
1.244     matthew  6307:     my @server_list = (defined($server_array) ? @$server_array
                   6308:                                               : keys(%libserv) );
                   6309:     for my $server (@server_list) {
1.118     harris41 6310: 	unless ($custom or $customshow) {
                   6311: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6312: 	    $rhash{$server}=$reply;
                   6313: 	}
                   6314: 	else {
                   6315: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6316: 			     &escape($custom).':'.&escape($customshow),
                   6317: 			     $server);
                   6318: 	    $rhash{$server}=$reply;
                   6319: 	}
1.112     harris41 6320:     }
1.118     harris41 6321:     return \%rhash;
1.240     www      6322: }
                   6323: 
                   6324: # ----------------------------------------- Send log queries and wait for reply
                   6325: 
                   6326: sub log_query {
                   6327:     my ($uname,$udom,$query,%filters)=@_;
                   6328:     my $uhome=&homeserver($uname,$udom);
                   6329:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6330:     my $uhost=&hostname($uhome);
1.800     albertel 6331:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6332:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6333:                        $uhome);
1.479     albertel 6334:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6335:     return get_query_reply($queryid);
                   6336: }
                   6337: 
1.818     raeburn  6338: # -------------------------- Update MySQL table for portfolio file
                   6339: 
                   6340: sub update_portfolio_table {
1.821     raeburn  6341:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6342:     if ($group ne '') {
                   6343:         $file_name =~s /^\Q$group\E//;
                   6344:     }
1.818     raeburn  6345:     my $homeserver = &homeserver($uname,$udom);
                   6346:     my $queryid=
1.821     raeburn  6347:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6348:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6349:     my $reply = &get_query_reply($queryid);
                   6350:     return $reply;
                   6351: }
                   6352: 
1.899     raeburn  6353: # -------------------------- Update MySQL allusers table
                   6354: 
                   6355: sub update_allusers_table {
                   6356:     my ($uname,$udom,$names) = @_;
                   6357:     my $homeserver = &homeserver($uname,$udom);
                   6358:     my $queryid=
                   6359:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6360:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6361:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6362:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6363:                'generation='.&escape($names->{'generation'}).'%%'.
                   6364:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6365:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6366:     return;
1.899     raeburn  6367: }
                   6368: 
1.508     raeburn  6369: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6370: 
                   6371: sub fetch_enrollment_query {
1.511     raeburn  6372:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6373:     my $homeserver;
1.547     raeburn  6374:     my $maxtries = 1;
1.508     raeburn  6375:     if ($context eq 'automated') {
                   6376:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6377:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6378:     } else {
                   6379:         $homeserver = &homeserver($cnum,$dom);
                   6380:     }
1.838     albertel 6381:     my $host=&hostname($homeserver);
1.506     raeburn  6382:     my $cmd = '';
1.1000    raeburn  6383:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6384:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6385:     }
                   6386:     $cmd =~ s/%%$//;
                   6387:     $cmd = &escape($cmd);
                   6388:     my $query = 'fetchenrollment';
1.620     albertel 6389:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6390:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6391:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6392:         return 'error: '.$queryid;
                   6393:     }
1.506     raeburn  6394:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6395:     my $tries = 1;
                   6396:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6397:         $reply = &get_query_reply($queryid);
                   6398:         $tries ++;
                   6399:     }
1.526     raeburn  6400:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6401:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6402:     } else {
1.901     albertel 6403:         my @responses = split(/:/,$reply);
1.515     raeburn  6404:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6405:             foreach my $line (@responses) {
                   6406:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6407:                 $$replyref{$key} = $value;
                   6408:             }
                   6409:         } else {
1.1117    foxr     6410:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6411:             foreach my $line (@responses) {
                   6412:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6413:                 $$replyref{$key} = $value;
                   6414:                 if ($value > 0) {
1.800     albertel 6415:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6416:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6417:                         my $destname = $pathname.'/'.$filename;
                   6418:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6419:                         if ($xml_classlist =~ /^error/) {
                   6420:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6421:                         } else {
1.506     raeburn  6422:                             if ( open(FILE,">$destname") ) {
                   6423:                                 print FILE &unescape($xml_classlist);
                   6424:                                 close(FILE);
1.526     raeburn  6425:                             } else {
                   6426:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6427:                             }
                   6428:                         }
                   6429:                     }
                   6430:                 }
                   6431:             }
                   6432:         }
                   6433:         return 'ok';
                   6434:     }
                   6435:     return 'error';
                   6436: }
                   6437: 
1.242     www      6438: sub get_query_reply {
                   6439:     my $queryid=shift;
1.1117    foxr     6440:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6441:     my $reply='';
                   6442:     for (1..100) {
                   6443: 	sleep 2;
                   6444:         if (-e $replyfile.'.end') {
1.448     albertel 6445: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6446: 		$reply = join('',<$fh>);
                   6447: 		close($fh);
1.240     www      6448: 	   } else { return 'error: reply_file_error'; }
1.242     www      6449:            return &unescape($reply);
                   6450: 	}
1.240     www      6451:     }
1.242     www      6452:     return 'timeout:'.$queryid;
1.240     www      6453: }
                   6454: 
                   6455: sub courselog_query {
1.241     www      6456: #
                   6457: # possible filters:
                   6458: # url: url or symb
                   6459: # username
                   6460: # domain
                   6461: # action: view, submit, grade
                   6462: # start: timestamp
                   6463: # end: timestamp
                   6464: #
1.240     www      6465:     my (%filters)=@_;
1.620     albertel 6466:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6467:     if ($filters{'url'}) {
                   6468: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6469:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6470:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6471:     }
1.620     albertel 6472:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6473:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6474:     return &log_query($cname,$cdom,'courselog',%filters);
                   6475: }
                   6476: 
                   6477: sub userlog_query {
1.858     raeburn  6478: #
                   6479: # possible filters:
                   6480: # action: log check role
                   6481: # start: timestamp
                   6482: # end: timestamp
                   6483: #
1.240     www      6484:     my ($uname,$udom,%filters)=@_;
                   6485:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6486: }
                   6487: 
1.506     raeburn  6488: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6489: 
                   6490: sub auto_run {
1.508     raeburn  6491:     my ($cnum,$cdom) = @_;
1.876     raeburn  6492:     my $response = 0;
                   6493:     my $settings;
                   6494:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6495:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6496:         $settings = $domconfig{'autoenroll'};
                   6497:         if ($settings->{'run'} eq '1') {
                   6498:             $response = 1;
                   6499:         }
                   6500:     } else {
1.934     raeburn  6501:         my $homeserver;
                   6502:         if (&is_course($cdom,$cnum)) {
                   6503:             $homeserver = &homeserver($cnum,$cdom);
                   6504:         } else {
                   6505:             $homeserver = &domain($cdom,'primary');
                   6506:         }
                   6507:         if ($homeserver ne 'no_host') {
                   6508:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6509:         }
1.876     raeburn  6510:     }
1.506     raeburn  6511:     return $response;
                   6512: }
1.776     albertel 6513: 
1.506     raeburn  6514: sub auto_get_sections {
1.508     raeburn  6515:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6516:     my $homeserver;
                   6517:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6518:         $homeserver = &homeserver($cnum,$cdom);
                   6519:     }
                   6520:     if (!defined($homeserver)) { 
                   6521:         if ($cdom =~ /^$match_domain$/) {
                   6522:             $homeserver = &domain($cdom,'primary');
                   6523:         }
                   6524:     }
                   6525:     my @secs;
                   6526:     if (defined($homeserver)) {
                   6527:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6528:         unless ($response eq 'refused') {
                   6529:             @secs = split(/:/,$response);
                   6530:         }
1.506     raeburn  6531:     }
                   6532:     return @secs;
                   6533: }
1.776     albertel 6534: 
1.506     raeburn  6535: sub auto_new_course {
1.1099    raeburn  6536:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6537:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6538:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6539:     return $response;
                   6540: }
1.776     albertel 6541: 
1.506     raeburn  6542: sub auto_validate_courseID {
1.508     raeburn  6543:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6544:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6545:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6546:     return $response;
                   6547: }
1.776     albertel 6548: 
1.1007    raeburn  6549: sub auto_validate_instcode {
1.1020    raeburn  6550:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6551:     my ($homeserver,$response);
                   6552:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6553:         $homeserver = &homeserver($cnum,$cdom);
                   6554:     }
                   6555:     if (!defined($homeserver)) {
                   6556:         if ($cdom =~ /^$match_domain$/) {
                   6557:             $homeserver = &domain($cdom,'primary');
                   6558:         }
                   6559:     }
1.1065    raeburn  6560:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6561:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6562:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6563:     return ($outcome,$description);
1.1007    raeburn  6564: }
                   6565: 
1.506     raeburn  6566: sub auto_create_password {
1.873     raeburn  6567:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6568:     my ($homeserver,$response);
1.506     raeburn  6569:     my $create_passwd = 0;
                   6570:     my $authchk = '';
1.873     raeburn  6571:     if ($udom =~ /^$match_domain$/) {
                   6572:         $homeserver = &domain($udom,'primary');
                   6573:     }
                   6574:     if ($homeserver eq '') {
                   6575:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6576:             $homeserver = &homeserver($cnum,$cdom);
                   6577:         }
                   6578:     }
                   6579:     if ($homeserver eq '') {
                   6580:         $authchk = 'nodomain';
1.506     raeburn  6581:     } else {
1.873     raeburn  6582:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6583:         if ($response eq 'refused') {
                   6584:             $authchk = 'refused';
                   6585:         } else {
1.901     albertel 6586:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6587:         }
1.506     raeburn  6588:     }
                   6589:     return ($authparam,$create_passwd,$authchk);
                   6590: }
                   6591: 
1.706     raeburn  6592: sub auto_photo_permission {
                   6593:     my ($cnum,$cdom,$students) = @_;
                   6594:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6595:     my ($outcome,$perm_reqd,$conditions) = 
                   6596: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6597:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6598: 	return (undef,undef);
                   6599:     }
1.706     raeburn  6600:     return ($outcome,$perm_reqd,$conditions);
                   6601: }
                   6602: 
                   6603: sub auto_checkphotos {
                   6604:     my ($uname,$udom,$pid) = @_;
                   6605:     my $homeserver = &homeserver($uname,$udom);
                   6606:     my ($result,$resulttype);
                   6607:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6608: 				   &escape($uname).':'.&escape($pid),
                   6609: 				   $homeserver));
1.709     albertel 6610:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6611: 	return (undef,undef);
                   6612:     }
1.706     raeburn  6613:     if ($outcome) {
                   6614:         ($result,$resulttype) = split(/:/,$outcome);
                   6615:     } 
                   6616:     return ($result,$resulttype);
                   6617: }
                   6618: 
                   6619: sub auto_photochoice {
                   6620:     my ($cnum,$cdom) = @_;
                   6621:     my $homeserver = &homeserver($cnum,$cdom);
                   6622:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6623: 						       &escape($cdom),
                   6624: 						       $homeserver)));
1.709     albertel 6625:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6626: 	return (undef,undef);
                   6627:     }
1.706     raeburn  6628:     return ($update,$comment);
                   6629: }
                   6630: 
                   6631: sub auto_photoupdate {
                   6632:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6633:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6634:     my $host=&hostname($homeserver);
1.706     raeburn  6635:     my $cmd = '';
                   6636:     my $maxtries = 1;
1.800     albertel 6637:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6638:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6639:     }
                   6640:     $cmd =~ s/%%$//;
                   6641:     $cmd = &escape($cmd);
                   6642:     my $query = 'institutionalphotos';
                   6643:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   6644:     unless ($queryid=~/^\Q$host\E\_/) {
                   6645:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   6646:         return 'error: '.$queryid;
                   6647:     }
                   6648:     my $reply = &get_query_reply($queryid);
                   6649:     my $tries = 1;
                   6650:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6651:         $reply = &get_query_reply($queryid);
                   6652:         $tries ++;
                   6653:     }
                   6654:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   6655:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   6656:     } else {
                   6657:         my @responses = split(/:/,$reply);
                   6658:         my $outcome = shift(@responses); 
                   6659:         foreach my $item (@responses) {
                   6660:             my ($key,$value) = split(/=/,$item);
                   6661:             $$photo{$key} = $value;
                   6662:         }
                   6663:         return $outcome;
                   6664:     }
                   6665:     return 'error';
                   6666: }
                   6667: 
1.521     raeburn  6668: sub auto_instcode_format {
1.793     albertel 6669:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   6670: 	$cat_order) = @_;
1.521     raeburn  6671:     my $courses = '';
1.772     raeburn  6672:     my @homeservers;
1.521     raeburn  6673:     if ($caller eq 'global') {
1.841     albertel 6674: 	my %servers = &get_servers($codedom,'library');
                   6675: 	foreach my $tryserver (keys(%servers)) {
                   6676: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6677: 		push(@homeservers,$tryserver);
                   6678: 	    }
1.584     raeburn  6679:         }
1.1022    raeburn  6680:     } elsif ($caller eq 'requests') {
                   6681:         if ($codedom =~ /^$match_domain$/) {
                   6682:             my $chome = &domain($codedom,'primary');
                   6683:             unless ($chome eq 'no_host') {
                   6684:                 push(@homeservers,$chome);
                   6685:             }
                   6686:         }
1.521     raeburn  6687:     } else {
1.772     raeburn  6688:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  6689:     }
1.793     albertel 6690:     foreach my $code (keys(%{$instcodes})) {
                   6691:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  6692:     }
                   6693:     chop($courses);
1.772     raeburn  6694:     my $ok_response = 0;
                   6695:     my $response;
                   6696:     while (@homeservers > 0 && $ok_response == 0) {
                   6697:         my $server = shift(@homeservers); 
                   6698:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   6699:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   6700:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 6701: 		split(/:/,$response);
1.772     raeburn  6702:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   6703:             push(@{$codetitles},&str2array($codetitles_str));
                   6704:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   6705:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   6706:             $ok_response = 1;
                   6707:         }
                   6708:     }
                   6709:     if ($ok_response) {
1.521     raeburn  6710:         return 'ok';
1.772     raeburn  6711:     } else {
                   6712:         return $response;
1.521     raeburn  6713:     }
                   6714: }
                   6715: 
1.792     raeburn  6716: sub auto_instcode_defaults {
                   6717:     my ($domain,$returnhash,$code_order) = @_;
                   6718:     my @homeservers;
1.841     albertel 6719: 
                   6720:     my %servers = &get_servers($domain,'library');
                   6721:     foreach my $tryserver (keys(%servers)) {
                   6722: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6723: 	    push(@homeservers,$tryserver);
                   6724: 	}
1.792     raeburn  6725:     }
1.841     albertel 6726: 
1.792     raeburn  6727:     my $response;
1.841     albertel 6728:     foreach my $server (@homeservers) {
1.792     raeburn  6729:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 6730:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   6731: 	
                   6732: 	foreach my $pair (split(/\&/,$response)) {
                   6733: 	    my ($name,$value)=split(/\=/,$pair);
                   6734: 	    if ($name eq 'code_order') {
                   6735: 		@{$code_order} = split(/\&/,&unescape($value));
                   6736: 	    } else {
                   6737: 		$returnhash->{&unescape($name)}=&unescape($value);
                   6738: 	    }
                   6739: 	}
                   6740: 	return 'ok';
1.792     raeburn  6741:     }
1.841     albertel 6742: 
                   6743:     return $response;
1.1003    raeburn  6744: }
                   6745: 
                   6746: sub auto_possible_instcodes {
1.1007    raeburn  6747:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   6748:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   6749:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   6750:         return;
                   6751:     }
1.1003    raeburn  6752:     my (@homeservers,$uhome);
                   6753:     if (defined(&domain($domain,'primary'))) {
                   6754:         $uhome=&domain($domain,'primary');
                   6755:         push(@homeservers,&domain($domain,'primary'));
                   6756:     } else {
                   6757:         my %servers = &get_servers($domain,'library');
                   6758:         foreach my $tryserver (keys(%servers)) {
                   6759:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   6760:                 push(@homeservers,$tryserver);
                   6761:             }
                   6762:         }
                   6763:     }
                   6764:     my $response;
                   6765:     foreach my $server (@homeservers) {
                   6766:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   6767:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  6768:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   6769:             split(':',$response);
                   6770:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   6771:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  6772:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  6773:             my ($name,$value)=split('=',$item);
                   6774:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6775:         }
                   6776:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  6777:             my ($name,$value)=split('=',$item);
                   6778:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  6779:         }
                   6780:         return 'ok';
                   6781:     }
                   6782:     return $response;
                   6783: }
1.792     raeburn  6784: 
1.1010    raeburn  6785: sub auto_courserequest_checks {
                   6786:     my ($dom) = @_;
1.1020    raeburn  6787:     my ($homeserver,%validations);
                   6788:     if ($dom =~ /^$match_domain$/) {
                   6789:         $homeserver = &domain($dom,'primary');
                   6790:     }
                   6791:     unless ($homeserver eq 'no_host') {
                   6792:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   6793:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   6794:             my @items = split(/&/,$response);
                   6795:             foreach my $item (@items) {
                   6796:                 my ($key,$value) = split('=',$item);
                   6797:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   6798:             }
                   6799:         }
                   6800:     }
1.1010    raeburn  6801:     return %validations; 
                   6802: }
                   6803: 
1.1020    raeburn  6804: sub auto_courserequest_validation {
                   6805:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   6806:     my ($homeserver,$response);
                   6807:     if ($dom =~ /^$match_domain$/) {
                   6808:         $homeserver = &domain($dom,'primary');
                   6809:     }
                   6810:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  6811:           
1.1020    raeburn  6812:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  6813:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  6814:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   6815:                                     $homeserver));
                   6816:     }
                   6817:     return $response;
                   6818: }
                   6819: 
1.777     albertel 6820: sub auto_validate_class_sec {
1.918     raeburn  6821:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  6822:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  6823:     my $ownerlist;
                   6824:     if (ref($owners) eq 'ARRAY') {
                   6825:         $ownerlist = join(',',@{$owners});
                   6826:     } else {
                   6827:         $ownerlist = $owners;
                   6828:     }
1.773     raeburn  6829:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  6830:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  6831:     return $response;
                   6832: }
                   6833: 
1.679     raeburn  6834: # ------------------------------------------------------- Course Group routines
                   6835: 
                   6836: sub get_coursegroups {
1.809     raeburn  6837:     my ($cdom,$cnum,$group,$namespace) = @_;
                   6838:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  6839: }
                   6840: 
1.679     raeburn  6841: sub modify_coursegroup {
                   6842:     my ($cdom,$cnum,$groupsettings) = @_;
                   6843:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   6844: }
                   6845: 
1.809     raeburn  6846: sub toggle_coursegroup_status {
                   6847:     my ($cdom,$cnum,$group,$action) = @_;
                   6848:     my ($from_namespace,$to_namespace);
                   6849:     if ($action eq 'delete') {
                   6850:         $from_namespace = 'coursegroups';
                   6851:         $to_namespace = 'deleted_groups';
                   6852:     } else {
                   6853:         $from_namespace = 'deleted_groups';
                   6854:         $to_namespace = 'coursegroups';
                   6855:     }
                   6856:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  6857:     if (my $tmp = &error(%curr_group)) {
                   6858:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   6859:         return ('read error',$tmp);
                   6860:     } else {
                   6861:         my %savedsettings = %curr_group; 
1.809     raeburn  6862:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  6863:         my $deloutcome;
                   6864:         if ($result eq 'ok') {
1.809     raeburn  6865:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  6866:         } else {
                   6867:             return ('write error',$result);
                   6868:         }
                   6869:         if ($deloutcome eq 'ok') {
                   6870:             return 'ok';
                   6871:         } else {
                   6872:             return ('delete error',$deloutcome);
                   6873:         }
                   6874:     }
                   6875: }
                   6876: 
1.679     raeburn  6877: sub modify_group_roles {
1.957     raeburn  6878:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  6879:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   6880:     my $role = 'gr/'.&escape($userprivs);
                   6881:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  6882:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  6883:     if ($result eq 'ok') {
                   6884:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   6885:     }
1.679     raeburn  6886:     return $result;
                   6887: }
                   6888: 
                   6889: sub modify_coursegroup_membership {
                   6890:     my ($cdom,$cnum,$membership) = @_;
                   6891:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   6892:     return $result;
                   6893: }
                   6894: 
1.682     raeburn  6895: sub get_active_groups {
                   6896:     my ($udom,$uname,$cdom,$cnum) = @_;
                   6897:     my $now = time;
                   6898:     my %groups = ();
                   6899:     foreach my $key (keys(%env)) {
1.811     albertel 6900:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  6901:             my ($start,$end) = split(/\./,$env{$key});
                   6902:             if (($end!=0) && ($end<$now)) { next; }
                   6903:             if (($start!=0) && ($start>$now)) { next; }
                   6904:             if ($1 eq $cdom && $2 eq $cnum) {
                   6905:                 $groups{$3} = $env{$key} ;
                   6906:             }
                   6907:         }
                   6908:     }
                   6909:     return %groups;
                   6910: }
                   6911: 
1.683     raeburn  6912: sub get_group_membership {
                   6913:     my ($cdom,$cnum,$group) = @_;
                   6914:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   6915: }
                   6916: 
                   6917: sub get_users_groups {
                   6918:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  6919:     my @usersgroups;
1.683     raeburn  6920:     my $cachetime=1800;
                   6921: 
                   6922:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  6923:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   6924:     if (defined($cached)) {
1.734     albertel 6925:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  6926:     } else {  
                   6927:         $grouplist = '';
1.816     raeburn  6928:         my $courseurl = &courseid_to_courseurl($courseid);
1.1086    raeburn  6929:         my $extra = &freeze_escape({'skipcheck' => 1});
                   6930:         my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817     raeburn  6931:         my $access_end = $env{'course.'.$courseid.
                   6932:                               '.default_enrollment_end_date'};
                   6933:         my $now = time;
                   6934:         foreach my $key (keys(%roleshash)) {
                   6935:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   6936:                 my $group = $1;
                   6937:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   6938:                     my $start = $2;
                   6939:                     my $end = $1;
                   6940:                     if ($start == -1) { next; } # deleted from group
                   6941:                     if (($start!=0) && ($start>$now)) { next; }
                   6942:                     if (($end!=0) && ($end<$now)) {
                   6943:                         if ($access_end && $access_end < $now) {
                   6944:                             if ($access_end - $end < 86400) {
                   6945:                                 push(@usersgroups,$group);
1.733     raeburn  6946:                             }
                   6947:                         }
1.817     raeburn  6948:                         next;
1.733     raeburn  6949:                     }
1.817     raeburn  6950:                     push(@usersgroups,$group);
1.683     raeburn  6951:                 }
                   6952:             }
                   6953:         }
1.817     raeburn  6954:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   6955:         $grouplist = join(':',@usersgroups);
                   6956:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  6957:     }
1.733     raeburn  6958:     return @usersgroups;
1.683     raeburn  6959: }
                   6960: 
                   6961: sub devalidate_getgroups_cache {
                   6962:     my ($udom,$uname,$cdom,$cnum)=@_;
                   6963:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 6964: 
1.683     raeburn  6965:     my $hashid="$udom:$uname:$courseid";
                   6966:     &devalidate_cache_new('getgroups',$hashid);
                   6967: }
                   6968: 
1.12      www      6969: # ------------------------------------------------------------------ Plain Text
                   6970: 
                   6971: sub plaintext {
1.988     raeburn  6972:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  6973:     if ($short =~ m{^cr/}) {
1.758     albertel 6974: 	return (split('/',$short))[-1];
                   6975:     }
1.742     raeburn  6976:     if (!defined($cid)) {
                   6977:         $cid = $env{'request.course.id'};
                   6978:     }
                   6979:     my %rolenames = (
1.1008    raeburn  6980:                       Course    => 'std',
                   6981:                       Community => 'alt1',
1.742     raeburn  6982:                     );
1.1037    raeburn  6983:     if ($cid ne '') {
                   6984:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   6985:             unless ($forcedefault) {
                   6986:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   6987:                 &Apache::lonlocal::mt_escape(\$roletext);
                   6988:                 return &Apache::lonlocal::mt($roletext);
                   6989:             }
                   6990:         }
                   6991:     }
                   6992:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   6993:         (defined($rolenames{$type})) && 
                   6994:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  6995:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  6996:     } elsif ($cid ne '') {
                   6997:         my $crstype = $env{'course.'.$cid.'.type'};
                   6998:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   6999:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7000:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7001:         }
1.742     raeburn  7002:     }
1.1037    raeburn  7003:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7004: }
                   7005: 
                   7006: # ----------------------------------------------------------------- Assign Role
                   7007: 
                   7008: sub assignrole {
1.957     raeburn  7009:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7010:         $context)=@_;
1.21      www      7011:     my $mrole;
                   7012:     if ($role =~ /^cr\//) {
1.393     www      7013:         my $cwosec=$url;
1.811     albertel 7014:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7015: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7016:            my $refused = 1;
                   7017:            if ($context eq 'requestcourses') {
                   7018:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7019:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7020:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7021:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7022:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7023:                            if ($crsenv{'internal.courseowner'} eq
                   7024:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7025:                                $refused = '';
                   7026:                            }
                   7027:                        }
                   7028:                    }
                   7029:                }
                   7030:            }
                   7031:            if ($refused) {
                   7032:                &logthis('Refused custom assignrole: '.
                   7033:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7034:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7035:                return 'refused';
                   7036:            }
1.104     www      7037:         }
1.21      www      7038:         $mrole='cr';
1.678     raeburn  7039:     } elsif ($role =~ /^gr\//) {
                   7040:         my $cwogrp=$url;
1.811     albertel 7041:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7042:         unless (&allowed('mdg',$cwogrp)) {
                   7043:             &logthis('Refused group assignrole: '.
                   7044:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7045:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7046:             return 'refused';
                   7047:         }
                   7048:         $mrole='gr';
1.21      www      7049:     } else {
1.82      www      7050:         my $cwosec=$url;
1.811     albertel 7051:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7052:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7053:             my $refused;
                   7054:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7055:                 if (!(&allowed('c'.$role,$url))) {
                   7056:                     $refused = 1;
                   7057:                 }
                   7058:             } else {
                   7059:                 $refused = 1;
                   7060:             }
1.947     raeburn  7061:             if ($refused) {
1.1045    raeburn  7062:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7063:                 if (!$selfenroll && $context eq 'course') {
                   7064:                     my %crsenv;
                   7065:                     if ($role eq 'cc' || $role eq 'co') {
                   7066:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7067:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7068:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7069:                                 if ($crsenv{'internal.courseowner'} eq 
                   7070:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7071:                                     $refused = '';
                   7072:                                 }
                   7073:                             }
                   7074:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7075:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7076:                                 if ($crsenv{'internal.courseowner'} eq 
                   7077:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7078:                                     $refused = '';
                   7079:                                 }
                   7080:                             }
                   7081:                         }
                   7082:                     }
                   7083:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7084:                     $refused = '';
1.1017    raeburn  7085:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7086:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7087:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7088:                         my $wrongcc;
                   7089:                         if ($cnum =~ /^$match_community$/) {
                   7090:                             $wrongcc = 1 if ($role eq 'cc');
                   7091:                         } else {
                   7092:                             $wrongcc = 1 if ($role eq 'co');
                   7093:                         }
                   7094:                         unless ($wrongcc) {
                   7095:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7096:                             if ($crsenv{'internal.courseowner'} eq 
                   7097:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7098:                                 $refused = '';
                   7099:                             }
1.1017    raeburn  7100:                         }
                   7101:                     }
                   7102:                 }
                   7103:                 if ($refused) {
1.947     raeburn  7104:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7105:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7106: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7107:                     return 'refused';
                   7108:                 }
1.932     raeburn  7109:             }
1.1131    raeburn  7110:         } elsif ($role eq 'au') {
                   7111:             if ($url ne '/'.$udom.'/') {
                   7112:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7113:                          ' to assign author role for '.$uname.':'.$udom.
                   7114:                          ' in domain: '.$url.' refused (wrong domain).');
                   7115:                 return 'refused';
                   7116:             }
1.104     www      7117:         }
1.21      www      7118:         $mrole=$role;
                   7119:     }
1.620     albertel 7120:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7121:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7122:     if ($end) { $command.='_'.$end; }
1.21      www      7123:     if ($start) {
                   7124: 	if ($end) { 
1.81      www      7125:            $command.='_'.$start; 
1.21      www      7126:         } else {
1.81      www      7127:            $command.='_0_'.$start;
1.21      www      7128:         }
                   7129:     }
1.739     raeburn  7130:     my $origstart = $start;
                   7131:     my $origend = $end;
1.957     raeburn  7132:     my $delflag;
1.357     www      7133: # actually delete
                   7134:     if ($deleteflag) {
1.373     www      7135: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7136: # modify command to delete the role
1.620     albertel 7137:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7138:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7139: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7140: # set start and finish to negative values for userrolelog
                   7141:            $start=-1;
                   7142:            $end=-1;
1.957     raeburn  7143:            $delflag = 1;
1.357     www      7144:         }
                   7145:     }
                   7146: # send command
1.349     www      7147:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7148: # log new user role if status is ok
1.349     www      7149:     if ($answer eq 'ok') {
1.663     raeburn  7150: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7151: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7152:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7153:         unless ($role =~ /^gr/) {
                   7154:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7155:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7156:         }
1.1053    raeburn  7157:         if ($role eq 'cc') {
                   7158:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7159:         }
1.349     www      7160:     }
                   7161:     return $answer;
1.169     harris41 7162: }
                   7163: 
1.1053    raeburn  7164: sub autoupdate_coowners {
                   7165:     my ($url,$end,$start,$uname,$udom) = @_;
                   7166:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7167:     if (($cdom ne '') && ($cnum ne '')) {
                   7168:         my $now = time;
                   7169:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7170:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7171:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7172:             my $instcode = $coursehash{'internal.coursecode'};
                   7173:             if ($instcode ne '') {
1.1056    raeburn  7174:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7175:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7176:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7177:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7178:                         if ($result eq 'valid') {
                   7179:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7180:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7181:                                     push(@newcoowners,$coowner);
                   7182:                                 }
                   7183:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7184:                                     push(@newcoowners,$uname.':'.$udom);
                   7185:                                 }
                   7186:                                 @newcoowners = sort(@newcoowners);
                   7187:                             } else {
                   7188:                                 push(@newcoowners,$uname.':'.$udom);
                   7189:                             }
                   7190:                         } else {
                   7191:                             if ($coursehash{'internal.co-owners'}) {
                   7192:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7193:                                     unless ($coowner eq $uname.':'.$udom) {
                   7194:                                         push(@newcoowners,$coowner);
                   7195:                                     }
                   7196:                                 }
                   7197:                                 unless (@newcoowners > 0) {
                   7198:                                     $delcoowners = 1;
                   7199:                                     $coowners = '';
                   7200:                                 }
                   7201:                             }
                   7202:                         }
                   7203:                         if (@newcoowners || $delcoowners) {
                   7204:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7205:                                             $delcoowners,@newcoowners);
                   7206:                         }
                   7207:                     }
                   7208:                 }
                   7209:             }
                   7210:         }
                   7211:     }
                   7212: }
                   7213: 
                   7214: sub store_coowners {
                   7215:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7216:     my $cid = $cdom.'_'.$cnum;
                   7217:     my ($coowners,$delresult,$putresult);
                   7218:     if (@newcoowners) {
                   7219:         $coowners = join(',',@newcoowners);
                   7220:         my %coownershash = (
                   7221:                             'internal.co-owners' => $coowners,
                   7222:                            );
                   7223:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7224:         if ($putresult eq 'ok') {
                   7225:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7226:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7227:             }
                   7228:         }
                   7229:     }
                   7230:     if ($delcoowners) {
                   7231:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7232:         if ($delresult eq 'ok') {
                   7233:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7234:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7235:             }
                   7236:         }
                   7237:     }
                   7238:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7239:         my %crsinfo =
                   7240:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7241:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7242:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7243:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7244:         }
                   7245:     }
                   7246: }
                   7247: 
1.169     harris41 7248: # -------------------------------------------------- Modify user authentication
1.197     www      7249: # Overrides without validation
                   7250: 
1.169     harris41 7251: sub modifyuserauth {
                   7252:     my ($udom,$uname,$umode,$upass)=@_;
                   7253:     my $uhome=&homeserver($uname,$udom);
1.197     www      7254:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7255:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7256:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7257:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7258:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7259: 		     &escape($upass),$uhome);
1.620     albertel 7260:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7261:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7262:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7263:     &log($udom,,$uname,$uhome,
1.620     albertel 7264:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7265:                                      $env{'user.name'}.', '.$umode.
1.197     www      7266:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7267:     unless ($reply eq 'ok') {
1.197     www      7268:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7269: 	return 'error: '.$reply;
                   7270:     }   
1.170     harris41 7271:     return 'ok';
1.80      www      7272: }
                   7273: 
1.81      www      7274: # --------------------------------------------------------------- Modify a user
1.80      www      7275: 
1.81      www      7276: sub modifyuser {
1.206     matthew  7277:     my ($udom,    $uname, $uid,
                   7278:         $umode,   $upass, $first,
                   7279:         $middle,  $last,  $gene,
1.1058    raeburn  7280:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7281:     $udom= &LONCAPA::clean_domain($udom);
                   7282:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7283:     my $showcandelete = 'none';
                   7284:     if (ref($candelete) eq 'ARRAY') {
                   7285:         if (@{$candelete} > 0) {
                   7286:             $showcandelete = join(', ',@{$candelete});
                   7287:         }
                   7288:     }
1.81      www      7289:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7290:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7291: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7292:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7293:                                      ' desiredhome not specified'). 
1.620     albertel 7294:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7295:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7296:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7297:     my $newuser;
                   7298:     if ($uhome eq 'no_host') {
                   7299:         $newuser = 1;
                   7300:     }
1.80      www      7301: # ----------------------------------------------------------------- Create User
1.406     albertel 7302:     if (($uhome eq 'no_host') && 
                   7303: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7304:         my $unhome='';
1.844     albertel 7305:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7306:             $unhome = $desiredhome;
1.620     albertel 7307: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7308: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7309:         } else { # load balancing routine for determining $unhome
1.81      www      7310:             my $loadm=10000000;
1.841     albertel 7311: 	    my %servers = &get_servers($udom,'library');
                   7312: 	    foreach my $tryserver (keys(%servers)) {
                   7313: 		my $answer=reply('load',$tryserver);
                   7314: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7315: 		    $loadm=$answer;
                   7316: 		    $unhome=$tryserver;
                   7317: 		}
1.80      www      7318: 	    }
                   7319:         }
                   7320:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7321: 	    return 'error: unable to find a home server for '.$uname.
                   7322:                    ' in domain '.$udom;
1.80      www      7323:         }
                   7324:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7325:                          &escape($upass),$unhome);
                   7326: 	unless ($reply eq 'ok') {
                   7327:             return 'error: '.$reply;
                   7328:         }   
1.230     stredwic 7329:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7330:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7331: 	    return 'error: unable verify users home machine.';
1.80      www      7332:         }
1.209     matthew  7333:     }   # End of creation of new user
1.80      www      7334: # ---------------------------------------------------------------------- Add ID
                   7335:     if ($uid) {
                   7336:        $uid=~tr/A-Z/a-z/;
                   7337:        my %uidhash=&idrget($udom,$uname);
1.196     www      7338:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7339:          && (!$forceid)) {
1.80      www      7340: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7341: 	      return 'error: user id "'.$uid.'" does not match '.
                   7342:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7343:           }
                   7344:        } else {
                   7345: 	  &idput($udom,($uname => $uid));
                   7346:        }
                   7347:     }
                   7348: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7349:     my @tmp=&get('environment',
1.899     raeburn  7350: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7351:                     'permanentemail','inststatus'],
1.134     albertel 7352: 		   $udom,$uname);
1.1075    raeburn  7353:     my (%names,%oldnames);
1.313     matthew  7354:     if ($tmp[0] =~ m/^error:.*/) { 
                   7355:         %names=(); 
                   7356:     } else {
                   7357:         %names = @tmp;
1.1075    raeburn  7358:         %oldnames = %names;
1.313     matthew  7359:     }
1.388     www      7360: #
1.1058    raeburn  7361: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7362: # of users did not contain them), do not overwrite existing values
                   7363: # unless field is in $candelete array ref.  
                   7364: #
                   7365: 
                   7366:     my @fields = ('firstname','middlename','lastname','generation',
                   7367:                   'permanentemail','id');
                   7368:     my %newvalues;
                   7369:     if (ref($candelete) eq 'ARRAY') {
                   7370:         foreach my $field (@fields) {
                   7371:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7372:                 if ($field eq 'firstname') {
                   7373:                     $names{$field} = $first;
                   7374:                 } elsif ($field eq 'middlename') {
                   7375:                     $names{$field} = $middle;
                   7376:                 } elsif ($field eq 'lastname') {
                   7377:                     $names{$field} = $last;
                   7378:                 } elsif ($field eq 'generation') { 
                   7379:                     $names{$field} = $gene;
                   7380:                 } elsif ($field eq 'permanentemail') {
                   7381:                     $names{$field} = $email;
                   7382:                 } elsif ($field eq 'id') {
                   7383:                     $names{$field}  = $uid;
                   7384:                 }
                   7385:             }
                   7386:         }
                   7387:     }
1.388     www      7388:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7389:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7390:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7391:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7392:     if ($email) {
                   7393:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7394:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7395:     }
1.899     raeburn  7396:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7397:     if (defined($inststatus)) {
                   7398:         $names{'inststatus'} = '';
                   7399:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7400:         if (ref($usertypes) eq 'HASH') {
                   7401:             my @okstatuses; 
                   7402:             foreach my $item (split(/:/,$inststatus)) {
                   7403:                 if (defined($usertypes->{$item})) {
                   7404:                     push(@okstatuses,$item);  
                   7405:                 }
                   7406:             }
                   7407:             if (@okstatuses) {
                   7408:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7409:             }
                   7410:         }
                   7411:     }
1.1075    raeburn  7412:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7413:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7414:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7415:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7416:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7417:     } else {
                   7418:         $logmsg .= ' during self creation';
                   7419:     }
1.1075    raeburn  7420:     my $changed;
                   7421:     if ($newuser) {
                   7422:         $changed = 1;
                   7423:     } else {
                   7424:         foreach my $field (@fields) {
                   7425:             if ($names{$field} ne $oldnames{$field}) {
                   7426:                 $changed = 1;
                   7427:                 last;
                   7428:             }
                   7429:         }
                   7430:     }
                   7431:     unless ($changed) {
                   7432:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7433:         &logthis($logmsg);
                   7434:         return 'ok';
                   7435:     }
                   7436:     my $reply = &put('environment', \%names, $udom,$uname);
                   7437:     if ($reply ne 'ok') { 
                   7438:         return 'error: '.$reply;
                   7439:     }
1.1087    raeburn  7440:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7441:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7442:     }
1.1075    raeburn  7443:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7444:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7445:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7446:     &logthis($logmsg);
1.134     albertel 7447:     return 'ok';
1.80      www      7448: }
                   7449: 
1.81      www      7450: # -------------------------------------------------------------- Modify student
1.80      www      7451: 
1.81      www      7452: sub modifystudent {
                   7453:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7454:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7455:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7456:     if (!$cid) {
1.620     albertel 7457: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7458: 	    return 'not_in_class';
                   7459: 	}
1.80      www      7460:     }
                   7461: # --------------------------------------------------------------- Make the user
1.81      www      7462:     my $reply=&modifyuser
1.209     matthew  7463: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7464:          $desiredhome,$email,$inststatus);
1.80      www      7465:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7466:     # This will cause &modify_student_enrollment to get the uid from the
                   7467:     # students environment
                   7468:     $uid = undef if (!$forceid);
1.455     albertel 7469:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7470: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7471:     return $reply;
                   7472: }
                   7473: 
                   7474: sub modify_student_enrollment {
1.957     raeburn  7475:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7476:     my ($cdom,$cnum,$chome);
                   7477:     if (!$cid) {
1.620     albertel 7478: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7479: 	    return 'not_in_class';
                   7480: 	}
1.620     albertel 7481: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7482: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7483:     } else {
                   7484: 	($cdom,$cnum)=split(/_/,$cid);
                   7485:     }
1.620     albertel 7486:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7487:     if (!$chome) {
1.457     raeburn  7488: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7489:     }
1.455     albertel 7490:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7491:     # Make sure the user exists
1.81      www      7492:     my $uhome=&homeserver($uname,$udom);
                   7493:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7494: 	return 'error: no such user';
                   7495:     }
1.297     matthew  7496:     # Get student data if we were not given enough information
                   7497:     if (!defined($first)  || $first  eq '' || 
                   7498:         !defined($last)   || $last   eq '' || 
                   7499:         !defined($uid)    || $uid    eq '' || 
                   7500:         !defined($middle) || $middle eq '' || 
                   7501:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7502:         # They did not supply us with enough data to enroll the student, so
                   7503:         # we need to pick up more information.
1.297     matthew  7504:         my %tmp = &get('environment',
1.294     matthew  7505:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7506:                        ,$udom,$uname);
                   7507: 
1.800     albertel 7508:         #foreach my $key (keys(%tmp)) {
                   7509:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7510:         #}
1.294     matthew  7511:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7512:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7513:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7514:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7515:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7516:     }
1.556     albertel 7517:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487     albertel 7518:     my $reply=cput('classlist',
                   7519: 		   {"$uname:$udom" => 
1.515     raeburn  7520: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7521: 		   $cdom,$cnum);
1.81      www      7522:     unless (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7523: 	return 'error: '.$reply;
1.652     albertel 7524:     } else {
                   7525: 	&devalidate_getsection_cache($udom,$uname,$cid);
1.81      www      7526:     }
1.297     matthew  7527:     # Add student role to user
1.83      www      7528:     my $uurl='/'.$cid;
1.81      www      7529:     $uurl=~s/\_/\//g;
                   7530:     if ($usec) {
                   7531: 	$uurl.='/'.$usec;
                   7532:     }
1.957     raeburn  7533:     return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21      www      7534: }
                   7535: 
1.556     albertel 7536: sub format_name {
                   7537:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7538:     my $name;
                   7539:     if ($first ne 'lastname') {
                   7540: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7541:     } else {
                   7542: 	if ($lastname=~/\S/) {
                   7543: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7544: 	    $name=~s/\s+,/,/;
                   7545: 	} else {
                   7546: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7547: 	}
                   7548:     }
                   7549:     $name=~s/^\s+//;
                   7550:     $name=~s/\s+$//;
                   7551:     $name=~s/\s+/ /g;
                   7552:     return $name;
                   7553: }
                   7554: 
1.84      www      7555: # ------------------------------------------------- Write to course preferences
                   7556: 
                   7557: sub writecoursepref {
                   7558:     my ($courseid,%prefs)=@_;
                   7559:     $courseid=~s/^\///;
                   7560:     $courseid=~s/\_/\//g;
                   7561:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7562:     my $chome=homeserver($cnum,$cdomain);
                   7563:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7564: 	return 'error: no such course';
                   7565:     }
                   7566:     my $cstring='';
1.800     albertel 7567:     foreach my $pref (keys(%prefs)) {
                   7568: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7569:     }
1.84      www      7570:     $cstring=~s/\&$//;
                   7571:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7572: }
                   7573: 
                   7574: # ---------------------------------------------------------- Make/modify course
                   7575: 
                   7576: sub createcourse {
1.741     raeburn  7577:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7578:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7579:     $url=&declutter($url);
                   7580:     my $cid='';
1.1028    raeburn  7581:     if ($context eq 'requestcourses') {
                   7582:         my $can_create = 0;
                   7583:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7584:         if ($udom eq $ownerdom) {
                   7585:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7586:                                   $context)) {
                   7587:                 $can_create = 1;
                   7588:             }
                   7589:         } else {
                   7590:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7591:                                            $category);
                   7592:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7593:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7594:                 if (@curr > 0) {
                   7595:                     my @options = qw(approval validate autolimit);
                   7596:                     my $optregex = join('|',@options);
                   7597:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7598:                         $can_create = 1;
                   7599:                     }
                   7600:                 }
                   7601:             }
                   7602:         }
                   7603:         if ($can_create) {
                   7604:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7605:                 unless (&allowed('ccc',$udom)) {
                   7606:                     return 'refused'; 
                   7607:                 }
1.1017    raeburn  7608:             }
                   7609:         } else {
                   7610:             return 'refused';
                   7611:         }
1.1028    raeburn  7612:     } elsif (!&allowed('ccc',$udom)) {
                   7613:         return 'refused';
1.84      www      7614:     }
1.1011    raeburn  7615: # --------------------------------------------------------------- Get Unique ID
                   7616:     my $uname;
                   7617:     if ($cnum =~ /^$match_courseid$/) {
                   7618:         my $chome=&homeserver($cnum,$udom,'true');
                   7619:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7620:             $uname = $cnum;
                   7621:         } else {
1.1038    raeburn  7622:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7623:         }
                   7624:     } else {
1.1038    raeburn  7625:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7626:     }
                   7627:     return $uname if ($uname =~ /^error/);
                   7628: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7629:     if (!defined($course_server)) {
                   7630:         if (defined(&domain($udom,'primary'))) {
                   7631:             $course_server = &domain($udom,'primary');
                   7632:         } else {
                   7633:             $course_server = $env{'user.home'}; 
                   7634:         }
                   7635:     }
                   7636:     my %host_servers =
                   7637:         &Apache::lonnet::get_servers($udom,'library');
                   7638:     unless ($host_servers{$course_server}) {
                   7639:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  7640:     }
1.84      www      7641: # ------------------------------------------------------------- Make the course
                   7642:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  7643:                       $course_server);
1.84      www      7644:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  7645:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      7646:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7647: 	return 'error: no such course';
                   7648:     }
1.271     www      7649: # ----------------------------------------------------------------- Course made
1.516     raeburn  7650: # log existence
1.1029    raeburn  7651:     my $now = time;
1.918     raeburn  7652:     my $newcourse = {
                   7653:                     $udom.'_'.$uname => {
1.921     raeburn  7654:                                      description => $description,
                   7655:                                      inst_code   => $inst_code,
                   7656:                                      owner       => $course_owner,
                   7657:                                      type        => $crstype,
1.1029    raeburn  7658:                                      creator     => $env{'user.name'}.':'.
                   7659:                                                     $env{'user.domain'},
                   7660:                                      created     => $now,
                   7661:                                      context     => $context,
1.918     raeburn  7662:                                                 },
                   7663:                     };
1.921     raeburn  7664:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      7665: # set toplevel url
1.271     www      7666:     my $topurl=$url;
                   7667:     unless ($nonstandard) {
                   7668: # ------------------------------------------ For standard courses, make top url
                   7669:         my $mapurl=&clutter($url);
1.278     www      7670:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 7671:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      7672: <map>
                   7673: <resource id="1" type="start"></resource>
                   7674: <resource id="2" src="$mapurl"></resource>
                   7675: <resource id="3" type="finish"></resource>
                   7676: <link index="1" from="1" to="2"></link>
                   7677: <link index="2" from="2" to="3"></link>
                   7678: </map>
                   7679: ENDINITMAP
                   7680:         $topurl=&declutter(
1.638     albertel 7681:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      7682:                           );
                   7683:     }
                   7684: # ----------------------------------------------------------- Write preferences
1.84      www      7685:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  7686:                      ('description'              => $description,
                   7687:                       'url'                      => $topurl,
                   7688:                       'internal.creator'         => $env{'user.name'}.':'.
                   7689:                                                     $env{'user.domain'},
                   7690:                       'internal.created'         => $now,
                   7691:                       'internal.creationcontext' => $context)
                   7692:                     );
1.84      www      7693:     return '/'.$udom.'/'.$uname;
                   7694: }
                   7695: 
1.1011    raeburn  7696: # ------------------------------------------------------------------- Create ID
                   7697: sub generate_coursenum {
1.1038    raeburn  7698:     my ($udom,$crstype) = @_;
1.1011    raeburn  7699:     my $domdesc = &domain($udom);
                   7700:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  7701:     my $first;
                   7702:     if ($crstype eq 'Community') {
                   7703:         $first = '0';
                   7704:     } else {
                   7705:         $first = int(1+rand(9)); 
                   7706:     } 
                   7707:     my $uname=$first.
1.1011    raeburn  7708:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7709:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7710:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7711: # ----------------------------------------------- Make sure that does not exist
                   7712:     my $uhome=&homeserver($uname,$udom,'true');
                   7713:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  7714:         if ($crstype eq 'Community') {
                   7715:             $first = '0';
                   7716:         } else {
                   7717:             $first = int(1+rand(9));
                   7718:         }
                   7719:         $uname=$first.
1.1011    raeburn  7720:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   7721:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   7722:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   7723:         $uhome=&homeserver($uname,$udom,'true');
                   7724:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   7725:             return 'error: unable to generate unique course-ID';
                   7726:         }
                   7727:     }
                   7728:     return $uname;
                   7729: }
                   7730: 
1.813     albertel 7731: sub is_course {
                   7732:     my ($cdom,$cnum) = @_;
                   7733:     my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946     raeburn  7734: 				undef,'.');
1.813     albertel 7735:     if (exists($courses{$cdom.'_'.$cnum})) {
                   7736:         return 1;
                   7737:     }
                   7738:     return 0;
                   7739: }
                   7740: 
1.1015    raeburn  7741: sub store_userdata {
                   7742:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  7743:     my $result;
1.1016    raeburn  7744:     if ($datakey ne '') {
1.1013    raeburn  7745:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  7746:             if ($udom eq '' || $uname eq '') {
                   7747:                 $udom = $env{'user.domain'};
                   7748:                 $uname = $env{'user.name'};
                   7749:             }
                   7750:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  7751:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   7752:                 $result = 'error: no_host';
                   7753:             } else {
                   7754:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   7755:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   7756: 
                   7757:                 my $namevalue='';
                   7758:                 foreach my $key (keys(%{$storehash})) {
                   7759:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   7760:                 }
                   7761:                 $namevalue=~s/\&$//;
1.1105    raeburn  7762:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   7763:                                   $namevalue,$uhome);
1.1013    raeburn  7764:             }
                   7765:         } else {
                   7766:             $result = 'error: data to store was not a hash reference'; 
                   7767:         }
                   7768:     } else {
                   7769:         $result= 'error: invalid requestkey'; 
                   7770:     }
                   7771:     return $result;
                   7772: }
                   7773: 
1.21      www      7774: # ---------------------------------------------------------- Assign Custom Role
                   7775: 
                   7776: sub assigncustomrole {
1.957     raeburn  7777:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7778:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  7779:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      7780: }
                   7781: 
                   7782: # ----------------------------------------------------------------- Revoke Role
                   7783: 
                   7784: sub revokerole {
1.957     raeburn  7785:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7786:     my $now=time;
1.965     raeburn  7787:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      7788: }
                   7789: 
                   7790: # ---------------------------------------------------------- Revoke Custom Role
                   7791: 
                   7792: sub revokecustomrole {
1.957     raeburn  7793:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      7794:     my $now=time;
1.357     www      7795:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  7796:            $deleteflag,$selfenroll,$context);
1.17      www      7797: }
                   7798: 
1.533     banghart 7799: # ------------------------------------------------------------ Disk usage
1.535     albertel 7800: sub diskusage {
1.955     raeburn  7801:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   7802:     $directorypath =~ s/\/$//;
                   7803:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   7804:                        .&escape($getpropath).':'.&escape($uname).':'
                   7805:                        .&escape($udom),homeserver($uname,$udom));
                   7806:     if ($listing eq 'unknown_cmd') {
                   7807:         if ($getpropath) {
                   7808:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   7809:         }
                   7810:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   7811:     }
1.514     albertel 7812:     return $listing;
1.512     banghart 7813: }
                   7814: 
1.566     banghart 7815: sub is_locked {
1.1096    raeburn  7816:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 7817:     my @check;
                   7818:     my $is_locked;
1.1093    raeburn  7819:     push (@check,$file_name);
1.613     albertel 7820:     my %locked = &get('file_permissions',\@check,
1.620     albertel 7821: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 7822:     my ($tmp)=keys(%locked);
                   7823:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  7824:     
1.566     banghart 7825:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  7826:         $is_locked = 'false';
                   7827:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  7828:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  7829:                $is_locked = 'true';
1.1096    raeburn  7830:                if (ref($which) eq 'ARRAY') {
                   7831:                    push(@{$which},$entry);
                   7832:                } else {
                   7833:                    last;
                   7834:                }
1.745     raeburn  7835:            }
                   7836:        }
1.566     banghart 7837:     } else {
                   7838:         $is_locked = 'false';
                   7839:     }
1.1093    raeburn  7840:     return $is_locked;
1.566     banghart 7841: }
                   7842: 
1.759     albertel 7843: sub declutter_portfile {
                   7844:     my ($file) = @_;
1.833     albertel 7845:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 7846:     return $file;
                   7847: }
                   7848: 
1.559     banghart 7849: # ------------------------------------------------------------- Mark as Read Only
                   7850: 
                   7851: sub mark_as_readonly {
                   7852:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 7853:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7854:     my ($tmp)=keys(%current_permissions);
                   7855:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 7856:     foreach my $file (@{$files}) {
1.759     albertel 7857: 	$file = &declutter_portfile($file);
1.561     banghart 7858:         push(@{$current_permissions{$file}},$what);
1.559     banghart 7859:     }
1.613     albertel 7860:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 7861:     return;
                   7862: }
                   7863: 
1.572     banghart 7864: # ------------------------------------------------------------Save Selected Files
                   7865: 
                   7866: sub save_selected_files {
                   7867:     my ($user, $path, @files) = @_;
                   7868:     my $filename = $user."savedfiles";
1.573     banghart 7869:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 7870:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 7871:     foreach my $file (@files) {
1.620     albertel 7872:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 7873:     }
                   7874:     foreach my $file (@other_files) {
1.574     banghart 7875:         print (OUT $file."\n");
1.572     banghart 7876:     }
1.574     banghart 7877:     close (OUT);
1.572     banghart 7878:     return 'ok';
                   7879: }
                   7880: 
1.574     banghart 7881: sub clear_selected_files {
                   7882:     my ($user) = @_;
                   7883:     my $filename = $user."savedfiles";
1.1117    foxr     7884:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 7885:     print (OUT undef);
                   7886:     close (OUT);
                   7887:     return ("ok");    
                   7888: }
                   7889: 
1.572     banghart 7890: sub files_in_path {
                   7891:     my ($user, $path) = @_;
                   7892:     my $filename = $user."savedfiles";
                   7893:     my %return_files;
1.1117    foxr     7894:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 7895:     while (my $line_in = <IN>) {
1.574     banghart 7896:         chomp ($line_in);
                   7897:         my @paths_and_file = split (m!/!, $line_in);
                   7898:         my $file_part = pop (@paths_and_file);
                   7899:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 7900:         $path_part.='/';
                   7901:         my $path_and_file = $path_part.$file_part;
                   7902:         if ($path_part eq $path) {
                   7903:             $return_files{$file_part}= 'selected';
                   7904:         }
                   7905:     }
1.574     banghart 7906:     close (IN);
                   7907:     return (\%return_files);
1.572     banghart 7908: }
                   7909: 
                   7910: # called in portfolio select mode, to show files selected NOT in current directory
                   7911: sub files_not_in_path {
                   7912:     my ($user, $path) = @_;
                   7913:     my $filename = $user."savedfiles";
                   7914:     my @return_files;
                   7915:     my $path_part;
1.1117    foxr     7916:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 7917:     while (my $line = <IN>) {
1.572     banghart 7918:         #ok, I know it's clunky, but I want it to work
1.800     albertel 7919:         my @paths_and_file = split(m|/|, $line);
                   7920:         my $file_part = pop(@paths_and_file);
                   7921:         chomp($file_part);
                   7922:         my $path_part = join('/', @paths_and_file);
1.572     banghart 7923:         $path_part .= '/';
                   7924:         my $path_and_file = $path_part.$file_part;
                   7925:         if ($path_part ne $path) {
1.800     albertel 7926:             push(@return_files, ($path_and_file));
1.572     banghart 7927:         }
                   7928:     }
1.800     albertel 7929:     close(OUT);
1.574     banghart 7930:     return (@return_files);
1.572     banghart 7931: }
                   7932: 
1.745     raeburn  7933: #----------------------------------------------Get portfolio file permissions
1.629     banghart 7934: 
1.745     raeburn  7935: sub get_portfile_permissions {
                   7936:     my ($domain,$user) = @_;
1.613     albertel 7937:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 7938:     my ($tmp)=keys(%current_permissions);
                   7939:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  7940:     return \%current_permissions;
                   7941: }
                   7942: 
                   7943: #---------------------------------------------Get portfolio file access controls
                   7944: 
1.749     raeburn  7945: sub get_access_controls {
1.745     raeburn  7946:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 7947:     my %access;
                   7948:     my $real_file = $file;
                   7949:     $file =~ s/\.meta$//;
1.745     raeburn  7950:     if (defined($file)) {
1.749     raeburn  7951:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   7952:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 7953:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  7954:             }
                   7955:         }
1.745     raeburn  7956:     } else {
1.749     raeburn  7957:         foreach my $key (keys(%{$current_permissions})) {
                   7958:             if ($key =~ /\0accesscontrol$/) {
                   7959:                 if (defined($group)) {
                   7960:                     if ($key !~ m-^\Q$group\E/-) {
                   7961:                         next;
                   7962:                     }
                   7963:                 }
                   7964:                 my ($fullpath) = split(/\0/,$key);
                   7965:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   7966:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   7967:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   7968:                     }
                   7969:                 }
                   7970:             }
                   7971:         }
                   7972:     }
                   7973:     return %access;
                   7974: }
                   7975: 
                   7976: sub modify_access_controls {
                   7977:     my ($file_name,$changes,$domain,$user)=@_;
                   7978:     my ($outcome,$deloutcome);
                   7979:     my %store_permissions;
                   7980:     my %new_values;
                   7981:     my %new_control;
                   7982:     my %translation;
                   7983:     my @deletions = ();
                   7984:     my $now = time;
                   7985:     if (exists($$changes{'activate'})) {
                   7986:         if (ref($$changes{'activate'}) eq 'HASH') {
                   7987:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   7988:             my $numnew = scalar(@newitems);
                   7989:             for (my $i=0; $i<$numnew; $i++) {
                   7990:                 my $newkey = $newitems[$i];
                   7991:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  7992:                 if ($newkey =~ /^\d+:/) { 
                   7993:                     $newkey =~ s/^(\d+)/$newid/;
                   7994:                     $translation{$1} = $newid;
                   7995:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   7996:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   7997:                     $translation{$1} = $newid;
                   7998:                 }
1.749     raeburn  7999:                 $new_values{$file_name."\0".$newkey} = 
                   8000:                                           $$changes{'activate'}{$newitems[$i]};
                   8001:                 $new_control{$newkey} = $now;
                   8002:             }
                   8003:         }
                   8004:     }
                   8005:     my %todelete;
                   8006:     my %changed_items;
                   8007:     foreach my $action ('delete','update') {
                   8008:         if (exists($$changes{$action})) {
                   8009:             if (ref($$changes{$action}) eq 'HASH') {
                   8010:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8011:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8012:                     if ($action eq 'delete') { 
                   8013:                         $todelete{$itemnum} = 1;
                   8014:                     } else {
                   8015:                         $changed_items{$itemnum} = $key;
                   8016:                     }
                   8017:                 }
1.745     raeburn  8018:             }
                   8019:         }
1.749     raeburn  8020:     }
                   8021:     # get lock on access controls for file.
                   8022:     my $lockhash = {
                   8023:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8024:                                                        ':'.$env{'user.domain'},
                   8025:                    }; 
                   8026:     my $tries = 0;
                   8027:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8028:    
                   8029:     while (($gotlock ne 'ok') && $tries <3) {
                   8030:         $tries ++;
                   8031:         sleep 1;
                   8032:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8033:     }
                   8034:     if ($gotlock eq 'ok') {
                   8035:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8036:         my ($tmp)=keys(%curr_permissions);
                   8037:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8038:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8039:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8040:             if (ref($curr_controls) eq 'HASH') {
                   8041:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8042:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8043:                     if (defined($todelete{$itemnum})) {
                   8044:                         push(@deletions,$file_name."\0".$control_item);
                   8045:                     } else {
                   8046:                         if (defined($changed_items{$itemnum})) {
                   8047:                             $new_control{$changed_items{$itemnum}} = $now;
                   8048:                             push(@deletions,$file_name."\0".$control_item);
                   8049:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8050:                         } else {
                   8051:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8052:                         }
                   8053:                     }
1.745     raeburn  8054:                 }
                   8055:             }
                   8056:         }
1.970     raeburn  8057:         my ($group);
                   8058:         if (&is_course($domain,$user)) {
                   8059:             ($group,my $file) = split(/\//,$file_name,2);
                   8060:         }
1.749     raeburn  8061:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8062:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8063:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8064:         #  remove lock
                   8065:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8066:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8067:         my $sqlresult =
1.970     raeburn  8068:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8069:                                     $group);
1.749     raeburn  8070:     } else {
                   8071:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8072:     }
1.749     raeburn  8073:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8074: }
                   8075: 
1.827     raeburn  8076: sub make_public_indefinitely {
                   8077:     my ($requrl) = @_;
                   8078:     my $now = time;
                   8079:     my $action = 'activate';
                   8080:     my $aclnum = 0;
                   8081:     if (&is_portfolio_url($requrl)) {
                   8082:         my (undef,$udom,$unum,$file_name,$group) =
                   8083:             &parse_portfolio_url($requrl);
                   8084:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8085:         my %access_controls = &get_access_controls($current_perms,
                   8086:                                                    $group,$file_name);
                   8087:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8088:             my ($num,$scope,$end,$start) = 
                   8089:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8090:             if ($scope eq 'public') {
                   8091:                 if ($start <= $now && $end == 0) {
                   8092:                     $action = 'none';
                   8093:                 } else {
                   8094:                     $action = 'update';
                   8095:                     $aclnum = $num;
                   8096:                 }
                   8097:                 last;
                   8098:             }
                   8099:         }
                   8100:         if ($action eq 'none') {
                   8101:              return 'ok';
                   8102:         } else {
                   8103:             my %changes;
                   8104:             my $newend = 0;
                   8105:             my $newstart = $now;
                   8106:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8107:             $changes{$action}{$newkey} = {
                   8108:                 type => 'public',
                   8109:                 time => {
                   8110:                     start => $newstart,
                   8111:                     end   => $newend,
                   8112:                 },
                   8113:             };
                   8114:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8115:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8116:             return $outcome;
                   8117:         }
                   8118:     } else {
                   8119:         return 'invalid';
                   8120:     }
                   8121: }
                   8122: 
1.745     raeburn  8123: #------------------------------------------------------Get Marked as Read Only
                   8124: 
                   8125: sub get_marked_as_readonly {
                   8126:     my ($domain,$user,$what,$group) = @_;
                   8127:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8128:     my @readonly_files;
1.629     banghart 8129:     my $cmp1=$what;
                   8130:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8131:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8132:         if (defined($group)) {
                   8133:             if ($file_name !~ m-^\Q$group\E/-) {
                   8134:                 next;
                   8135:             }
                   8136:         }
1.561     banghart 8137:         if (ref($value) eq "ARRAY"){
                   8138:             foreach my $stored_what (@{$value}) {
1.629     banghart 8139:                 my $cmp2=$stored_what;
1.759     albertel 8140:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8141:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8142:                 }
1.629     banghart 8143:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8144:                     push(@readonly_files, $file_name);
1.745     raeburn  8145:                     last;
1.563     banghart 8146:                 } elsif (!defined($what)) {
                   8147:                     push(@readonly_files, $file_name);
1.745     raeburn  8148:                     last;
1.561     banghart 8149:                 }
                   8150:             }
1.745     raeburn  8151:         }
1.561     banghart 8152:     }
                   8153:     return @readonly_files;
                   8154: }
1.577     banghart 8155: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8156: 
1.577     banghart 8157: sub get_marked_as_readonly_hash {
1.745     raeburn  8158:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8159:     my %readonly_files;
1.745     raeburn  8160:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8161:         if (defined($group)) {
                   8162:             if ($file_name !~ m-^\Q$group\E/-) {
                   8163:                 next;
                   8164:             }
                   8165:         }
1.577     banghart 8166:         if (ref($value) eq "ARRAY"){
                   8167:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8168:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8169:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8170:                         if ($lock_descriptor eq 'graded') {
                   8171:                             $readonly_files{$file_name} = 'graded';
                   8172:                         } elsif ($lock_descriptor eq 'handback') {
                   8173:                             $readonly_files{$file_name} = 'handback';
                   8174:                         } else {
                   8175:                             if (!exists($readonly_files{$file_name})) {
                   8176:                                 $readonly_files{$file_name} = 'locked';
                   8177:                             }
                   8178:                         }
1.745     raeburn  8179:                     }
1.750     banghart 8180:                 } 
1.577     banghart 8181:             }
                   8182:         } 
                   8183:     }
                   8184:     return %readonly_files;
                   8185: }
1.559     banghart 8186: # ------------------------------------------------------------ Unmark as Read Only
                   8187: 
                   8188: sub unmark_as_readonly {
1.629     banghart 8189:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8190:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8191:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8192:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8193:     my $symb_crs = $what;
                   8194:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8195:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8196:     my ($tmp)=keys(%current_permissions);
                   8197:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8198:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8199:     foreach my $file (@readonly_files) {
1.759     albertel 8200: 	my $clean_file = &declutter_portfile($file);
                   8201: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8202: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8203:         my @new_locks;
                   8204:         my @del_keys;
                   8205:         if (ref($current_locks) eq "ARRAY"){
                   8206:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8207:                 my $compare=$locker;
1.749     raeburn  8208:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8209:                     $compare=join('',@{$locker});
1.746     raeburn  8210:                     if ($compare ne $symb_crs) {
                   8211:                         push(@new_locks, $locker);
                   8212:                     }
1.563     banghart 8213:                 }
                   8214:             }
1.650     albertel 8215:             if (scalar(@new_locks) > 0) {
1.563     banghart 8216:                 $current_permissions{$file} = \@new_locks;
                   8217:             } else {
                   8218:                 push(@del_keys, $file);
1.613     albertel 8219:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8220:                 delete($current_permissions{$file});
1.563     banghart 8221:             }
                   8222:         }
1.561     banghart 8223:     }
1.613     albertel 8224:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8225:     return;
                   8226: }
1.512     banghart 8227: 
1.17      www      8228: # ------------------------------------------------------------ Directory lister
                   8229: 
                   8230: sub dirlist {
1.955     raeburn  8231:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8232:     $uri=~s/^\///;
                   8233:     $uri=~s/\/$//;
1.253     stredwic 8234:     my ($udom, $uname);
1.955     raeburn  8235:     if ($getuserdir) {
1.253     stredwic 8236:         $udom = $userdomain;
                   8237:         $uname = $username;
1.955     raeburn  8238:     } else {
                   8239:         (undef,$udom,$uname)=split(/\//,$uri);
                   8240:         if(defined($userdomain)) {
                   8241:             $udom = $userdomain;
                   8242:         }
                   8243:         if(defined($username)) {
                   8244:             $uname = $username;
                   8245:         }
1.253     stredwic 8246:     }
1.955     raeburn  8247:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8248: 
1.955     raeburn  8249:     $dirRoot = $perlvar{'lonDocRoot'};
                   8250:     if (defined($getpropath)) {
                   8251:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8252:         $dirRoot =~ s/\/$//;
1.955     raeburn  8253:     } elsif (defined($getuserdir)) {
                   8254:         my $subdir=$uname.'__';
                   8255:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8256:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8257:                    ."/$udom/$subdir/$uname";
                   8258:     } elsif (defined($alternateRoot)) {
                   8259:         $dirRoot = $alternateRoot;
1.751     banghart 8260:     }
1.253     stredwic 8261: 
                   8262:     if($udom) {
                   8263:         if($uname) {
1.1135    raeburn  8264:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8265:             if ($uhome eq 'no_host') {
                   8266:                 return ([],'no_host');
                   8267:             }
1.955     raeburn  8268:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8269:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8270:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8271:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8272:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8273:             } else {
                   8274:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8275:             }
1.605     matthew  8276:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8277:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8278:                 @listing_results = split(/:/,$listing);
                   8279:             } else {
                   8280:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8281:             }
1.1135    raeburn  8282:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8283:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8284:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8285:                 return ([],$listing);
                   8286:             } else {
                   8287:                 return (\@listing_results);
1.1135    raeburn  8288:             }
1.955     raeburn  8289:         } elsif(!$alternateRoot) {
1.1136    raeburn  8290:             my (%allusers,%listerror);
1.841     albertel 8291: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8292:  	    foreach my $tryserver (keys(%servers)) {
                   8293:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8294:                                   &escape($udom),$tryserver);
                   8295:                 if ($listing eq 'unknown_cmd') {
                   8296: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8297: 				      $udom, $tryserver);
                   8298:                 } else {
                   8299:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8300:                 }
1.841     albertel 8301: 		if ($listing eq 'unknown_cmd') {
                   8302: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8303: 				      $udom, $tryserver);
                   8304: 		    @listing_results = split(/:/,$listing);
                   8305: 		} else {
                   8306: 		    @listing_results =
                   8307: 			map { &unescape($_); } split(/:/,$listing);
                   8308: 		}
1.1136    raeburn  8309:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8310:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8311:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8312:                     $listerror{$tryserver} = $listing;
                   8313:                 } else {
1.841     albertel 8314: 		    foreach my $line (@listing_results) {
                   8315: 			my ($entry) = split(/&/,$line,2);
                   8316: 			$allusers{$entry} = 1;
                   8317: 		    }
                   8318: 		}
1.253     stredwic 8319:             }
1.1136    raeburn  8320:             my @alluserslist=();
1.800     albertel 8321:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8322:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8323:             }
1.1136    raeburn  8324:             return (\@alluserslist);
1.253     stredwic 8325:         } else {
1.1136    raeburn  8326:             return ([],'missing username');
1.253     stredwic 8327:         }
1.955     raeburn  8328:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8329:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8330:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8331:         return (\@all_domains);
1.955     raeburn  8332:     } else {
1.1136    raeburn  8333:         return ([],'missing domain');
1.275     stredwic 8334:     }
                   8335: }
                   8336: 
                   8337: # --------------------------------------------- GetFileTimestamp
                   8338: # This function utilizes dirlist and returns the date stamp for
                   8339: # when it was last modified.  It will also return an error of -1
                   8340: # if an error occurs
                   8341: 
                   8342: sub GetFileTimestamp {
1.955     raeburn  8343:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8344:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8345:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8346:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8347:                                     undef,$getuserdir);
                   8348:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8349:         return -1;
                   8350:     }
                   8351:     if (ref($fileref) eq 'ARRAY') {
                   8352:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8353:         # @stats contains first the filename, then the stat output
                   8354:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8355:     } else {
                   8356:         return -1;
1.253     stredwic 8357:     }
1.26      www      8358: }
                   8359: 
1.712     albertel 8360: sub stat_file {
                   8361:     my ($uri) = @_;
1.787     albertel 8362:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8363: 
1.955     raeburn  8364:     my ($udom,$uname,$file);
1.712     albertel 8365:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8366: 	($udom,$uname,$file) =
1.811     albertel 8367: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8368: 	$file = 'userfiles/'.$file;
                   8369:     }
                   8370:     if ($uri =~ m-^/res/-) {
                   8371: 	($udom,$uname) = 
1.807     albertel 8372: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8373: 	$file = $uri;
                   8374:     }
                   8375: 
                   8376:     if (!$udom || !$uname || !$file) {
                   8377: 	# unable to handle the uri
                   8378: 	return ();
                   8379:     }
1.956     raeburn  8380:     my $getpropath;
                   8381:     if ($file =~ /^userfiles\//) {
                   8382:         $getpropath = 1;
                   8383:     }
1.1136    raeburn  8384:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8385:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8386:         return ();
                   8387:     } else {
                   8388:         if (ref($listref) eq 'ARRAY') {
                   8389:             my @stats = split('&',$listref->[0]);
                   8390: 	    shift(@stats); #filename is first
                   8391: 	    return @stats;
                   8392:         }
1.712     albertel 8393:     }
                   8394:     return ();
                   8395: }
                   8396: 
1.26      www      8397: # -------------------------------------------------------- Value of a Condition
                   8398: 
1.713     albertel 8399: # gets the value of a specific preevaluated condition
                   8400: #    stored in the string  $env{user.state.<cid>}
                   8401: # or looks up a condition reference in the bighash and if if hasn't
                   8402: # already been evaluated recurses into docondval to get the value of
                   8403: # the condition, then memoizing it to 
                   8404: #   $env{user.state.<cid>.<condition>}
1.40      www      8405: sub directcondval {
                   8406:     my $number=shift;
1.620     albertel 8407:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8408: 	&Apache::lonuserstate::evalstate();
                   8409:     }
1.713     albertel 8410:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8411: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8412:     } elsif ($number =~ /^_/) {
                   8413: 	my $sub_condition;
                   8414: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8415: 		&GDBM_READER(),0640)) {
                   8416: 	    $sub_condition=$bighash{'conditions'.$number};
                   8417: 	    untie(%bighash);
                   8418: 	}
                   8419: 	my $value = &docondval($sub_condition);
1.949     raeburn  8420: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8421: 	return $value;
                   8422:     }
1.620     albertel 8423:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8424:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8425:     } else {
                   8426:        return 2;
                   8427:     }
                   8428: }
                   8429: 
1.713     albertel 8430: # get the collection of conditions for this resource
1.26      www      8431: sub condval {
                   8432:     my $condidx=shift;
1.54      www      8433:     my $allpathcond='';
1.713     albertel 8434:     foreach my $cond (split(/\|/,$condidx)) {
                   8435: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8436: 	    $allpathcond.=
                   8437: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8438: 	}
1.191     harris41 8439:     }
1.54      www      8440:     $allpathcond=~s/\|$//;
1.713     albertel 8441:     return &docondval($allpathcond);
                   8442: }
                   8443: 
                   8444: #evaluates an expression of conditions
                   8445: sub docondval {
                   8446:     my ($allpathcond) = @_;
                   8447:     my $result=0;
                   8448:     if ($env{'request.course.id'}
                   8449: 	&& defined($allpathcond)) {
                   8450: 	my $operand='|';
                   8451: 	my @stack;
                   8452: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8453: 	    if ($chunk eq '(') {
                   8454: 		push @stack,($operand,$result);
                   8455: 	    } elsif ($chunk eq ')') {
                   8456: 		my $before=pop @stack;
                   8457: 		if (pop @stack eq '&') {
                   8458: 		    $result=$result>$before?$before:$result;
                   8459: 		} else {
                   8460: 		    $result=$result>$before?$result:$before;
                   8461: 		}
                   8462: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8463: 		$operand=$chunk;
                   8464: 	    } else {
                   8465: 		my $new=directcondval($chunk);
                   8466: 		if ($operand eq '&') {
                   8467: 		    $result=$result>$new?$new:$result;
                   8468: 		} else {
                   8469: 		    $result=$result>$new?$result:$new;
                   8470: 		}
                   8471: 	    }
                   8472: 	}
1.26      www      8473:     }
                   8474:     return $result;
1.421     albertel 8475: }
                   8476: 
                   8477: # ---------------------------------------------------- Devalidate courseresdata
                   8478: 
                   8479: sub devalidatecourseresdata {
                   8480:     my ($coursenum,$coursedomain)=@_;
                   8481:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8482:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8483: }
                   8484: 
1.763     www      8485: 
1.200     www      8486: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8487: #
                   8488: #  Parameters:
                   8489: #      $coursenum    - Number of the course.
                   8490: #      $coursedomain - Domain at which the course was created.
                   8491: #  Returns:
                   8492: #     A hash of the course parameters along (I think) with timestamps
                   8493: #     and version info.
1.877     foxr     8494: 
1.624     albertel 8495: sub get_courseresdata {
                   8496:     my ($coursenum,$coursedomain)=@_;
1.200     www      8497:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8498:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8499:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8500:     my %dumpreply;
1.417     albertel 8501:     unless (defined($cached)) {
1.624     albertel 8502: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8503: 	$result=\%dumpreply;
1.251     albertel 8504: 	my ($tmp) = keys(%dumpreply);
                   8505: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8506: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8507: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8508: 	    return $tmp;
1.416     albertel 8509: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8510: 	    $result=undef;
1.599     albertel 8511: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8512: 	}
                   8513:     }
1.624     albertel 8514:     return $result;
                   8515: }
                   8516: 
1.633     albertel 8517: sub devalidateuserresdata {
                   8518:     my ($uname,$udom)=@_;
                   8519:     my $hashid="$udom:$uname";
                   8520:     &devalidate_cache_new('userres',$hashid);
                   8521: }
                   8522: 
1.624     albertel 8523: sub get_userresdata {
                   8524:     my ($uname,$udom)=@_;
                   8525:     #most student don\'t have any data set, check if there is some data
                   8526:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8527: 
                   8528:     my $hashid="$udom:$uname";
                   8529:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8530:     if (!defined($cached)) {
                   8531: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8532: 	$result=\%resourcedata;
                   8533: 	&do_cache_new('userres',$hashid,$result,600);
                   8534:     }
                   8535:     my ($tmp)=keys(%$result);
                   8536:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8537: 	return $result;
                   8538:     }
                   8539:     #error 2 occurs when the .db doesn't exist
                   8540:     if ($tmp!~/error: 2 /) {
1.672     albertel 8541: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8542: 		 " Trying to get resource data for ".
                   8543: 		 $uname." at ".$udom.": ".
                   8544: 		 $tmp."</font>");
                   8545:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8546: 	#&EXT_cache_set($udom,$uname);
                   8547: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8548: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8549:     }
                   8550:     return $tmp;
                   8551: }
1.879     foxr     8552: #----------------------------------------------- resdata - return resource data
                   8553: #  Purpose:
                   8554: #    Return resource data for either users or for a course.
                   8555: #  Parameters:
                   8556: #     $name      - Course/user name.
                   8557: #     $domain    - Name of the domain the user/course is registered on.
                   8558: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8559: #     @which     - Array of names of resources desired.
                   8560: #  Returns:
                   8561: #     The value of the first reasource in @which that is found in the
                   8562: #     resource hash.
                   8563: #  Exceptional Conditions:
                   8564: #     If the $type passed in is not valid (not the string 'course' or 
                   8565: #     'user', an undefined  reference is returned.
                   8566: #     If none of the resources are found, an undef is returned
1.624     albertel 8567: sub resdata {
                   8568:     my ($name,$domain,$type,@which)=@_;
                   8569:     my $result;
                   8570:     if ($type eq 'course') {
                   8571: 	$result=&get_courseresdata($name,$domain);
                   8572:     } elsif ($type eq 'user') {
                   8573: 	$result=&get_userresdata($name,$domain);
                   8574:     }
                   8575:     if (!ref($result)) { return $result; }    
1.251     albertel 8576:     foreach my $item (@which) {
1.927     albertel 8577: 	if (defined($result->{$item->[0]})) {
                   8578: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8579: 	}
1.250     albertel 8580:     }
1.291     albertel 8581:     return undef;
1.200     www      8582: }
                   8583: 
1.379     matthew  8584: #
                   8585: # EXT resource caching routines
                   8586: #
                   8587: 
                   8588: sub clear_EXT_cache_status {
1.383     albertel 8589:     &delenv('cache.EXT.');
1.379     matthew  8590: }
                   8591: 
                   8592: sub EXT_cache_status {
                   8593:     my ($target_domain,$target_user) = @_;
1.383     albertel 8594:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8595:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8596:         # We know already the user has no data
                   8597:         return 1;
                   8598:     } else {
                   8599:         return 0;
                   8600:     }
                   8601: }
                   8602: 
                   8603: sub EXT_cache_set {
                   8604:     my ($target_domain,$target_user) = @_;
1.383     albertel 8605:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8606:     #&appenv({$cachename => time});
1.379     matthew  8607: }
                   8608: 
1.28      www      8609: # --------------------------------------------------------- Value of a Variable
1.58      www      8610: sub EXT {
1.715     albertel 8611: 
1.395     albertel 8612:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8613:     unless ($varname) { return ''; }
1.218     albertel 8614:     #get real user name/domain, courseid and symb
                   8615:     my $courseid;
1.359     albertel 8616:     my $publicuser;
1.427     www      8617:     if ($symbparm) {
                   8618: 	$symbparm=&get_symb_from_alias($symbparm);
                   8619:     }
1.218     albertel 8620:     if (!($uname && $udom)) {
1.790     albertel 8621:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8622:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8623:     } else {
1.620     albertel 8624: 	$courseid=$env{'request.course.id'};
1.218     albertel 8625:     }
1.48      www      8626:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8627:     my $rest;
1.320     albertel 8628:     if (defined($therest[0])) {
1.48      www      8629:        $rest=join('.',@therest);
                   8630:     } else {
                   8631:        $rest='';
                   8632:     }
1.320     albertel 8633: 
1.57      www      8634:     my $qualifierrest=$qualifier;
                   8635:     if ($rest) { $qualifierrest.='.'.$rest; }
                   8636:     my $spacequalifierrest=$space;
                   8637:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      8638:     if ($realm eq 'user') {
1.48      www      8639: # --------------------------------------------------------------- user.resource
                   8640: 	if ($space eq 'resource') {
1.651     albertel 8641: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   8642: 		  || defined($Apache::lonhomework::parsing_a_task))
                   8643: 		 &&
1.744     albertel 8644: 		 ($symbparm eq &symbread()) ) {	
                   8645: 		# if we are in the middle of processing the resource the
                   8646: 		# get the value we are planning on committing
                   8647:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   8648:                     return $Apache::lonhomework::results{$qualifierrest};
                   8649:                 } else {
                   8650:                     return $Apache::lonhomework::history{$qualifierrest};
                   8651:                 }
1.335     albertel 8652: 	    } else {
1.359     albertel 8653: 		my %restored;
1.620     albertel 8654: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 8655: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   8656: 		} else {
                   8657: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   8658: 		}
1.335     albertel 8659: 		return $restored{$qualifierrest};
                   8660: 	    }
1.48      www      8661: # ----------------------------------------------------------------- user.access
                   8662:         } elsif ($space eq 'access') {
1.218     albertel 8663: 	    # FIXME - not supporting calls for a specific user
1.48      www      8664:             return &allowed($qualifier,$rest);
                   8665: # ------------------------------------------ user.preferences, user.environment
                   8666:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 8667: 	    if (($uname eq $env{'user.name'}) &&
                   8668: 		($udom eq $env{'user.domain'})) {
                   8669: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 8670: 	    } else {
1.359     albertel 8671: 		my %returnhash;
                   8672: 		if (!$publicuser) {
                   8673: 		    %returnhash=&userenvironment($udom,$uname,
                   8674: 						 $qualifierrest);
                   8675: 		}
1.218     albertel 8676: 		return $returnhash{$qualifierrest};
                   8677: 	    }
1.48      www      8678: # ----------------------------------------------------------------- user.course
                   8679:         } elsif ($space eq 'course') {
1.218     albertel 8680: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8681:             return $env{join('.',('request.course',$qualifier))};
1.48      www      8682: # ------------------------------------------------------------------- user.role
                   8683:         } elsif ($space eq 'role') {
1.218     albertel 8684: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 8685:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      8686:             if ($qualifier eq 'value') {
                   8687: 		return $role;
                   8688:             } elsif ($qualifier eq 'extent') {
                   8689:                 return $where;
                   8690:             }
                   8691: # ----------------------------------------------------------------- user.domain
                   8692:         } elsif ($space eq 'domain') {
1.218     albertel 8693:             return $udom;
1.48      www      8694: # ------------------------------------------------------------------- user.name
                   8695:         } elsif ($space eq 'name') {
1.218     albertel 8696:             return $uname;
1.48      www      8697: # ---------------------------------------------------- Any other user namespace
1.29      www      8698:         } else {
1.359     albertel 8699: 	    my %reply;
                   8700: 	    if (!$publicuser) {
                   8701: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   8702: 	    }
                   8703: 	    return $reply{$qualifierrest};
1.48      www      8704:         }
1.236     www      8705:     } elsif ($realm eq 'query') {
                   8706: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 8707:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   8708: 						[$spacequalifierrest]);
1.620     albertel 8709: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      8710:    } elsif ($realm eq 'request') {
1.48      www      8711: # ------------------------------------------------------------- request.browser
                   8712:         if ($space eq 'browser') {
1.1145    bisitz   8713:             return $env{'browser.'.$qualifier};
1.57      www      8714: # ------------------------------------------------------------ request.filename
                   8715:         } else {
1.620     albertel 8716:             return $env{'request.'.$spacequalifierrest};
1.29      www      8717:         }
1.28      www      8718:     } elsif ($realm eq 'course') {
1.48      www      8719: # ---------------------------------------------------------- course.description
1.620     albertel 8720:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      8721:     } elsif ($realm eq 'resource') {
1.165     www      8722: 
1.620     albertel 8723: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 8724: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   8725: 	}
1.693     albertel 8726: 
                   8727: 	if ($space eq 'title') {
                   8728: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   8729: 	    return &gettitle($symbparm);
                   8730: 	}
                   8731: 	
                   8732: 	if ($space eq 'map') {
                   8733: 	    my ($map) = &decode_symb($symbparm);
                   8734: 	    return &symbread($map);
                   8735: 	}
1.905     albertel 8736: 	if ($space eq 'filename') {
                   8737: 	    if ($symbparm) {
                   8738: 		return &clutter((&decode_symb($symbparm))[2]);
                   8739: 	    }
                   8740: 	    return &hreflocation('',$env{'request.filename'});
                   8741: 	}
1.693     albertel 8742: 
                   8743: 	my ($section, $group, @groups);
1.593     albertel 8744: 	my ($courselevelm,$courselevel);
1.539     albertel 8745: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8746: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      8747: 
1.218     albertel 8748: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      8749: 
1.60      www      8750: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 8751: 	    my $symbp=$symbparm;
1.735     albertel 8752: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 8753: 
                   8754: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   8755: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   8756: 
1.620     albertel 8757: 	    if (($env{'user.name'} eq $uname) &&
                   8758: 		($env{'user.domain'} eq $udom)) {
                   8759: 		$section=$env{'request.course.sec'};
1.733     raeburn  8760:                 @groups = split(/:/,$env{'request.course.groups'});  
                   8761:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 8762: 	    } else {
1.539     albertel 8763: 		if (! defined($usection)) {
1.551     albertel 8764: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 8765: 		} else {
                   8766: 		    $section = $usection;
                   8767: 		}
1.733     raeburn  8768:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 8769: 	    }
                   8770: 
                   8771: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   8772: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   8773: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   8774: 
1.593     albertel 8775: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 8776: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 8777: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      8778: 
1.60      www      8779: # ----------------------------------------------------------- first, check user
1.624     albertel 8780: 
                   8781: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 8782: 				       ([$courselevelr,'resource'],
                   8783: 					[$courselevelm,'map'     ],
                   8784: 					[$courselevel, 'course'  ]));
1.931     albertel 8785: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      8786: 
1.594     albertel 8787: # ------------------------------------------------ second, check some of course
1.684     raeburn  8788:             my $coursereply;
1.691     raeburn  8789:             if (@groups > 0) {
                   8790:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   8791:                                        $mapparm,$spacequalifierrest);
1.927     albertel 8792:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  8793:             }
1.96      www      8794: 
1.684     raeburn  8795: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 8796: 				  $env{'course.'.$courseid.'.domain'},
                   8797: 				  'course',
                   8798: 				  ([$seclevelr,   'resource'],
                   8799: 				   [$seclevelm,   'map'     ],
                   8800: 				   [$seclevel,    'course'  ],
                   8801: 				   [$courselevelr,'resource']));
                   8802: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      8803: 
1.60      www      8804: # ------------------------------------------------------ third, check map parms
1.218     albertel 8805: 	    my %parmhash=();
                   8806: 	    my $thisparm='';
                   8807: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 8808: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 8809: 		    &GDBM_READER(),0640)) {
1.218     albertel 8810: 		$thisparm=$parmhash{$symbparm};
                   8811: 		untie(%parmhash);
                   8812: 	    }
1.927     albertel 8813: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 8814: 	}
1.594     albertel 8815: # ------------------------------------------ fourth, look in resource metadata
1.71      www      8816: 
1.218     albertel 8817: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 8818: 	my $filename;
                   8819: 	if (!$symbparm) { $symbparm=&symbread(); }
                   8820: 	if ($symbparm) {
1.409     www      8821: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 8822: 	} else {
1.620     albertel 8823: 	    $filename=$env{'request.filename'};
1.282     albertel 8824: 	}
                   8825: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 8826: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 8827: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 8828: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      8829: 
1.927     albertel 8830: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 8831: 	if ($symbparm && defined($courseid) && 
1.620     albertel 8832: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 8833: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   8834: 				     $env{'course.'.$courseid.'.domain'},
                   8835: 				     'course',
1.927     albertel 8836: 				     ([$courselevelm,'map'   ],
                   8837: 				      [$courselevel, 'course']));
                   8838: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 8839: 	}
1.145     www      8840: # ------------------------------------------------------------------ Cascade up
1.218     albertel 8841: 	unless ($space eq '0') {
1.336     albertel 8842: 	    my @parts=split(/_/,$space);
                   8843: 	    my $id=pop(@parts);
                   8844: 	    my $part=join('_',@parts);
                   8845: 	    if ($part eq '') { $part='0'; }
1.927     albertel 8846: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 8847: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  8848: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 8849: 	}
1.395     albertel 8850: 	if ($recurse) { return undef; }
                   8851: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 8852: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      8853: # ---------------------------------------------------- Any other user namespace
                   8854:     } elsif ($realm eq 'environment') {
                   8855: # ----------------------------------------------------------------- environment
1.620     albertel 8856: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   8857: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 8858: 	} else {
1.770     albertel 8859: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   8860: 		return '';
                   8861: 	    }
1.219     albertel 8862: 	    my %returnhash=&userenvironment($udom,$uname,
                   8863: 					    $spacequalifierrest);
                   8864: 	    return $returnhash{$spacequalifierrest};
                   8865: 	}
1.28      www      8866:     } elsif ($realm eq 'system') {
1.48      www      8867: # ----------------------------------------------------------------- system.time
                   8868: 	if ($space eq 'time') {
                   8869: 	    return time;
                   8870:         }
1.696     albertel 8871:     } elsif ($realm eq 'server') {
                   8872: # ----------------------------------------------------------------- system.time
                   8873: 	if ($space eq 'name') {
                   8874: 	    return $ENV{'SERVER_NAME'};
                   8875:         }
1.28      www      8876:     }
1.48      www      8877:     return '';
1.61      www      8878: }
                   8879: 
1.927     albertel 8880: sub get_reply {
                   8881:     my ($reply_value) = @_;
1.940     raeburn  8882:     if (ref($reply_value) eq 'ARRAY') {
                   8883:         if (wantarray) {
                   8884: 	    return @$reply_value;
                   8885:         }
                   8886:         return $reply_value->[0];
                   8887:     } else {
                   8888:         return $reply_value;
1.927     albertel 8889:     }
                   8890: }
                   8891: 
1.691     raeburn  8892: sub check_group_parms {
                   8893:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   8894:     my @groupitems = ();
                   8895:     my $resultitem;
1.927     albertel 8896:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  8897:     foreach my $group (@{$groups}) {
                   8898:         foreach my $level (@levels) {
1.927     albertel 8899:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   8900:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  8901:         }
                   8902:     }
                   8903:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   8904:                             $env{'course.'.$courseid.'.domain'},
                   8905:                                      'course',@groupitems);
                   8906:     return $coursereply;
                   8907: }
                   8908: 
                   8909: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  8910:     my ($courseid,@groups) = @_;
                   8911:     @groups = sort(@groups);
1.691     raeburn  8912:     return @groups;
                   8913: }
                   8914: 
1.395     albertel 8915: sub packages_tab_default {
                   8916:     my ($uri,$varname)=@_;
                   8917:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 8918: 
                   8919:     my (@extension,@specifics,$do_default);
                   8920:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 8921: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 8922: 	if ($pack_type eq 'default') {
                   8923: 	    $do_default=1;
                   8924: 	} elsif ($pack_type eq 'extension') {
                   8925: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 8926: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 8927: 	    # only look at packages defaults for packages that this id is
1.738     albertel 8928: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   8929: 	}
                   8930:     }
                   8931:     # first look for a package that matches the requested part id
                   8932:     foreach my $package (@specifics) {
                   8933: 	my (undef,$pack_type,$pack_part)=@{$package};
                   8934: 	next if ($pack_part ne $part);
                   8935: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8936: 	    return $packagetab{"$pack_type&$name&default"};
                   8937: 	}
                   8938:     }
                   8939:     # look for any possible matching non extension_ package
                   8940:     foreach my $package (@specifics) {
                   8941: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 8942: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8943: 	    return $packagetab{"$pack_type&$name&default"};
                   8944: 	}
1.585     albertel 8945: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 8946: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   8947: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 8948: 	}
                   8949:     }
1.738     albertel 8950:     # look for any posible extension_ match
                   8951:     foreach my $package (@extension) {
                   8952: 	my ($package,$pack_type)=@{$package};
                   8953: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   8954: 	    return $packagetab{"$pack_type&$name&default"};
                   8955: 	}
                   8956: 	if (defined($packagetab{$package."&$name&default"})) {
                   8957: 	    return $packagetab{$package."&$name&default"};
                   8958: 	}
                   8959:     }
                   8960:     # look for a global default setting
                   8961:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   8962: 	return $packagetab{"default&$name&default"};
                   8963:     }
1.395     albertel 8964:     return undef;
                   8965: }
                   8966: 
1.334     albertel 8967: sub add_prefix_and_part {
                   8968:     my ($prefix,$part)=@_;
                   8969:     my $keyroot;
                   8970:     if (defined($prefix) && $prefix !~ /^__/) {
                   8971: 	# prefix that has a part already
                   8972: 	$keyroot=$prefix;
                   8973:     } elsif (defined($prefix)) {
                   8974: 	# prefix that is missing a part
                   8975: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   8976:     } else {
                   8977: 	# no prefix at all
                   8978: 	if (defined($part)) { $keyroot='_'.$part; }
                   8979:     }
                   8980:     return $keyroot;
                   8981: }
                   8982: 
1.71      www      8983: # ---------------------------------------------------------------- Get metadata
                   8984: 
1.599     albertel 8985: my %metaentry;
1.1070    www      8986: my %importedpartids;
1.71      www      8987: sub metadata {
1.176     www      8988:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      8989:     $uri=&declutter($uri);
1.288     albertel 8990:     # if it is a non metadata possible uri return quickly
1.529     albertel 8991:     if (($uri eq '') || 
                   8992: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 8993: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  8994:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 8995: 	return undef;
                   8996:     }
1.1140    www      8997:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 8998: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 8999: 	return undef;
1.288     albertel 9000:     }
1.73      www      9001:     my $filename=$uri;
                   9002:     $uri=~s/\.meta$//;
1.172     www      9003: #
                   9004: # Is the metadata already cached?
1.177     www      9005: # Look at timestamp of caching
1.172     www      9006: # Everything is cached by the main uri, libraries are never directly cached
                   9007: #
1.428     albertel 9008:     if (!defined($liburi)) {
1.599     albertel 9009: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9010: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9011:     }
                   9012:     {
1.1069    www      9013: # Imported parts would go here
1.1070    www      9014:         my %importedids=();
                   9015:         my @origfileimportpartids=();
1.1069    www      9016:         my $importedparts=0;
1.172     www      9017: #
                   9018: # Is this a recursive call for a library?
                   9019: #
1.599     albertel 9020: #	if (! exists($metacache{$uri})) {
                   9021: #	    $metacache{$uri}={};
                   9022: #	}
1.924     albertel 9023: 	my $cachetime = 60*60;
1.171     www      9024:         if ($liburi) {
                   9025: 	    $liburi=&declutter($liburi);
                   9026:             $filename=$liburi;
1.401     bowersj2 9027:         } else {
1.599     albertel 9028: 	    &devalidate_cache_new('meta',$uri);
                   9029: 	    undef(%metaentry);
1.401     bowersj2 9030: 	}
1.140     www      9031:         my %metathesekeys=();
1.73      www      9032:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9033: 	my $metastring;
1.1140    www      9034: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9035: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9036: 	    $metastring = 
1.929     albertel 9037: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9038: 					  ('grade_target' => 'meta'));
                   9039: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9040: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9041:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9042: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9043: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9044: 	    $metastring=&getfile($file);
1.489     albertel 9045: 	}
1.208     albertel 9046:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9047:         my $token;
1.140     www      9048:         undef %metathesekeys;
1.71      www      9049:         while ($token=$parser->get_token) {
1.339     albertel 9050: 	    if ($token->[0] eq 'S') {
                   9051: 		if (defined($token->[2]->{'package'})) {
1.172     www      9052: #
                   9053: # This is a package - get package info
                   9054: #
1.339     albertel 9055: 		    my $package=$token->[2]->{'package'};
                   9056: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9057: 		    if (defined($token->[2]->{'id'})) { 
                   9058: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9059: 		    }
1.599     albertel 9060: 		    if ($metaentry{':packages'}) {
                   9061: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9062: 		    } else {
1.599     albertel 9063: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9064: 		    }
1.736     albertel 9065: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9066: 			my $part=$keyroot;
                   9067: 			$part=~s/^\_//;
1.736     albertel 9068: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9069: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9070: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9071: 			    # ignore package.tab specified default values
                   9072:                             # here &package_tab_default() will fetch those
                   9073: 			    if ($subp eq 'default') { next; }
1.736     albertel 9074: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9075: 			    my $unikey;
                   9076: 			    if ($pack =~ /_0$/) {
                   9077: 				$unikey='parameter_0_'.$name;
                   9078: 				$part=0;
                   9079: 			    } else {
                   9080: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9081: 			    }
1.339     albertel 9082: 			    if ($subp eq 'display') {
                   9083: 				$value.=' [Part: '.$part.']';
                   9084: 			    }
1.599     albertel 9085: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9086: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9087: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9088: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9089: 			    }
1.599     albertel 9090: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9091: 				$metaentry{':'.$unikey}=
                   9092: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9093: 			    }
1.339     albertel 9094: 			}
                   9095: 		    }
                   9096: 		} else {
1.172     www      9097: #
                   9098: # This is not a package - some other kind of start tag
1.339     albertel 9099: #
                   9100: 		    my $entry=$token->[1];
1.1068    www      9101: 		    my $unikey='';
1.175     www      9102: 
1.339     albertel 9103: 		    if ($entry eq 'import') {
1.175     www      9104: #
                   9105: # Importing a library here
1.339     albertel 9106: #
1.1067    www      9107:                         my $location=$parser->get_text('/import');
                   9108:                         my $dir=$filename;
                   9109:                         $dir=~s|[^/]*$||;
                   9110:                         $location=&filelocation($dir,$location);
1.1069    www      9111:                        
1.1068    www      9112:                         my $importmode=$token->[2]->{'importmode'};
                   9113:                         if ($importmode eq 'problem') {
1.1069    www      9114: # Import as problem/response
1.1068    www      9115:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9116:                         } elsif ($importmode eq 'part') {
                   9117: # Import as part(s)
1.1069    www      9118:                            $importedparts=1;
                   9119: # We need to get the original file and the imported file to get the part order correct
                   9120: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9121: # Load and inspect original file
1.1070    www      9122:                            if ($#origfileimportpartids<0) {
                   9123:                               undef(%importedpartids);
                   9124:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9125:                               my $origfile=&getfile($origfilelocation);
                   9126:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9127:                            }
                   9128: 
1.1069    www      9129: # Load and inspect imported file
                   9130:                            my $impfile=&getfile($location);
                   9131:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9132:                            if ($#impfilepartids>=0) {
                   9133: # This problem had parts
1.1070    www      9134:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9135:                            } else {
                   9136: # Importing by turning a single problem into a problem part
                   9137: # It gets the import-tags ID as part-ID
                   9138:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9139:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9140:                            }
1.1068    www      9141:                         } else {
                   9142: # Normal import
                   9143:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9144:                            if (defined($token->[2]->{'id'})) {
                   9145:                               $unikey.='_'.$token->[2]->{'id'};
                   9146:                            }
1.1067    www      9147:                         }
                   9148: 
1.339     albertel 9149: 			if ($depthcount<20) {
1.736     albertel 9150: 			    my $metadata = 
                   9151: 				&metadata($uri,'keys', $location,$unikey,
                   9152: 					  $depthcount+1);
                   9153: 			    foreach my $meta (split(',',$metadata)) {
                   9154: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9155: 				$metathesekeys{$meta}=1;
1.339     albertel 9156: 			    }
1.1068    www      9157: 			
                   9158:                         }
1.1067    www      9159: 		    } else {
                   9160: #
                   9161: # Not importing, some other kind of non-package, non-library start tag
                   9162: # 
                   9163:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9164:                         if (defined($token->[2]->{'id'})) {
                   9165:                             $unikey.='_'.$token->[2]->{'id'};
                   9166:                         }
1.339     albertel 9167: 			if (defined($token->[2]->{'name'})) { 
                   9168: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9169: 			}
                   9170: 			$metathesekeys{$unikey}=1;
1.736     albertel 9171: 			foreach my $param (@{$token->[3]}) {
                   9172: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9173: 				$token->[2]->{$param};
1.339     albertel 9174: 			}
                   9175: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9176: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9177: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9178: 		 # only ws inside the tag, and not in default, so use default
                   9179: 		 # as value
1.599     albertel 9180: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9181: 			} elsif ( $internaltext =~ /\S/ ) {
                   9182: 		  # something interesting inside the tag
                   9183: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9184: 			} else {
1.908     albertel 9185: 		  # no interesting values, don't set a default
1.339     albertel 9186: 			}
1.172     www      9187: # end of not-a-package not-a-library import
1.339     albertel 9188: 		    }
1.172     www      9189: # end of not-a-package start tag
1.339     albertel 9190: 		}
1.172     www      9191: # the next is the end of "start tag"
1.339     albertel 9192: 	    }
                   9193: 	}
1.483     albertel 9194: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9195: 	$extension = lc($extension);
                   9196: 	if ($extension eq 'htm') { $extension='html'; }
                   9197: 
1.737     albertel 9198: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9199: 	    #no specific packages #how's our extension
                   9200: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9201: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9202: 					 \%metathesekeys);
                   9203: 	}
1.883     albertel 9204: 
                   9205: 	if (!exists($metaentry{':packages'})
                   9206: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9207: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9208: 		#no specific packages well let's get default then
                   9209: 		if ($key!~/^default&/) { next; }
1.488     albertel 9210: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9211: 					     \%metathesekeys);
                   9212: 	    }
                   9213: 	}
1.338     www      9214: # are there custom rights to evaluate
1.599     albertel 9215: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9216: 
1.338     www      9217:     #
                   9218:     # Importing a rights file here
1.339     albertel 9219:     #
                   9220: 	    unless ($depthcount) {
1.599     albertel 9221: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9222: 		my $dir=$filename;
                   9223: 		$dir=~s|[^/]*$||;
                   9224: 		$location=&filelocation($dir,$location);
1.736     albertel 9225: 		my $rights_metadata =
                   9226: 		    &metadata($uri,'keys',$location,'_rights',
                   9227: 			      $depthcount+1);
                   9228: 		foreach my $rights (split(',',$rights_metadata)) {
                   9229: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9230: 		    $metathesekeys{$rights}=1;
1.339     albertel 9231: 		}
                   9232: 	    }
                   9233: 	}
1.737     albertel 9234: 	# uniqifiy package listing
                   9235: 	my %seen;
                   9236: 	my @uniq_packages =
                   9237: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9238: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9239: 
1.1070    www      9240:         if ($importedparts) {
                   9241: # We had imported parts and need to rebuild partorder
                   9242:            $metaentry{':partorder'}='';
                   9243:            $metathesekeys{'partorder'}=1;
                   9244:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9245:                if ($origfileimportpartids[$index] eq 'part') {
                   9246: # original part, part of the problem
                   9247:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9248:                } else {
                   9249: # we have imported parts at this position
                   9250:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9251:                }
                   9252:            }
                   9253:            $metaentry{':partorder'}=~s/^\,//;
                   9254:         }
                   9255: 
1.737     albertel 9256: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9257: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9258: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9259: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9260: # this is the end of "was not already recently cached
1.71      www      9261:     }
1.599     albertel 9262:     return $metaentry{':'.$what};
1.261     albertel 9263: }
                   9264: 
1.488     albertel 9265: sub metadata_create_package_def {
1.483     albertel 9266:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9267:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9268:     if ($subp eq 'default') { next; }
                   9269:     
1.599     albertel 9270:     if (defined($metaentry{':packages'})) {
                   9271: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9272:     } else {
1.599     albertel 9273: 	$metaentry{':packages'}=$package;
1.483     albertel 9274:     }
                   9275:     my $value=$packagetab{$key};
                   9276:     my $unikey;
                   9277:     $unikey='parameter_0_'.$name;
1.599     albertel 9278:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9279:     $$metathesekeys{$unikey}=1;
1.599     albertel 9280:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9281: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9282:     }
1.599     albertel 9283:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9284: 	$metaentry{':'.$unikey}=
                   9285: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9286:     }
                   9287: }
                   9288: 
1.261     albertel 9289: sub metadata_generate_part0 {
                   9290:     my ($metadata,$metacache,$uri) = @_;
                   9291:     my %allnames;
1.737     albertel 9292:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9293: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9294: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9295: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9296: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9297: 	    $allnames{$name}=$part;
                   9298: 	  }
                   9299: 	}
                   9300:     }
                   9301:     foreach my $name (keys(%allnames)) {
                   9302:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9303:       my $key=":parameter_0_$name";
1.261     albertel 9304:       $$metacache{"$key.part"}='0';
                   9305:       $$metacache{"$key.name"}=$name;
1.428     albertel 9306:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9307: 					   $allnames{$name}.'_'.$name.
                   9308: 					   '.type'};
1.428     albertel 9309:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9310: 			     '.display'};
1.644     www      9311:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9312:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9313:       $$metacache{"$key.display"}=$olddis;
                   9314:     }
1.71      www      9315: }
                   9316: 
1.764     albertel 9317: # ------------------------------------------------------ Devalidate title cache
                   9318: 
                   9319: sub devalidate_title_cache {
                   9320:     my ($url)=@_;
                   9321:     if (!$env{'request.course.id'}) { return; }
                   9322:     my $symb=&symbread($url);
                   9323:     if (!$symb) { return; }
                   9324:     my $key=$env{'request.course.id'}."\0".$symb;
                   9325:     &devalidate_cache_new('title',$key);
                   9326: }
                   9327: 
1.1014    droeschl 9328: # ------------------------------------------------- Get the title of a course
                   9329: 
                   9330: sub current_course_title {
                   9331:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9332: }
1.301     www      9333: # ------------------------------------------------- Get the title of a resource
                   9334: 
                   9335: sub gettitle {
                   9336:     my $urlsymb=shift;
                   9337:     my $symb=&symbread($urlsymb);
1.534     albertel 9338:     if ($symb) {
1.620     albertel 9339: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9340: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9341: 	if (defined($cached)) { 
                   9342: 	    return $result;
                   9343: 	}
1.534     albertel 9344: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9345: 	my $title='';
1.907     albertel 9346: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9347: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9348: 	} else {
                   9349: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9350: 		    &GDBM_READER(),0640)) {
                   9351: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9352: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9353: 		untie(%bighash);
                   9354: 	    }
1.534     albertel 9355: 	}
                   9356: 	$title=~s/\&colon\;/\:/gs;
                   9357: 	if ($title) {
1.599     albertel 9358: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9359: 	}
                   9360: 	$urlsymb=$url;
                   9361:     }
                   9362:     my $title=&metadata($urlsymb,'title');
                   9363:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9364:     return $title;
1.301     www      9365: }
1.613     albertel 9366: 
1.614     albertel 9367: sub get_slot {
                   9368:     my ($which,$cnum,$cdom)=@_;
                   9369:     if (!$cnum || !$cdom) {
1.790     albertel 9370: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9371: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9372: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9373:     }
1.703     albertel 9374:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9375:     my %slotinfo;
                   9376:     if (exists($remembered{$key})) {
                   9377: 	$slotinfo{$which} = $remembered{$key};
                   9378:     } else {
                   9379: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9380: 	&Apache::lonhomework::showhash(%slotinfo);
                   9381: 	my ($tmp)=keys(%slotinfo);
                   9382: 	if ($tmp=~/^error:/) { return (); }
                   9383: 	$remembered{$key} = $slotinfo{$which};
                   9384:     }
1.616     albertel 9385:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9386: 	return %{$slotinfo{$which}};
                   9387:     }
                   9388:     return $slotinfo{$which};
1.614     albertel 9389: }
1.31      www      9390: # ------------------------------------------------- Update symbolic store links
                   9391: 
                   9392: sub symblist {
                   9393:     my ($mapname,%newhash)=@_;
1.438     www      9394:     $mapname=&deversion(&declutter($mapname));
1.31      www      9395:     my %hash;
1.620     albertel 9396:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9397:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9398:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9399: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9400: 		next if ($url eq 'last_known'
                   9401: 			 && $env{'form.no_update_last_known'});
                   9402: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9403: 						    $newhash{$url}->[1],
                   9404: 						    $newhash{$url}->[0]);
1.191     harris41 9405:             }
1.31      www      9406:             if (untie(%hash)) {
                   9407: 		return 'ok';
                   9408:             }
                   9409:         }
                   9410:     }
                   9411:     return 'error';
1.212     www      9412: }
                   9413: 
                   9414: # --------------------------------------------------------------- Verify a symb
                   9415: 
                   9416: sub symbverify {
1.510     www      9417:     my ($symb,$thisurl)=@_;
                   9418:     my $thisfn=$thisurl;
1.439     www      9419:     $thisfn=&declutter($thisfn);
1.215     www      9420: # direct jump to resource in page or to a sequence - will construct own symbs
                   9421:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9422: # check URL part
1.409     www      9423:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9424: 
1.431     www      9425:     unless ($url eq $thisfn) { return 0; }
1.213     www      9426: 
1.216     www      9427:     $symb=&symbclean($symb);
1.510     www      9428:     $thisurl=&deversion($thisurl);
1.439     www      9429:     $thisfn=&deversion($thisfn);
1.213     www      9430: 
                   9431:     my %bighash;
                   9432:     my $okay=0;
1.431     www      9433: 
1.620     albertel 9434:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9435:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9436:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9437:             $thisurl =~ s/\?.+$//;
                   9438:         }
1.510     www      9439:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9440:         unless ($ids) {
                   9441:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9442:             $ids=$bighash{$idkey};
1.216     www      9443:         }
                   9444:         if ($ids) {
                   9445: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9446: 	    foreach my $id (split(/\,/,$ids)) {
                   9447: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9448:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9449:                    $symb =~ s/\?.+$//;
                   9450:                }
1.216     www      9451:                if (
                   9452:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9453:    eq $symb) { 
1.620     albertel 9454: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9455: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9456:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9457: 		       $okay=1; 
                   9458: 		   }
                   9459: 	       }
1.216     www      9460: 	   }
                   9461:         }
1.213     www      9462: 	untie(%bighash);
                   9463:     }
                   9464:     return $okay;
1.31      www      9465: }
                   9466: 
1.210     www      9467: # --------------------------------------------------------------- Clean-up symb
                   9468: 
                   9469: sub symbclean {
                   9470:     my $symb=shift;
1.568     albertel 9471:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9472: # remove version from map
                   9473:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9474: 
1.210     www      9475: # remove version from URL
                   9476:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9477: 
1.507     www      9478: # remove wrapper
                   9479: 
1.510     www      9480:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9481:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9482:     return $symb;
1.409     www      9483: }
                   9484: 
                   9485: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9486: 
                   9487: sub encode_symb {
                   9488:     my ($map,$resid,$url)=@_;
                   9489:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9490: }
1.409     www      9491: 
                   9492: sub decode_symb {
1.568     albertel 9493:     my $symb=shift;
                   9494:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9495:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9496:     return (&fixversion($map),$resid,&fixversion($url));
                   9497: }
                   9498: 
                   9499: sub fixversion {
                   9500:     my $fn=shift;
1.609     banghart 9501:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9502:     my %bighash;
                   9503:     my $uri=&clutter($fn);
1.620     albertel 9504:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9505: # is this cached?
1.599     albertel 9506:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9507:     if (defined($cached)) { return $result; }
                   9508: # unfortunately not cached, or expired
1.620     albertel 9509:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9510: 	    &GDBM_READER(),0640)) {
                   9511:  	if ($bighash{'version_'.$uri}) {
                   9512:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9513:  	    unless (($version eq 'mostrecent') || 
                   9514: 		    ($version==&getversion($uri))) {
1.440     www      9515:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9516:  	    }
                   9517:  	}
                   9518:  	untie %bighash;
1.413     www      9519:     }
1.599     albertel 9520:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9521: }
                   9522: 
                   9523: sub deversion {
                   9524:     my $url=shift;
                   9525:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9526:     return $url;
1.210     www      9527: }
                   9528: 
1.31      www      9529: # ------------------------------------------------------ Return symb list entry
                   9530: 
                   9531: sub symbread {
1.249     www      9532:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9533:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9534:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9535: # no filename provided? try from environment
1.44      www      9536:     unless ($thisfn) {
1.620     albertel 9537:         if ($env{'request.symb'}) {
                   9538: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9539: 	}
1.620     albertel 9540: 	$thisfn=$env{'request.filename'};
1.44      www      9541:     }
1.569     albertel 9542:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9543: # is that filename actually a symb? Verify, clean, and return
                   9544:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9545: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9546: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9547: 	}
1.242     www      9548:     }
1.44      www      9549:     $thisfn=declutter($thisfn);
1.31      www      9550:     my %hash;
1.37      www      9551:     my %bighash;
                   9552:     my $syval='';
1.620     albertel 9553:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9554:         my $targetfn = $thisfn;
1.609     banghart 9555:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9556:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9557:         }
1.687     albertel 9558: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9559: 	    $targetfn=$1;
                   9560: 	}
1.620     albertel 9561:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9562:                       &GDBM_READER(),0640)) {
1.481     raeburn  9563: 	    $syval=$hash{$targetfn};
1.37      www      9564:             untie(%hash);
                   9565:         }
                   9566: # ---------------------------------------------------------- There was an entry
                   9567:         if ($syval) {
1.601     albertel 9568: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9569: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9570: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9571: 		    #return $env{$cache_str}='';
1.601     albertel 9572: 		#}    
                   9573: 		#$syval.=$1;
                   9574: 	    #}
1.37      www      9575:         } else {
                   9576: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9577:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9578:                             &GDBM_READER(),0640)) {
1.37      www      9579: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9580:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      9581:               unless ($ids) { 
                   9582:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      9583:               }
                   9584:               unless ($ids) {
                   9585: # alias?
                   9586: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      9587:               }
1.37      www      9588:               if ($ids) {
                   9589: # ------------------------------------------------------------------- Has ID(s)
                   9590:                  my @possibilities=split(/\,/,$ids);
1.39      www      9591:                  if ($#possibilities==0) {
                   9592: # ----------------------------------------------- There is only one possibility
1.37      www      9593: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 9594: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9595: 						    $resid,$thisfn);
1.249     www      9596:                  } elsif (!$donotrecurse) {
1.39      www      9597: # ------------------------------------------ There is more than one possibility
                   9598:                      my $realpossible=0;
1.800     albertel 9599:                      foreach my $id (@possibilities) {
                   9600: 			 my $file=$bighash{'src_'.$id};
1.39      www      9601:                          if (&allowed('bre',$file)) {
1.800     albertel 9602:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      9603:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   9604: 				$realpossible++;
1.626     albertel 9605:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   9606: 						    $resid,$thisfn);
1.39      www      9607:                             }
                   9608: 			 }
1.191     harris41 9609:                      }
1.39      www      9610: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      9611:                  } else {
                   9612:                      $syval='';
1.37      www      9613:                  }
                   9614: 	      }
                   9615:               untie(%bighash)
1.481     raeburn  9616:            }
1.31      www      9617:         }
1.62      www      9618:         if ($syval) {
1.620     albertel 9619: 	    return $env{$cache_str}=$syval;
1.62      www      9620:         }
1.31      www      9621:     }
1.949     raeburn  9622:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9623:     return $env{$cache_str}='';
1.31      www      9624: }
                   9625: 
                   9626: # ---------------------------------------------------------- Return random seed
                   9627: 
1.32      www      9628: sub numval {
                   9629:     my $txt=shift;
                   9630:     $txt=~tr/A-J/0-9/;
                   9631:     $txt=~tr/a-j/0-9/;
                   9632:     $txt=~tr/K-T/0-9/;
                   9633:     $txt=~tr/k-t/0-9/;
                   9634:     $txt=~tr/U-Z/0-5/;
                   9635:     $txt=~tr/u-z/0-5/;
                   9636:     $txt=~s/\D//g;
1.564     albertel 9637:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      9638:     return int($txt);
1.368     albertel 9639: }
                   9640: 
1.484     albertel 9641: sub numval2 {
                   9642:     my $txt=shift;
                   9643:     $txt=~tr/A-J/0-9/;
                   9644:     $txt=~tr/a-j/0-9/;
                   9645:     $txt=~tr/K-T/0-9/;
                   9646:     $txt=~tr/k-t/0-9/;
                   9647:     $txt=~tr/U-Z/0-5/;
                   9648:     $txt=~tr/u-z/0-5/;
                   9649:     $txt=~s/\D//g;
                   9650:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9651:     my $total;
                   9652:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 9653:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 9654:     return int($total);
                   9655: }
                   9656: 
1.575     albertel 9657: sub numval3 {
                   9658:     use integer;
                   9659:     my $txt=shift;
                   9660:     $txt=~tr/A-J/0-9/;
                   9661:     $txt=~tr/a-j/0-9/;
                   9662:     $txt=~tr/K-T/0-9/;
                   9663:     $txt=~tr/k-t/0-9/;
                   9664:     $txt=~tr/U-Z/0-5/;
                   9665:     $txt=~tr/u-z/0-5/;
                   9666:     $txt=~s/\D//g;
                   9667:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   9668:     my $total;
                   9669:     foreach my $val (@txts) { $total+=$val; }
                   9670:     if ($_64bit) { $total=(($total<<32)>>32); }
                   9671:     return $total;
                   9672: }
                   9673: 
1.675     albertel 9674: sub digest {
                   9675:     my ($data)=@_;
                   9676:     my $digest=&Digest::MD5::md5($data);
                   9677:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   9678:     my ($e,$f);
                   9679:     {
                   9680:         use integer;
                   9681:         $e=($a+$b);
                   9682:         $f=($c+$d);
                   9683:         if ($_64bit) {
                   9684:             $e=(($e<<32)>>32);
                   9685:             $f=(($f<<32)>>32);
                   9686:         }
                   9687:     }
                   9688:     if (wantarray) {
                   9689: 	return ($e,$f);
                   9690:     } else {
                   9691: 	my $g;
                   9692: 	{
                   9693: 	    use integer;
                   9694: 	    $g=($e+$f);
                   9695: 	    if ($_64bit) {
                   9696: 		$g=(($g<<32)>>32);
                   9697: 	    }
                   9698: 	}
                   9699: 	return $g;
                   9700:     }
                   9701: }
                   9702: 
1.368     albertel 9703: sub latest_rnd_algorithm_id {
1.675     albertel 9704:     return '64bit5';
1.366     albertel 9705: }
1.32      www      9706: 
1.503     albertel 9707: sub get_rand_alg {
                   9708:     my ($courseid)=@_;
1.790     albertel 9709:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 9710:     if ($courseid) {
1.620     albertel 9711: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 9712:     }
                   9713:     return &latest_rnd_algorithm_id();
                   9714: }
                   9715: 
1.562     albertel 9716: sub validCODE {
                   9717:     my ($CODE)=@_;
                   9718:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   9719:     return 0;
                   9720: }
                   9721: 
1.491     albertel 9722: sub getCODE {
1.620     albertel 9723:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 9724:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   9725: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   9726: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 9727: 	return $Apache::lonhomework::history{'resource.CODE'};
                   9728:     }
                   9729:     return undef;
                   9730: }
1.1133    foxr     9731: #
                   9732: #  Determines the random seed for a specific context:
                   9733: #
                   9734: # parameters:
                   9735: #   symb      - in course context the symb for the seed.
                   9736: #   course_id - The course id of the form domain_coursenum.
                   9737: #   domain    - Domain for the user.
                   9738: #   course    - Course for the user.
                   9739: #   cenv      - environment of the course.
                   9740: #
                   9741: # NOTE:
                   9742: #   All parameters are picked out of the environment if missing
                   9743: #   or not defined.
                   9744: #   If a symb cannot be determined the current time is used instead.
                   9745: #
                   9746: #  For a given well defined symb, courside, domain, username,
                   9747: #  and course environment, the seed is reproducible.
                   9748: #
1.31      www      9749: sub rndseed {
1.1133    foxr     9750:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 9751:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 9752:     if (!defined($symb)) {
1.366     albertel 9753: 	unless ($symb=$wsymb) { return time; }
                   9754:     }
1.1146    foxr     9755:     if (!defined $courseid) { 
                   9756: 	$courseid=$wcourseid; 
                   9757:     }
                   9758:     if (!defined $domain) { $domain=$wdomain; }
                   9759:     if (!defined $username) { $username=$wusername }
1.1133    foxr     9760: 
                   9761:     my $which;
                   9762:     if (defined($cenv->{'rndseed'})) {
                   9763: 	$which = $cenv->{'rndseed'};
                   9764:     } else {
                   9765: 	$which =&get_rand_alg($courseid);
                   9766:     }
1.491     albertel 9767:     if (defined(&getCODE())) {
1.1133    foxr     9768: 
1.675     albertel 9769: 	if ($which eq '64bit5') {
                   9770: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   9771: 	} elsif ($which eq '64bit4') {
1.575     albertel 9772: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   9773: 	} else {
                   9774: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   9775: 	}
1.675     albertel 9776:     } elsif ($which eq '64bit5') {
                   9777: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 9778:     } elsif ($which eq '64bit4') {
                   9779: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 9780:     } elsif ($which eq '64bit3') {
                   9781: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 9782:     } elsif ($which eq '64bit2') {
                   9783: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 9784:     } elsif ($which eq '64bit') {
                   9785: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   9786:     }
                   9787:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   9788: }
                   9789: 
                   9790: sub rndseed_32bit {
                   9791:     my ($symb,$courseid,$domain,$username)=@_;
                   9792:     {
                   9793: 	use integer;
                   9794: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   9795: 	my $symbseed=numval($symb) << 22;
                   9796: 	my $namechck=unpack("%32C*",$username) << 17;
                   9797: 	my $nameseed=numval($username) << 12;
                   9798: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   9799: 	my $courseseed=unpack("%32C*",$courseid);
                   9800: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 9801: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9802: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9803: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 9804: 	return $num;
                   9805:     }
                   9806: }
                   9807: 
                   9808: sub rndseed_64bit {
                   9809:     my ($symb,$courseid,$domain,$username)=@_;
                   9810:     {
                   9811: 	use integer;
                   9812: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   9813: 	my $symbseed=numval($symb) << 10;
                   9814: 	my $namechck=unpack("%32S*",$username);
                   9815: 	
                   9816: 	my $nameseed=numval($username) << 21;
                   9817: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   9818: 	my $courseseed=unpack("%32S*",$courseid);
                   9819: 	
                   9820: 	my $num1=$symbchck+$symbseed+$namechck;
                   9821: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9822: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9823: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 9824: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 9825: 	return "$num1,$num2";
1.155     albertel 9826:     }
1.366     albertel 9827: }
                   9828: 
1.443     albertel 9829: sub rndseed_64bit2 {
                   9830:     my ($symb,$courseid,$domain,$username)=@_;
                   9831:     {
                   9832: 	use integer;
                   9833: 	# strings need to be an even # of cahracters long, it it is odd the
                   9834:         # last characters gets thrown away
                   9835: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9836: 	my $symbseed=numval($symb) << 10;
                   9837: 	my $namechck=unpack("%32S*",$username.' ');
                   9838: 	
                   9839: 	my $nameseed=numval($username) << 21;
1.501     albertel 9840: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9841: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9842: 	
                   9843: 	my $num1=$symbchck+$symbseed+$namechck;
                   9844: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9845: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9846: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 9847: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 9848: 	return "$num1,$num2";
                   9849:     }
                   9850: }
                   9851: 
                   9852: sub rndseed_64bit3 {
                   9853:     my ($symb,$courseid,$domain,$username)=@_;
                   9854:     {
                   9855: 	use integer;
                   9856: 	# strings need to be an even # of cahracters long, it it is odd the
                   9857:         # last characters gets thrown away
                   9858: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9859: 	my $symbseed=numval2($symb) << 10;
                   9860: 	my $namechck=unpack("%32S*",$username.' ');
                   9861: 	
                   9862: 	my $nameseed=numval2($username) << 21;
1.443     albertel 9863: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9864: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9865: 	
                   9866: 	my $num1=$symbchck+$symbseed+$namechck;
                   9867: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9868: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9869: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 9870: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9871: 	
1.503     albertel 9872: 	return "$num1:$num2";
1.443     albertel 9873:     }
                   9874: }
                   9875: 
1.575     albertel 9876: sub rndseed_64bit4 {
                   9877:     my ($symb,$courseid,$domain,$username)=@_;
                   9878:     {
                   9879: 	use integer;
                   9880: 	# strings need to be an even # of cahracters long, it it is odd the
                   9881:         # last characters gets thrown away
                   9882: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   9883: 	my $symbseed=numval3($symb) << 10;
                   9884: 	my $namechck=unpack("%32S*",$username.' ');
                   9885: 	
                   9886: 	my $nameseed=numval3($username) << 21;
                   9887: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   9888: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9889: 	
                   9890: 	my $num1=$symbchck+$symbseed+$namechck;
                   9891: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 9892: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   9893: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 9894: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      9895: 	
1.575     albertel 9896: 	return "$num1:$num2";
                   9897:     }
                   9898: }
                   9899: 
1.675     albertel 9900: sub rndseed_64bit5 {
                   9901:     my ($symb,$courseid,$domain,$username)=@_;
                   9902:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   9903:     return "$num1:$num2";
                   9904: }
                   9905: 
1.366     albertel 9906: sub rndseed_CODE_64bit {
                   9907:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 9908:     {
1.366     albertel 9909: 	use integer;
1.443     albertel 9910: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 9911: 	my $symbseed=numval2($symb);
1.491     albertel 9912: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9913: 	my $CODEseed=numval(&getCODE());
1.443     albertel 9914: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 9915: 	my $num1=$symbseed+$CODEchck;
                   9916: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9917: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9918: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 9919: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9920: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 9921: 	return "$num1:$num2";
1.366     albertel 9922:     }
                   9923: }
                   9924: 
1.575     albertel 9925: sub rndseed_CODE_64bit4 {
                   9926:     my ($symb,$courseid,$domain,$username)=@_;
                   9927:     {
                   9928: 	use integer;
                   9929: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   9930: 	my $symbseed=numval3($symb);
                   9931: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   9932: 	my $CODEseed=numval3(&getCODE());
                   9933: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   9934: 	my $num1=$symbseed+$CODEchck;
                   9935: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 9936: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   9937: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 9938: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   9939: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   9940: 	return "$num1:$num2";
                   9941:     }
                   9942: }
                   9943: 
1.675     albertel 9944: sub rndseed_CODE_64bit5 {
                   9945:     my ($symb,$courseid,$domain,$username)=@_;
                   9946:     my $code = &getCODE();
                   9947:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   9948:     return "$num1:$num2";
                   9949: }
                   9950: 
1.366     albertel 9951: sub setup_random_from_rndseed {
                   9952:     my ($rndseed)=@_;
1.503     albertel 9953:     if ($rndseed =~/([,:])/) {
                   9954: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 9955: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   9956:     } else {
                   9957: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 9958:     }
1.36      albertel 9959: }
                   9960: 
1.474     albertel 9961: sub latest_receipt_algorithm_id {
1.835     albertel 9962:     return 'receipt3';
1.474     albertel 9963: }
                   9964: 
1.480     www      9965: sub recunique {
                   9966:     my $fucourseid=shift;
                   9967:     my $unique;
1.835     albertel 9968:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   9969: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9970: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      9971:     } else {
                   9972: 	$unique=$perlvar{'lonReceipt'};
                   9973:     }
                   9974:     return unpack("%32C*",$unique);
                   9975: }
                   9976: 
                   9977: sub recprefix {
                   9978:     my $fucourseid=shift;
                   9979:     my $prefix;
1.835     albertel 9980:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   9981: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 9982: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      9983:     } else {
                   9984: 	$prefix=$perlvar{'lonHostID'};
                   9985:     }
                   9986:     return unpack("%32C*",$prefix);
                   9987: }
                   9988: 
1.76      www      9989: sub ireceipt {
1.474     albertel 9990:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 9991: 
                   9992:     my $return =&recprefix($fucourseid).'-';
                   9993: 
                   9994:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   9995: 	$env{'request.state'} eq 'construct') {
                   9996: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   9997: 	return $return;
                   9998:     }
                   9999: 
1.76      www      10000:     my $cuname=unpack("%32C*",$funame);
                   10001:     my $cudom=unpack("%32C*",$fudom);
                   10002:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10003:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10004:     my $cunique=&recunique($fucourseid);
1.474     albertel 10005:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10006:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10007: 
1.790     albertel 10008: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10009: 			       
                   10010: 	$return.= ($cunique%$cuname+
                   10011: 		   $cunique%$cudom+
                   10012: 		   $cusymb%$cuname+
                   10013: 		   $cusymb%$cudom+
                   10014: 		   $cucourseid%$cuname+
                   10015: 		   $cucourseid%$cudom+
                   10016: 		   $cpart%$cuname+
                   10017: 		   $cpart%$cudom);
                   10018:     } else {
                   10019: 	$return.= ($cunique%$cuname+
                   10020: 		   $cunique%$cudom+
                   10021: 		   $cusymb%$cuname+
                   10022: 		   $cusymb%$cudom+
                   10023: 		   $cucourseid%$cuname+
                   10024: 		   $cucourseid%$cudom);
                   10025:     }
                   10026:     return $return;
1.76      www      10027: }
                   10028: 
                   10029: sub receipt {
1.474     albertel 10030:     my ($part)=@_;
1.790     albertel 10031:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10032:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10033: }
1.260     ng       10034: 
1.790     albertel 10035: sub whichuser {
                   10036:     my ($passedsymb)=@_;
                   10037:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10038:     if (defined($env{'form.grade_symb'})) {
                   10039: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10040: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10041: 	if (!$allowed &&
                   10042: 	    exists($env{'request.course.sec'}) &&
                   10043: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10044: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10045: 			      '/'.$env{'request.course.sec'});
                   10046: 	}
                   10047: 	if ($allowed) {
                   10048: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10049: 	    $courseid=$tmp_courseid;
                   10050: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10051: 	    ($name)=&get_env_multiple('form.grade_username');
                   10052: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10053: 	}
                   10054:     }
                   10055:     if (!$passedsymb) {
                   10056: 	$symb=&symbread();
                   10057:     } else {
                   10058: 	$symb=$passedsymb;
                   10059:     }
                   10060:     $courseid=$env{'request.course.id'};
                   10061:     $domain=$env{'user.domain'};
                   10062:     $name=$env{'user.name'};
                   10063:     if ($name eq 'public' && $domain eq 'public') {
                   10064: 	if (!defined($env{'form.username'})) {
                   10065: 	    $env{'form.username'}.=time.rand(10000000);
                   10066: 	}
                   10067: 	$name.=$env{'form.username'};
                   10068:     }
                   10069:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10070: 
                   10071: }
                   10072: 
1.36      albertel 10073: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10074: # returns either the contents of the file or 
                   10075: # -1 if the file doesn't exist
1.481     raeburn  10076: #
                   10077: # if the target is a file that was uploaded via DOCS, 
                   10078: # a check will be made to see if a current copy exists on the local server,
                   10079: # if it does this will be served, otherwise a copy will be retrieved from
                   10080: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10081: # the local server.   
1.472     albertel 10082: 
1.36      albertel 10083: sub getfile {
1.538     albertel 10084:     my ($file) = @_;
1.609     banghart 10085:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10086:     &repcopy($file);
                   10087:     return &readfile($file);
                   10088: }
                   10089: 
                   10090: sub repcopy_userfile {
                   10091:     my ($file)=@_;
1.1142    raeburn  10092:     my $londocroot = $perlvar{'lonDocRoot'};
                   10093:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
                   10094:     if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10095:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10096: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10097:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10098:     if (-e "$file") {
1.828     www      10099: # we already have a local copy, check it out
1.538     albertel 10100: 	my @fileinfo = stat($file);
1.828     www      10101: 	my $rtncode;
                   10102: 	my $info;
1.538     albertel 10103: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10104: 	if ($lwpresp ne 'ok') {
1.828     www      10105: # there is no such file anymore, even though we had a local copy
1.482     albertel 10106: 	    if ($rtncode eq '404') {
1.538     albertel 10107: 		unlink($file);
1.482     albertel 10108: 	    }
                   10109: 	    return -1;
                   10110: 	}
                   10111: 	if ($info < $fileinfo[9]) {
1.828     www      10112: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10113: 	    return 'ok';
1.828     www      10114: 	} else {
                   10115: # the file is outdated, get rid of it
                   10116: 	    unlink($file);
1.482     albertel 10117: 	}
1.828     www      10118:     }
                   10119: # one way or the other, at this point, we don't have the file
                   10120: # construct the correct path for the file
                   10121:     my @parts = ($cdom,$cnum); 
                   10122:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10123: 	push @parts, split(/\//,$1);
                   10124:     }
                   10125:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10126:     foreach my $part (@parts) {
                   10127: 	$path .= '/'.$part;
                   10128: 	if (!-e $path) {
                   10129: 	    mkdir($path,0770);
1.482     albertel 10130: 	}
                   10131:     }
1.828     www      10132: # now the path exists for sure
                   10133: # get a user agent
                   10134:     my $ua=new LWP::UserAgent;
                   10135:     my $transferfile=$file.'.in.transfer';
                   10136: # FIXME: this should flock
                   10137:     if (-e $transferfile) { return 'ok'; }
                   10138:     my $request;
                   10139:     $uri=~s/^\///;
1.980     raeburn  10140:     my $homeserver = &homeserver($cnum,$cdom);
                   10141:     my $protocol = $protocol{$homeserver};
                   10142:     $protocol = 'http' if ($protocol ne 'https');
                   10143:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10144:     my $response=$ua->request($request,$transferfile);
                   10145: # did it work?
                   10146:     if ($response->is_error()) {
                   10147: 	unlink($transferfile);
                   10148: 	&logthis("Userfile repcopy failed for $uri");
                   10149: 	return -1;
                   10150:     }
                   10151: # worked, rename the transfer file
                   10152:     rename($transferfile,$file);
1.607     raeburn  10153:     return 'ok';
1.481     raeburn  10154: }
                   10155: 
1.517     albertel 10156: sub tokenwrapper {
                   10157:     my $uri=shift;
1.980     raeburn  10158:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10159:     $uri=~s|^/||;
1.620     albertel 10160:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10161:     my $token=$1;
1.552     albertel 10162:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10163:     if ($udom && $uname && $file) {
                   10164: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10165:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10166:         my $homeserver = &homeserver($uname,$udom);
                   10167:         my $protocol = $protocol{$homeserver};
                   10168:         $protocol = 'http' if ($protocol ne 'https');
                   10169:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10170:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10171:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10172:     } else {
                   10173:         return '/adm/notfound.html';
                   10174:     }
                   10175: }
                   10176: 
1.828     www      10177: # call with reqtype HEAD: get last modification time
                   10178: # call with reqtype GET: get the file contents
                   10179: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10180: #
1.481     raeburn  10181: sub getuploaded {
                   10182:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10183:     $uri=~s/^\///;
1.980     raeburn  10184:     my $homeserver = &homeserver($cnum,$cdom);
                   10185:     my $protocol = $protocol{$homeserver};
                   10186:     $protocol = 'http' if ($protocol ne 'https');
                   10187:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10188:     my $ua=new LWP::UserAgent;
                   10189:     my $request=new HTTP::Request($reqtype,$uri);
                   10190:     my $response=$ua->request($request);
                   10191:     $$rtncode = $response->code;
1.482     albertel 10192:     if (! $response->is_success()) {
                   10193: 	return 'failed';
                   10194:     }      
                   10195:     if ($reqtype eq 'HEAD') {
1.486     www      10196: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10197:     } elsif ($reqtype eq 'GET') {
                   10198: 	$$info = $response->content;
1.472     albertel 10199:     }
1.482     albertel 10200:     return 'ok';
1.36      albertel 10201: }
                   10202: 
1.481     raeburn  10203: sub readfile {
                   10204:     my $file = shift;
                   10205:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10206:     my $fh;
                   10207:     open($fh,"<$file");
                   10208:     my $a='';
1.800     albertel 10209:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10210:     return $a;
                   10211: }
                   10212: 
1.36      albertel 10213: sub filelocation {
1.590     banghart 10214:     my ($dir,$file) = @_;
                   10215:     my $location;
                   10216:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10217: 
                   10218:     if ($file =~ m-^/adm/-) {
                   10219: 	$file=~s-^/adm/wrapper/-/-;
                   10220: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10221:     }
1.882     albertel 10222: 
1.1139    www      10223:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10224:         $location = $file;
1.609     banghart 10225:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10226:         my ($udom,$uname,$filename)=
1.811     albertel 10227:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10228:         my $home=&homeserver($uname,$udom);
                   10229:         my $is_me=0;
                   10230:         my @ids=&current_machine_ids();
                   10231:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10232:         if ($is_me) {
1.1117    foxr     10233:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10234:         } else {
                   10235:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10236:   	      $udom.'/'.$uname.'/'.$filename;
                   10237:         }
1.882     albertel 10238:     } elsif ($file =~ m-^/adm/-) {
                   10239: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10240:     } else {
                   10241:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10242:         $file=~s:^/(res|priv)/:/:;
                   10243:         my $space=$1;
1.590     banghart 10244:         if ( !( $file =~ m:^/:) ) {
                   10245:             $location = $dir. '/'.$file;
                   10246:         } else {
1.1142    raeburn  10247:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10248:         }
1.59      albertel 10249:     }
1.590     banghart 10250:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10251:     while ($location=~m{/\.\./}) {
                   10252: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10253: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10254: 	} else {
                   10255: 	    $location=~ s{/\.\./}{/}g;
                   10256: 	}
                   10257:     } #remove dir/..
1.590     banghart 10258:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10259:     return $location;
1.46      www      10260: }
1.36      albertel 10261: 
1.46      www      10262: sub hreflocation {
                   10263:     my ($dir,$file)=@_;
1.980     raeburn  10264:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10265: 	$file=filelocation($dir,$file);
1.700     albertel 10266:     } elsif ($file=~m-^/adm/-) {
                   10267: 	$file=~s-^/adm/wrapper/-/-;
                   10268: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10269:     }
                   10270:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10271: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10272:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10273: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10274: 	        {/uploaded/$1/$2/}x;
1.46      www      10275:     }
1.913     albertel 10276:     if ($file=~ m{^/userfiles/}) {
                   10277: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10278:     }
1.462     albertel 10279:     return $file;
1.465     albertel 10280: }
                   10281: 
1.1139    www      10282: 
                   10283: 
                   10284: 
                   10285: 
1.465     albertel 10286: sub current_machine_domains {
1.853     albertel 10287:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10288: }
                   10289: 
                   10290: sub machine_domains {
                   10291:     my ($hostname) = @_;
1.465     albertel 10292:     my @domains;
1.838     albertel 10293:     my %hostname = &all_hostnames();
1.465     albertel 10294:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10295: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10296: 	if ($hostname eq $name) {
1.844     albertel 10297: 	    push(@domains,&host_domain($id));
1.465     albertel 10298: 	}
                   10299:     }
                   10300:     return @domains;
                   10301: }
                   10302: 
                   10303: sub current_machine_ids {
1.853     albertel 10304:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10305: }
                   10306: 
                   10307: sub machine_ids {
                   10308:     my ($hostname) = @_;
                   10309:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10310:     my @ids;
1.888     albertel 10311:     my %name_to_host = &all_names();
1.889     albertel 10312:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10313: 	return @{ $name_to_host{$hostname} };
                   10314:     }
                   10315:     return;
1.31      www      10316: }
                   10317: 
1.824     raeburn  10318: sub additional_machine_domains {
                   10319:     my @domains;
                   10320:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10321:     while( my $line = <$fh>) {
                   10322:         $line =~ s/\s//g;
                   10323:         push(@domains,$line);
                   10324:     }
                   10325:     return @domains;
                   10326: }
                   10327: 
                   10328: sub default_login_domain {
                   10329:     my $domain = $perlvar{'lonDefDomain'};
                   10330:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10331:     foreach my $posdom (&current_machine_domains(),
                   10332:                         &additional_machine_domains()) {
                   10333:         if (lc($posdom) eq lc($testdomain)) {
                   10334:             $domain=$posdom;
                   10335:             last;
                   10336:         }
                   10337:     }
                   10338:     return $domain;
                   10339: }
                   10340: 
1.31      www      10341: # ------------------------------------------------------------- Declutters URLs
                   10342: 
                   10343: sub declutter {
                   10344:     my $thisfn=shift;
1.569     albertel 10345:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10346:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10347:     $thisfn=~s/^\///;
1.697     albertel 10348:     $thisfn=~s|^adm/wrapper/||;
                   10349:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10350:     $thisfn=~s/^res\///;
1.1032    raeburn  10351:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10352:         $thisfn=~s/\?.+$//;
                   10353:     }
1.268     www      10354:     return $thisfn;
                   10355: }
                   10356: 
                   10357: # ------------------------------------------------------------- Clutter up URLs
                   10358: 
                   10359: sub clutter {
                   10360:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10361:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10362: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10363:        $thisfn='/res'.$thisfn; 
                   10364:     }
1.1031    raeburn  10365:     if ($thisfn !~m|^/adm|) {
                   10366: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10367: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10368: 	} else {
                   10369: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10370: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10371: 	    if ($embstyle eq 'ssi'
                   10372: 		|| ($embstyle eq 'hdn')
                   10373: 		|| ($embstyle eq 'rat')
                   10374: 		|| ($embstyle eq 'prv')
                   10375: 		|| ($embstyle eq 'ign')) {
                   10376: 		#do nothing with these
                   10377: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10378: 		|| ($embstyle eq 'emb')
                   10379: 		|| ($embstyle eq 'wrp')) {
                   10380: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10381: 	    } elsif ($embstyle eq 'unk'
                   10382: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10383: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10384: 	    } else {
1.718     www      10385: #		&logthis("Got a blank emb style");
1.695     albertel 10386: 	    }
1.694     albertel 10387: 	}
                   10388:     }
1.31      www      10389:     return $thisfn;
1.12      www      10390: }
                   10391: 
1.787     albertel 10392: sub clutter_with_no_wrapper {
                   10393:     my $uri = &clutter(shift);
                   10394:     if ($uri =~ m-^/adm/-) {
                   10395: 	$uri =~ s-^/adm/wrapper/-/-;
                   10396: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10397:     }
                   10398:     return $uri;
                   10399: }
                   10400: 
1.557     albertel 10401: sub freeze_escape {
                   10402:     my ($value)=@_;
                   10403:     if (ref($value)) {
                   10404: 	$value=&nfreeze($value);
                   10405: 	return '__FROZEN__'.&escape($value);
                   10406:     }
                   10407:     return &escape($value);
                   10408: }
                   10409: 
1.11      www      10410: 
1.557     albertel 10411: sub thaw_unescape {
                   10412:     my ($value)=@_;
                   10413:     if ($value =~ /^__FROZEN__/) {
                   10414: 	substr($value,0,10,undef);
                   10415: 	$value=&unescape($value);
                   10416: 	return &thaw($value);
                   10417:     }
                   10418:     return &unescape($value);
                   10419: }
                   10420: 
1.436     albertel 10421: sub correct_line_ends {
                   10422:     my ($result)=@_;
                   10423:     $$result =~s/\r\n/\n/mg;
                   10424:     $$result =~s/\r/\n/mg;
1.415     albertel 10425: }
1.1       albertel 10426: # ================================================================ Main Program
                   10427: 
1.184     www      10428: sub goodbye {
1.204     albertel 10429:    &logthis("Starting Shut down");
1.443     albertel 10430: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10431:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10432: #converted
1.599     albertel 10433: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10434:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10435: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10436: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10437: #1.1 only
1.870     albertel 10438: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10439: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10440: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10441: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10442:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10443:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10444:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10445:    &flushcourselogs();
                   10446:    &logthis("Shutting down");
                   10447: }
                   10448: 
1.852     albertel 10449: sub get_dns {
1.869     albertel 10450:     my ($url,$func,$ignore_cache) = @_;
                   10451:     if (!$ignore_cache) {
                   10452: 	my ($content,$cached)=
                   10453: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10454: 	if ($cached) {
                   10455: 	    &$func($content);
                   10456: 	    return;
                   10457: 	}
                   10458:     }
                   10459: 
                   10460:     my %alldns;
1.852     albertel 10461:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10462:     foreach my $dns (<$config>) {
                   10463: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10464:         my $line = $1;
                   10465:         my ($host,$protocol) = split(/:/,$line);
                   10466:         if ($protocol ne 'https') {
                   10467:             $protocol = 'http';
                   10468:         }
                   10469: 	$alldns{$host} = $protocol;
1.869     albertel 10470:     }
                   10471:     while (%alldns) {
                   10472: 	my ($dns) = keys(%alldns);
1.852     albertel 10473: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10474:         $ua->timeout(30);
1.979     raeburn  10475: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10476: 	my $response=$ua->request($request);
1.979     raeburn  10477:         delete($alldns{$dns});
1.852     albertel 10478: 	next if ($response->is_error());
                   10479: 	my @content = split("\n",$response->content);
1.869     albertel 10480: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10481: 	&$func(\@content);
1.869     albertel 10482: 	return;
1.852     albertel 10483:     }
                   10484:     close($config);
1.871     albertel 10485:     my $which = (split('/',$url))[3];
                   10486:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10487:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10488:     my @content = <$config>;
                   10489:     &$func(\@content);
                   10490:     return;
1.852     albertel 10491: }
1.327     albertel 10492: # ------------------------------------------------------------ Read domain file
                   10493: {
1.852     albertel 10494:     my $loaded;
1.846     albertel 10495:     my %domain;
                   10496: 
1.852     albertel 10497:     sub parse_domain_tab {
                   10498: 	my ($lines) = @_;
                   10499: 	foreach my $line (@$lines) {
                   10500: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10501: 
1.846     albertel 10502: 	    chomp($line);
1.852     albertel 10503: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10504: 	    my %this_domain;
                   10505: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10506: 			       'lang_def', 'city', 'longi', 'lati',
                   10507: 			       'primary') {
                   10508: 		$this_domain{$field} = shift(@elements);
                   10509: 	    }
                   10510: 	    $domain{$name} = \%this_domain;
1.852     albertel 10511: 	}
                   10512:     }
1.864     albertel 10513: 
                   10514:     sub reset_domain_info {
                   10515: 	undef($loaded);
                   10516: 	undef(%domain);
                   10517:     }
                   10518: 
1.852     albertel 10519:     sub load_domain_tab {
1.869     albertel 10520: 	my ($ignore_cache) = @_;
                   10521: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10522: 	my $fh;
                   10523: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10524: 	    my @lines = <$fh>;
                   10525: 	    &parse_domain_tab(\@lines);
1.448     albertel 10526: 	}
1.852     albertel 10527: 	close($fh);
                   10528: 	$loaded = 1;
1.327     albertel 10529:     }
1.846     albertel 10530: 
                   10531:     sub domain {
1.852     albertel 10532: 	&load_domain_tab() if (!$loaded);
                   10533: 
1.846     albertel 10534: 	my ($name,$what) = @_;
                   10535: 	return if ( !exists($domain{$name}) );
                   10536: 
                   10537: 	if (!$what) {
                   10538: 	    return $domain{$name}{'description'};
                   10539: 	}
                   10540: 	return $domain{$name}{$what};
                   10541:     }
1.974     raeburn  10542: 
                   10543:     sub domain_info {
                   10544:         &load_domain_tab() if (!$loaded);
                   10545:         return %domain;
                   10546:     }
                   10547: 
1.327     albertel 10548: }
                   10549: 
                   10550: 
1.1       albertel 10551: # ------------------------------------------------------------- Read hosts file
                   10552: {
1.838     albertel 10553:     my %hostname;
1.844     albertel 10554:     my %hostdom;
1.845     albertel 10555:     my %libserv;
1.852     albertel 10556:     my $loaded;
1.888     albertel 10557:     my %name_to_host;
1.1074    raeburn  10558:     my %internetdom;
1.1107    raeburn  10559:     my %LC_dns_serv;
1.852     albertel 10560: 
                   10561:     sub parse_hosts_tab {
                   10562: 	my ($file) = @_;
                   10563: 	foreach my $configline (@$file) {
                   10564: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10565:             chomp($configline);
                   10566: 	    if ($configline =~ /^\^/) {
                   10567:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10568:                     $LC_dns_serv{$1} = 1;
                   10569:                 }
                   10570:                 next;
                   10571:             }
1.1074    raeburn  10572: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10573: 	    $name=~s/\s//g;
                   10574: 	    if ($id && $domain && $role && $name) {
                   10575: 		$hostname{$id}=$name;
1.888     albertel 10576: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10577: 		$hostdom{$id}=$domain;
                   10578: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10579:                 if (defined($protocol)) {
                   10580:                     if ($protocol eq 'https') {
                   10581:                         $protocol{$id} = $protocol;
                   10582:                     } else {
                   10583:                         $protocol{$id} = 'http'; 
                   10584:                     }
1.968     raeburn  10585:                 } else {
1.969     raeburn  10586:                     $protocol{$id} = 'http';
1.968     raeburn  10587:                 }
1.1074    raeburn  10588:                 if (defined($intdom)) {
                   10589:                     $internetdom{$id} = $intdom;
                   10590:                 }
1.852     albertel 10591: 	    }
                   10592: 	}
                   10593:     }
1.864     albertel 10594:     
                   10595:     sub reset_hosts_info {
1.897     albertel 10596: 	&purge_remembered();
1.864     albertel 10597: 	&reset_domain_info();
                   10598: 	&reset_hosts_ip_info();
1.892     albertel 10599: 	undef(%name_to_host);
1.864     albertel 10600: 	undef(%hostname);
                   10601: 	undef(%hostdom);
                   10602: 	undef(%libserv);
                   10603: 	undef($loaded);
                   10604:     }
1.1       albertel 10605: 
1.852     albertel 10606:     sub load_hosts_tab {
1.869     albertel 10607: 	my ($ignore_cache) = @_;
                   10608: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 10609: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10610: 	my @config = <$config>;
                   10611: 	&parse_hosts_tab(\@config);
                   10612: 	close($config);
                   10613: 	$loaded=1;
1.1       albertel 10614:     }
1.852     albertel 10615: 
1.838     albertel 10616:     sub hostname {
1.852     albertel 10617: 	&load_hosts_tab() if (!$loaded);
                   10618: 
1.838     albertel 10619: 	my ($lonid) = @_;
                   10620: 	return $hostname{$lonid};
                   10621:     }
1.845     albertel 10622: 
1.838     albertel 10623:     sub all_hostnames {
1.852     albertel 10624: 	&load_hosts_tab() if (!$loaded);
                   10625: 
1.838     albertel 10626: 	return %hostname;
                   10627:     }
1.845     albertel 10628: 
1.888     albertel 10629:     sub all_names {
                   10630: 	&load_hosts_tab() if (!$loaded);
                   10631: 
                   10632: 	return %name_to_host;
                   10633:     }
                   10634: 
1.974     raeburn  10635:     sub all_host_domain {
                   10636:         &load_hosts_tab() if (!$loaded);
                   10637:         return %hostdom;
                   10638:     }
                   10639: 
1.845     albertel 10640:     sub is_library {
1.852     albertel 10641: 	&load_hosts_tab() if (!$loaded);
                   10642: 
1.845     albertel 10643: 	return exists($libserv{$_[0]});
                   10644:     }
                   10645: 
                   10646:     sub all_library {
1.852     albertel 10647: 	&load_hosts_tab() if (!$loaded);
                   10648: 
1.845     albertel 10649: 	return %libserv;
                   10650:     }
                   10651: 
1.1062    droeschl 10652:     sub unique_library {
                   10653: 	#2x reverse removes all hostnames that appear more than once
                   10654:         my %unique = reverse &all_library();
                   10655:         return reverse %unique;
                   10656:     }
                   10657: 
1.841     albertel 10658:     sub get_servers {
1.852     albertel 10659: 	&load_hosts_tab() if (!$loaded);
                   10660: 
1.841     albertel 10661: 	my ($domain,$type) = @_;
                   10662: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   10663: 	                                          : %hostname;
                   10664: 	my %result;
1.842     albertel 10665: 	if (ref($domain) eq 'ARRAY') {
                   10666: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 10667: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 10668: 		    $result{$host} = $hostname;
                   10669: 		}
                   10670: 	    }
                   10671: 	} else {
                   10672: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   10673: 		if ($hostdom{$host} eq $domain) {
                   10674: 		    $result{$host} = $hostname;
                   10675: 		}
1.841     albertel 10676: 	    }
                   10677: 	}
                   10678: 	return %result;
                   10679:     }
1.845     albertel 10680: 
1.1062    droeschl 10681:     sub get_unique_servers {
                   10682:         my %unique = reverse &get_servers(@_);
                   10683: 	return reverse %unique;
                   10684:     }
                   10685: 
1.844     albertel 10686:     sub host_domain {
1.852     albertel 10687: 	&load_hosts_tab() if (!$loaded);
                   10688: 
1.844     albertel 10689: 	my ($lonid) = @_;
                   10690: 	return $hostdom{$lonid};
                   10691:     }
                   10692: 
1.841     albertel 10693:     sub all_domains {
1.852     albertel 10694: 	&load_hosts_tab() if (!$loaded);
                   10695: 
1.841     albertel 10696: 	my %seen;
                   10697: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   10698: 	return @uniq;
                   10699:     }
1.1074    raeburn  10700: 
                   10701:     sub internet_dom {
                   10702:         &load_hosts_tab() if (!$loaded);
                   10703: 
                   10704:         my ($lonid) = @_;
                   10705:         return $internetdom{$lonid};
                   10706:     }
1.1107    raeburn  10707: 
                   10708:     sub is_LC_dns {
                   10709:         &load_hosts_tab() if (!$loaded);
                   10710: 
                   10711:         my ($hostname) = @_;
                   10712:         return exists($LC_dns_serv{$hostname});
                   10713:     }
                   10714: 
1.1       albertel 10715: }
                   10716: 
1.847     albertel 10717: { 
                   10718:     my %iphost;
1.856     albertel 10719:     my %name_to_ip;
                   10720:     my %lonid_to_ip;
1.869     albertel 10721: 
1.847     albertel 10722:     sub get_hosts_from_ip {
                   10723: 	my ($ip) = @_;
                   10724: 	my %iphosts = &get_iphost();
                   10725: 	if (ref($iphosts{$ip})) {
                   10726: 	    return @{$iphosts{$ip}};
                   10727: 	}
                   10728: 	return;
1.839     albertel 10729:     }
1.864     albertel 10730:     
                   10731:     sub reset_hosts_ip_info {
                   10732: 	undef(%iphost);
                   10733: 	undef(%name_to_ip);
                   10734: 	undef(%lonid_to_ip);
                   10735:     }
1.856     albertel 10736: 
                   10737:     sub get_host_ip {
                   10738: 	my ($lonid) = @_;
                   10739: 	if (exists($lonid_to_ip{$lonid})) {
                   10740: 	    return $lonid_to_ip{$lonid};
                   10741: 	}
                   10742: 	my $name=&hostname($lonid);
                   10743:    	my $ip = gethostbyname($name);
                   10744: 	return if (!$ip || length($ip) ne 4);
                   10745: 	$ip=inet_ntoa($ip);
                   10746: 	$name_to_ip{$name}   = $ip;
                   10747: 	$lonid_to_ip{$lonid} = $ip;
                   10748: 	return $ip;
                   10749:     }
1.847     albertel 10750:     
                   10751:     sub get_iphost {
1.869     albertel 10752: 	my ($ignore_cache) = @_;
1.894     albertel 10753: 
1.869     albertel 10754: 	if (!$ignore_cache) {
                   10755: 	    if (%iphost) {
                   10756: 		return %iphost;
                   10757: 	    }
                   10758: 	    my ($ip_info,$cached)=
                   10759: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   10760: 	    if ($cached) {
                   10761: 		%iphost      = %{$ip_info->[0]};
                   10762: 		%name_to_ip  = %{$ip_info->[1]};
                   10763: 		%lonid_to_ip = %{$ip_info->[2]};
                   10764: 		return %iphost;
                   10765: 	    }
                   10766: 	}
1.894     albertel 10767: 
                   10768: 	# get yesterday's info for fallback
                   10769: 	my %old_name_to_ip;
                   10770: 	my ($ip_info,$cached)=
                   10771: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   10772: 	if ($cached) {
                   10773: 	    %old_name_to_ip = %{$ip_info->[1]};
                   10774: 	}
                   10775: 
1.888     albertel 10776: 	my %name_to_host = &all_names();
                   10777: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 10778: 	    my $ip;
                   10779: 	    if (!exists($name_to_ip{$name})) {
                   10780: 		$ip = gethostbyname($name);
                   10781: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 10782: 		    if (defined($old_name_to_ip{$name})) {
                   10783: 			$ip = $old_name_to_ip{$name};
                   10784: 			&logthis("Can't find $name defaulting to old $ip");
                   10785: 		    } else {
                   10786: 			&logthis("Name $name no IP found");
                   10787: 			next;
                   10788: 		    }
                   10789: 		} else {
                   10790: 		    $ip=inet_ntoa($ip);
1.847     albertel 10791: 		}
                   10792: 		$name_to_ip{$name} = $ip;
                   10793: 	    } else {
                   10794: 		$ip = $name_to_ip{$name};
1.653     albertel 10795: 	    }
1.888     albertel 10796: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   10797: 		$lonid_to_ip{$id} = $ip;
                   10798: 	    }
                   10799: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 10800: 	}
1.869     albertel 10801: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   10802: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 10803: 				      48*60*60);
1.869     albertel 10804: 
1.847     albertel 10805: 	return %iphost;
1.598     albertel 10806:     }
                   10807: 
1.992     raeburn  10808:     #
                   10809:     #  Given a DNS returns the loncapa host name for that DNS 
                   10810:     # 
                   10811:     sub host_from_dns {
                   10812:         my ($dns) = @_;
                   10813:         my @hosts;
                   10814:         my $ip;
                   10815: 
1.993     raeburn  10816:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  10817:             $ip = $name_to_ip{$dns};
                   10818:         }
                   10819:         if (!$ip) {
                   10820:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   10821:             if (length($ip) == 4) { 
                   10822: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   10823:             }
                   10824:         }
                   10825:         if ($ip) {
                   10826: 	    @hosts = get_hosts_from_ip($ip);
                   10827: 	    return $hosts[0];
                   10828:         }
                   10829:         return undef;
1.986     foxr     10830:     }
1.992     raeburn  10831: 
1.1074    raeburn  10832:     sub get_internet_names {
                   10833:         my ($lonid) = @_;
                   10834:         return if ($lonid eq '');
                   10835:         my ($idnref,$cached)=
                   10836:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   10837:         if ($cached) {
                   10838:             return $idnref;
                   10839:         }
                   10840:         my $ip = &get_host_ip($lonid);
                   10841:         my @hosts = &get_hosts_from_ip($ip);
                   10842:         my %iphost = &get_iphost();
                   10843:         my (@idns,%seen);
                   10844:         foreach my $id (@hosts) {
                   10845:             my $dom = &host_domain($id);
                   10846:             my $prim_id = &domain($dom,'primary');
                   10847:             my $prim_ip = &get_host_ip($prim_id);
                   10848:             next if ($seen{$prim_ip});
                   10849:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   10850:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   10851:                     my $intdom = &internet_dom($id);
                   10852:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   10853:                         push(@idns,$intdom);
                   10854:                     }
                   10855:                 }
                   10856:             }
                   10857:             $seen{$prim_ip} = 1;
                   10858:         }
                   10859:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   10860:     }
                   10861: 
1.986     foxr     10862: }
                   10863: 
1.1079    raeburn  10864: sub all_loncaparevs {
                   10865:     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);
                   10866: }
                   10867: 
1.862     albertel 10868: BEGIN {
                   10869: 
                   10870: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   10871:     unless ($readit) {
                   10872: {
                   10873:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   10874:     %perlvar = (%perlvar,%{$configvars});
                   10875: }
                   10876: 
                   10877: 
1.1       albertel 10878: # ------------------------------------------------------ Read spare server file
                   10879: {
1.448     albertel 10880:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 10881: 
                   10882:     while (my $configline=<$config>) {
                   10883:        chomp($configline);
1.284     matthew  10884:        if ($configline) {
1.784     albertel 10885: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 10886: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 10887: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 10888:        }
                   10889:     }
1.448     albertel 10890:     close($config);
1.1       albertel 10891: }
1.11      www      10892: # ------------------------------------------------------------ Read permissions
                   10893: {
1.448     albertel 10894:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      10895: 
                   10896:     while (my $configline=<$config>) {
1.448     albertel 10897: 	chomp($configline);
                   10898: 	if ($configline) {
                   10899: 	    my ($role,$perm)=split(/ /,$configline);
                   10900: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   10901: 	}
1.11      www      10902:     }
1.448     albertel 10903:     close($config);
1.11      www      10904: }
                   10905: 
                   10906: # -------------------------------------------- Read plain texts for permissions
                   10907: {
1.448     albertel 10908:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      10909: 
                   10910:     while (my $configline=<$config>) {
1.448     albertel 10911: 	chomp($configline);
                   10912: 	if ($configline) {
1.742     raeburn  10913: 	    my ($short,@plain)=split(/:/,$configline);
                   10914:             %{$prp{$short}} = ();
                   10915: 	    if (@plain > 0) {
                   10916:                 $prp{$short}{'std'} = $plain[0];
                   10917:                 for (my $i=1; $i<@plain; $i++) {
                   10918:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   10919:                 }
                   10920:             }
1.448     albertel 10921: 	}
1.135     www      10922:     }
1.448     albertel 10923:     close($config);
1.135     www      10924: }
                   10925: 
                   10926: # ---------------------------------------------------------- Read package table
                   10927: {
1.448     albertel 10928:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      10929: 
                   10930:     while (my $configline=<$config>) {
1.483     albertel 10931: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 10932: 	chomp($configline);
                   10933: 	my ($short,$plain)=split(/:/,$configline);
                   10934: 	my ($pack,$name)=split(/\&/,$short);
                   10935: 	if ($plain ne '') {
                   10936: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   10937: 	    $packagetab{$short}=$plain; 
                   10938: 	}
1.11      www      10939:     }
1.448     albertel 10940:     close($config);
1.329     matthew  10941: }
                   10942: 
1.1073    raeburn  10943: # ---------------------------------------------------------- Read loncaparev table
                   10944: {
                   10945:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   10946:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   10947:             while (my $configline=<$config>) {
                   10948:                 chomp($configline);
                   10949:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   10950:                 $loncaparevs{$hostid}=$loncaparev;
                   10951:             }
                   10952:             close($config);
                   10953:         }
                   10954:     }
                   10955: }
                   10956: 
1.1074    raeburn  10957: # ---------------------------------------------------------- Read serverhostID table
                   10958: {
                   10959:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   10960:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   10961:             while (my $configline=<$config>) {
                   10962:                 chomp($configline);
                   10963:                 my ($name,$id)=split(/:/,$configline);
                   10964:                 $serverhomeIDs{$name}=$id;
                   10965:             }
                   10966:             close($config);
                   10967:         }
                   10968:     }
                   10969: }
                   10970: 
1.1079    raeburn  10971: {
                   10972:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   10973:     if (-e $file) {
                   10974:         my $parser = HTML::LCParser->new($file);
                   10975:         while (my $token = $parser->get_token()) {
                   10976:             if ($token->[0] eq 'S') {
                   10977:                 my $item = $token->[1];
                   10978:                 my $name = $token->[2]{'name'};
                   10979:                 my $value = $token->[2]{'value'};
                   10980:                 if ($item ne '' && $name ne '' && $value ne '') {
                   10981:                     my $release = $parser->get_text();
                   10982:                     $release =~ s/(^\s*|\s*$ )//gx;
                   10983:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   10984:                 }
                   10985:             }
                   10986:         }
                   10987:     }
1.1073    raeburn  10988: }
                   10989: 
1.1138    raeburn  10990: # ---------------------------------------------------------- Read managers table
                   10991: {
                   10992:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   10993:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   10994:             while (my $configline=<$config>) {
                   10995:                 chomp($configline);
                   10996:                 next if ($configline =~ /^\#/);
                   10997:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   10998:                     $managerstab{$configline} = 1;
                   10999:                 }
                   11000:             }
                   11001:             close($config);
                   11002:         }
                   11003:     }
                   11004: }
                   11005: 
1.329     matthew  11006: # ------------- set up temporary directory
                   11007: {
1.1117    foxr     11008:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11009: 
1.11      www      11010: }
                   11011: 
1.794     albertel 11012: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11013: 				'compress_threshold'=> 20_000,
                   11014:  			        });
1.185     www      11015: 
1.281     www      11016: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11017: $dumpcount=0;
1.958     www      11018: $locknum=0;
1.22      www      11019: 
1.163     harris41 11020: &logtouch();
1.672     albertel 11021: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11022: $readit=1;
1.564     albertel 11023:     {
                   11024: 	use integer;
                   11025: 	my $test=(2**32)+1;
1.568     albertel 11026: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11027: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11028:     }
1.195     www      11029: }
1.1       albertel 11030: }
1.179     www      11031: 
1.1       albertel 11032: 1;
1.191     harris41 11033: __END__
                   11034: 
1.243     albertel 11035: =pod
                   11036: 
1.191     harris41 11037: =head1 NAME
                   11038: 
1.243     albertel 11039: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11040: 
                   11041: =head1 SYNOPSIS
                   11042: 
1.243     albertel 11043: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11044: 
                   11045:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11046: 
1.243     albertel 11047: Common parameters:
                   11048: 
                   11049: =over 4
                   11050: 
                   11051: =item *
                   11052: 
                   11053: $uname : an internal username (if $cname expecting a course Id specifically)
                   11054: 
                   11055: =item *
                   11056: 
                   11057: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11058: 
                   11059: =item *
                   11060: 
                   11061: $symb : a resource instance identifier
                   11062: 
                   11063: =item *
                   11064: 
                   11065: $namespace : the name of a .db file that contains the data needed or
                   11066: being set.
                   11067: 
                   11068: =back
                   11069: 
1.394     bowersj2 11070: =head1 OVERVIEW
1.191     harris41 11071: 
1.394     bowersj2 11072: lonnet provides subroutines which interact with the
                   11073: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11074: about classes, users, and resources.
1.243     albertel 11075: 
                   11076: For many of these objects you can also use this to store data about
                   11077: them or modify them in various ways.
1.191     harris41 11078: 
1.394     bowersj2 11079: =head2 Symbs
1.191     harris41 11080: 
1.394     bowersj2 11081: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11082: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11083: map, the resource number of the resource in the map, and the URL of
                   11084: the resource itself. The latter is somewhat redundant, but might help
                   11085: if maps change.
                   11086: 
                   11087: An example is
                   11088: 
                   11089:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11090: 
                   11091: The respective map entry is
                   11092: 
                   11093:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11094:   title="Problem 2">
                   11095:  </resource>
                   11096: 
                   11097: Symbs are used by the random number generator, as well as to store and
                   11098: restore data specific to a certain instance of for example a problem.
                   11099: 
                   11100: =head2 Storing And Retrieving Data
                   11101: 
                   11102: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11103: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11104: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11105: is is the non-critical message twin of cstore. These functions are for
                   11106: handlers to store a perl hash to a user's permanent data space in an
                   11107: easy manner, and to retrieve it again on another call. It is expected
                   11108: that a handler would use this once at the beginning to retrieve data,
                   11109: and then again once at the end to send only the new data back.
                   11110: 
                   11111: The data is stored in the user's data directory on the user's
                   11112: homeserver under the ID of the course.
                   11113: 
                   11114: The hash that is returned by restore will have all of the previous
                   11115: value for all of the elements of the hash.
                   11116: 
                   11117: Example:
                   11118: 
                   11119:  #creating a hash
                   11120:  my %hash;
                   11121:  $hash{'foo'}='bar';
                   11122: 
                   11123:  #storing it
                   11124:  &Apache::lonnet::cstore(\%hash);
                   11125: 
                   11126:  #changing a value
                   11127:  $hash{'foo'}='notbar';
                   11128: 
                   11129:  #adding a new value
                   11130:  $hash{'bar'}='foo';
                   11131:  &Apache::lonnet::cstore(\%hash);
                   11132: 
                   11133:  #retrieving the hash
                   11134:  my %history=&Apache::lonnet::restore();
                   11135: 
                   11136:  #print the hash
                   11137:  foreach my $key (sort(keys(%history))) {
                   11138:    print("\%history{$key} = $history{$key}");
                   11139:  }
                   11140: 
                   11141: Will print out:
1.191     harris41 11142: 
1.394     bowersj2 11143:  %history{1:foo} = bar
                   11144:  %history{1:keys} = foo:timestamp
                   11145:  %history{1:timestamp} = 990455579
                   11146:  %history{2:bar} = foo
                   11147:  %history{2:foo} = notbar
                   11148:  %history{2:keys} = foo:bar:timestamp
                   11149:  %history{2:timestamp} = 990455580
                   11150:  %history{bar} = foo
                   11151:  %history{foo} = notbar
                   11152:  %history{timestamp} = 990455580
                   11153:  %history{version} = 2
                   11154: 
                   11155: Note that the special hash entries C<keys>, C<version> and
                   11156: C<timestamp> were added to the hash. C<version> will be equal to the
                   11157: total number of versions of the data that have been stored. The
                   11158: C<timestamp> attribute will be the UNIX time the hash was
                   11159: stored. C<keys> is available in every historical section to list which
                   11160: keys were added or changed at a specific historical revision of a
                   11161: hash.
                   11162: 
                   11163: B<Warning>: do not store the hash that restore returns directly. This
                   11164: will cause a mess since it will restore the historical keys as if the
                   11165: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11166: 
1.394     bowersj2 11167: Calling convention:
1.191     harris41 11168: 
1.394     bowersj2 11169:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11170:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11171: 
1.394     bowersj2 11172: For more detailed information, see lonnet specific documentation.
1.191     harris41 11173: 
1.394     bowersj2 11174: =head1 RETURN MESSAGES
1.191     harris41 11175: 
1.394     bowersj2 11176: =over 4
1.191     harris41 11177: 
1.394     bowersj2 11178: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11179: 
1.394     bowersj2 11180: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11181: when the connection is brought back up
1.191     harris41 11182: 
1.394     bowersj2 11183: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11184: for later delivery
1.191     harris41 11185: 
1.967     bisitz   11186: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11187: 
1.394     bowersj2 11188: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11189: that was requested
1.191     harris41 11190: 
1.243     albertel 11191: =back
1.191     harris41 11192: 
1.243     albertel 11193: =head1 PUBLIC SUBROUTINES
1.191     harris41 11194: 
1.243     albertel 11195: =head2 Session Environment Functions
1.191     harris41 11196: 
1.243     albertel 11197: =over 4
1.191     harris41 11198: 
1.394     bowersj2 11199: =item * 
                   11200: X<appenv()>
1.949     raeburn  11201: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11202: the user envirnoment file, and will be restored for each access this
1.620     albertel 11203: user makes during this session, also modifies the %env for the current
1.949     raeburn  11204: process. Optional rolesarrayref - if defined contains a reference to an array
                   11205: of roles which are exempt from the restriction on modifying user.role entries 
                   11206: in the user's environment.db and in %env.    
1.191     harris41 11207: 
                   11208: =item *
1.394     bowersj2 11209: X<delenv()>
1.987     raeburn  11210: B<delenv($delthis,$regexp)>: removes all items from the session
                   11211: environment file that begin with $delthis. If the 
                   11212: optional second arg - $regexp - is true, $delthis is treated as a 
                   11213: regular expression, otherwise \Q$delthis\E is used. 
                   11214: The values are also deleted from the current processes %env.
1.191     harris41 11215: 
1.795     albertel 11216: =item * get_env_multiple($name) 
                   11217: 
                   11218: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11219: values may be defined and end up as an array ref.
                   11220: 
                   11221: returns an array of values
                   11222: 
1.243     albertel 11223: =back
                   11224: 
                   11225: =head2 User Information
1.191     harris41 11226: 
1.243     albertel 11227: =over 4
1.191     harris41 11228: 
                   11229: =item *
1.394     bowersj2 11230: X<queryauthenticate()>
                   11231: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11232: authentication scheme
                   11233: 
                   11234: =item *
1.394     bowersj2 11235: X<authenticate()>
1.1073    raeburn  11236: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11237: authenticate user from domain's lib servers (first use the current
                   11238: one). C<$upass> should be the users password.
1.1073    raeburn  11239: $checkdefauth is optional (value is 1 if a check should be made to
                   11240:    authenticate user using default authentication method, and allow
                   11241:    account creation if username does not have account in the domain).
                   11242: $clientcancheckhost is optional (value is 1 if checking whether the
                   11243:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11244: 
                   11245: =item *
1.394     bowersj2 11246: X<homeserver()>
                   11247: B<homeserver($uname,$udom)>: find the server which has
                   11248: the user's directory and files (there must be only one), this caches
                   11249: the answer, and also caches if there is a borken connection.
1.191     harris41 11250: 
                   11251: =item *
1.394     bowersj2 11252: X<idget()>
                   11253: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11254: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11255: username, and only 1 username per ID in a specific domain) (returns
                   11256: hash: id=>name,id=>name)
1.191     harris41 11257: 
                   11258: =item *
1.394     bowersj2 11259: X<idrget()>
                   11260: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11261: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11262: 
                   11263: =item *
1.394     bowersj2 11264: X<idput()>
                   11265: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11266: 
                   11267: =item *
1.394     bowersj2 11268: X<rolesinit()>
                   11269: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243     albertel 11270: 
                   11271: =item *
1.551     albertel 11272: X<getsection()>
                   11273: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11274: course $cname, return section name/number or '' for "not in course"
                   11275: and '-1' for "no section"
                   11276: 
                   11277: =item *
1.394     bowersj2 11278: X<userenvironment()>
                   11279: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11280: passed in @what from the requested user's environment, returns a hash
                   11281: 
1.858     raeburn  11282: =item * 
                   11283: X<userlog_query()>
1.859     albertel 11284: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11285: activity.log file. %filters defines filters applied when parsing the
                   11286: log file. These can be start or end timestamps, or the type of action
                   11287: - log to look for Login or Logout events, check for Checkin or
                   11288: Checkout, role for role selection. The response is in the form
                   11289: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11290: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11291: 
1.243     albertel 11292: =back
                   11293: 
                   11294: =head2 User Roles
                   11295: 
                   11296: =over 4
                   11297: 
                   11298: =item *
                   11299: 
1.810     raeburn  11300: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11301:  F: full access
                   11302:  U,I,K: authentication modes (cxx only)
                   11303:  '': forbidden
                   11304:  1: user needs to choose course
                   11305:  2: browse allowed
1.766     albertel 11306:  A: passphrase authentication needed
1.243     albertel 11307: 
                   11308: =item *
                   11309: 
                   11310: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11311: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11312: and course level
                   11313: 
                   11314: =item *
                   11315: 
1.988     raeburn  11316: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11317: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11318: $type is Course (default) or Community.
1.988     raeburn  11319: If $forcedefault evaluates to true, text returned will be default 
                   11320: text for $type. Otherwise, if this is a course, the text returned 
                   11321: will be a custom name for the role (if defined in the course's 
                   11322: environment).  If no custom name is defined the default is returned.
                   11323:    
1.832     raeburn  11324: =item *
                   11325: 
1.935     raeburn  11326: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11327: All arguments are optional. Returns a hash of a roles, either for
                   11328: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11329: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11330: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11331: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11332: For each key, value is set to colon-separated start and end times for
                   11333: the role.  If no username and domain are specified, will default to
1.934     raeburn  11334: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11335: of role statuses (active, future or previous), roles 
                   11336: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11337: to restrict the list of roles reported. If no array ref is 
                   11338: provided for types, will default to return only active roles.
1.834     albertel 11339: 
1.243     albertel 11340: =back
                   11341: 
                   11342: =head2 User Modification
                   11343: 
                   11344: =over 4
                   11345: 
                   11346: =item *
                   11347: 
1.957     raeburn  11348: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11349: user for the level given by URL.  Optional start and end dates (leave empty
                   11350: string or zero for "no date")
1.191     harris41 11351: 
                   11352: =item *
                   11353: 
1.243     albertel 11354: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11355: change a users, password, possible return values are: ok,
                   11356: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11357: refused
1.191     harris41 11358: 
                   11359: =item *
                   11360: 
1.243     albertel 11361: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11362: 
                   11363: =item *
                   11364: 
1.1058    raeburn  11365: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11366:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11367: 
                   11368: will update user information (firstname,middlename,lastname,generation,
                   11369: permanentemail), and if forceid is true, student/employee ID also.
                   11370: A user's institutional affiliation(s) can also be updated.
                   11371: User information fields will not be overwritten with empty entries 
                   11372: unless the field is included in the $candelete array reference.
                   11373: This array is included when a single user is modified via "Manage Users",
                   11374: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11375: 
                   11376: =item *
                   11377: 
1.286     matthew  11378: modifystudent
                   11379: 
1.957     raeburn  11380: modify a student's enrollment and identification information.
1.286     matthew  11381: The course id is resolved based on the current users environment.  
                   11382: This means the envoking user must be a course coordinator or otherwise
                   11383: associated with a course.
                   11384: 
1.297     matthew  11385: This call is essentially a wrapper for lonnet::modifyuser and
                   11386: lonnet::modify_student_enrollment
1.286     matthew  11387: 
                   11388: Inputs: 
                   11389: 
                   11390: =over 4
                   11391: 
1.957     raeburn  11392: =item B<$udom> Student's loncapa domain
1.286     matthew  11393: 
1.957     raeburn  11394: =item B<$uname> Student's loncapa login name
1.286     matthew  11395: 
1.964     bisitz   11396: =item B<$uid> Student/Employee ID
1.286     matthew  11397: 
1.957     raeburn  11398: =item B<$umode> Student's authentication mode
1.286     matthew  11399: 
1.957     raeburn  11400: =item B<$upass> Student's password
1.286     matthew  11401: 
1.957     raeburn  11402: =item B<$first> Student's first name
1.286     matthew  11403: 
1.957     raeburn  11404: =item B<$middle> Student's middle name
1.286     matthew  11405: 
1.957     raeburn  11406: =item B<$last> Student's last name
1.286     matthew  11407: 
1.957     raeburn  11408: =item B<$gene> Student's generation
1.286     matthew  11409: 
1.957     raeburn  11410: =item B<$usec> Student's section in course
1.286     matthew  11411: 
                   11412: =item B<$end> Unix time of the roles expiration
                   11413: 
                   11414: =item B<$start> Unix time of the roles start date
                   11415: 
                   11416: =item B<$forceid> If defined, allow $uid to be changed
                   11417: 
                   11418: =item B<$desiredhome> server to use as home server for student
                   11419: 
1.957     raeburn  11420: =item B<$email> Student's permanent e-mail address
                   11421: 
                   11422: =item B<$type> Type of enrollment (auto or manual)
                   11423: 
1.963     raeburn  11424: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11425: 
                   11426: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11427: 
1.963     raeburn  11428: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11429: 
1.963     raeburn  11430: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11431: 
1.963     raeburn  11432: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11433: 
1.286     matthew  11434: =back
1.297     matthew  11435: 
                   11436: =item *
                   11437: 
                   11438: modify_student_enrollment
                   11439: 
                   11440: Change a students enrollment status in a class.  The environment variable
                   11441: 'role.request.course' must be defined for this function to proceed.
                   11442: 
                   11443: Inputs:
                   11444: 
                   11445: =over 4
                   11446: 
                   11447: =item $udom, students domain
                   11448: 
                   11449: =item $uname, students name
                   11450: 
                   11451: =item $uid, students user id
                   11452: 
                   11453: =item $first, students first name
                   11454: 
                   11455: =item $middle
                   11456: 
                   11457: =item $last
                   11458: 
                   11459: =item $gene
                   11460: 
                   11461: =item $usec
                   11462: 
                   11463: =item $end
                   11464: 
                   11465: =item $start
                   11466: 
1.957     raeburn  11467: =item $type
                   11468: 
                   11469: =item $locktype
                   11470: 
                   11471: =item $cid
                   11472: 
                   11473: =item $selfenroll
                   11474: 
                   11475: =item $context
                   11476: 
1.297     matthew  11477: =back
                   11478: 
1.191     harris41 11479: 
                   11480: =item *
                   11481: 
1.243     albertel 11482: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11483: custom role; give a custom role to a user for the level given by URL.  Specify
                   11484: name and domain of role author, and role name
1.191     harris41 11485: 
                   11486: =item *
                   11487: 
1.243     albertel 11488: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11489: 
                   11490: =item *
                   11491: 
1.243     albertel 11492: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11493: 
                   11494: =back
                   11495: 
                   11496: =head2 Course Infomation
                   11497: 
                   11498: =over 4
1.191     harris41 11499: 
                   11500: =item *
                   11501: 
1.1118    foxr     11502: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11503: specified course id, including all environment settings for the
                   11504: course, the description of the course will be in the hash under the
                   11505: key 'description'
1.191     harris41 11506: 
1.1118    foxr     11507: $options is an optional parameter that if supplied is a hash reference that controls
                   11508: what how this function works.  It has the following key/values:
                   11509: 
                   11510: =over 4
                   11511: 
                   11512: =item freshen_cache
                   11513: 
                   11514: If defined, and the environment cache for the course is valid, it is 
                   11515: returned in the returned hash.
                   11516: 
                   11517: =item one_time
                   11518: 
                   11519: If defined, the last cache time is set to _now_
                   11520: 
                   11521: =item user
                   11522: 
                   11523: If defined, the supplied username is used instead of the current user.
                   11524: 
                   11525: 
                   11526: =back
                   11527: 
1.191     harris41 11528: =item *
                   11529: 
1.624     albertel 11530: resdata($name,$domain,$type,@which) : request for current parameter
                   11531: setting for a specific $type, where $type is either 'course' or 'user',
                   11532: @what should be a list of parameters to ask about. This routine caches
                   11533: answers for 5 minutes.
1.243     albertel 11534: 
1.877     foxr     11535: =item *
                   11536: 
                   11537: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11538: data base, returning a hash that is keyed by the resource name and has
                   11539: values that are the resource value.  I believe that the timestamps and
                   11540: versions are also returned.
                   11541: 
                   11542: 
1.243     albertel 11543: =back
                   11544: 
                   11545: =head2 Course Modification
                   11546: 
                   11547: =over 4
1.191     harris41 11548: 
                   11549: =item *
                   11550: 
1.243     albertel 11551: writecoursepref($courseid,%prefs) : write preferences (environment
                   11552: database) for a course
1.191     harris41 11553: 
                   11554: =item *
                   11555: 
1.1011    raeburn  11556: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11557: 
                   11558: =item *
                   11559: 
1.1038    raeburn  11560: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11561: 
                   11562: =back
                   11563: 
                   11564: =head2 Resource Subroutines
                   11565: 
                   11566: =over 4
1.191     harris41 11567: 
                   11568: =item *
                   11569: 
1.243     albertel 11570: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 11571: 
                   11572: =item *
                   11573: 
1.243     albertel 11574: repcopy($filename) : subscribes to the requested file, and attempts to
                   11575: replicate from the owning library server, Might return
1.607     raeburn  11576: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   11577: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 11578: resource. Expects the local filesystem pathname
                   11579: (/home/httpd/html/res/....)
                   11580: 
                   11581: =back
                   11582: 
                   11583: =head2 Resource Information
                   11584: 
                   11585: =over 4
1.191     harris41 11586: 
                   11587: =item *
                   11588: 
1.243     albertel 11589: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   11590: a vairety of different possible values, $varname should be a request
                   11591: string, and the other parameters can be used to specify who and what
                   11592: one is asking about.
                   11593: 
                   11594: Possible values for $varname are environment.lastname (or other item
                   11595: from the envirnment hash), user.name (or someother aspect about the
                   11596: user), resource.0.maxtries (or some other part and parameter of a
                   11597: resource)
1.204     albertel 11598: 
                   11599: =item *
                   11600: 
1.243     albertel 11601: directcondval($number) : get current value of a condition; reads from a state
                   11602: string
1.204     albertel 11603: 
                   11604: =item *
                   11605: 
1.243     albertel 11606: condval($condidx) : value of condition index based on state
1.204     albertel 11607: 
                   11608: =item *
                   11609: 
1.243     albertel 11610: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   11611: resource's metadata, $what should be either a specific key, or either
                   11612: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   11613: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   11614: 
                   11615: this function automatically caches all requests
1.191     harris41 11616: 
                   11617: =item *
                   11618: 
1.243     albertel 11619: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   11620: network of library servers; returns file handle of where SQL and regex results
                   11621: will be stored for query
1.191     harris41 11622: 
                   11623: =item *
                   11624: 
1.243     albertel 11625: symbread($filename) : return symbolic list entry (filename argument optional);
                   11626: returns the data handle
1.191     harris41 11627: 
                   11628: =item *
                   11629: 
1.243     albertel 11630: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 11631: a possible symb for the URL in $thisfn, and if is an encryypted
                   11632: resource that the user accessed using /enc/ returns a 1 on success, 0
                   11633: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 11634: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 11635: 
1.191     harris41 11636: 
                   11637: =item *
                   11638: 
1.243     albertel 11639: symbclean($symb) : removes versions numbers from a symb, returns the
                   11640: cleaned symb
1.191     harris41 11641: 
                   11642: =item *
                   11643: 
1.243     albertel 11644: is_on_map($uri) : checks if the $uri is somewhere on the current
                   11645: course map, user must be in a course for it to work.
1.191     harris41 11646: 
                   11647: =item *
                   11648: 
1.243     albertel 11649: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 11650: 
                   11651: =item *
                   11652: 
1.243     albertel 11653: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   11654: a random seed, all arguments are optional, if they aren't sent it uses the
                   11655: environment to derive them. Note: if symb isn't sent and it can't get one
                   11656: from &symbread it will use the current time as its return value
1.191     harris41 11657: 
                   11658: =item *
                   11659: 
1.243     albertel 11660: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   11661: unfakeable, receipt
1.191     harris41 11662: 
                   11663: =item *
                   11664: 
1.620     albertel 11665: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 11666: 
                   11667: =item *
                   11668: 
1.243     albertel 11669: countacc($url) : count the number of accesses to a given URL
1.191     harris41 11670: 
                   11671: =item *
                   11672: 
1.243     albertel 11673: 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 11674: 
                   11675: =item *
                   11676: 
1.243     albertel 11677: 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 11678: 
                   11679: =item *
                   11680: 
1.243     albertel 11681: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 11682: 
                   11683: =item *
                   11684: 
1.243     albertel 11685: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   11686: forcing spreadsheet to reevaluate the resource scores next time.
                   11687: 
                   11688: =back
                   11689: 
                   11690: =head2 Storing/Retreiving Data
                   11691: 
                   11692: =over 4
1.191     harris41 11693: 
                   11694: =item *
                   11695: 
1.243     albertel 11696: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   11697: for this url; hashref needs to be given and should be a \%hashname; the
                   11698: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 11699: be derived from the env
1.191     harris41 11700: 
                   11701: =item *
                   11702: 
1.243     albertel 11703: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   11704: uses critical subroutine
1.191     harris41 11705: 
                   11706: =item *
                   11707: 
1.243     albertel 11708: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   11709: all args are optional
1.191     harris41 11710: 
                   11711: =item *
                   11712: 
1.717     albertel 11713: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   11714: dumps the complete (or key matching regexp) namespace into a hash
                   11715: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   11716: normally &store()ed into
                   11717: 
                   11718: $range should be either an integer '100' (give me the first 100
                   11719:                                            matching records)
                   11720:               or be  two integers sperated by a - with no spaces
                   11721:                  '30-50' (give me the 30th through the 50th matching
                   11722:                           records)
                   11723: 
                   11724: 
                   11725: =item *
                   11726: 
                   11727: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   11728: replaces a &store() version of data with a replacement set of data
                   11729: for a particular resource in a namespace passed in the $storehash hash 
                   11730: reference
                   11731: 
                   11732: =item *
                   11733: 
1.243     albertel 11734: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   11735: works very similar to store/cstore, but all data is stored in a
                   11736: temporary location and can be reset using tmpreset, $storehash should
                   11737: be a hash reference, returns nothing on success
1.191     harris41 11738: 
                   11739: =item *
                   11740: 
1.243     albertel 11741: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   11742: similar to restore, but all data is stored in a temporary location and
                   11743: can be reset using tmpreset. Returns a hash of values on success,
                   11744: error string otherwise.
1.191     harris41 11745: 
                   11746: =item *
                   11747: 
1.243     albertel 11748: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   11749: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 11750: 
                   11751: =item *
                   11752: 
1.243     albertel 11753: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11754: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 11755: 
                   11756: =item *
                   11757: 
1.243     albertel 11758: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   11759: namesp ($udom and $uname are optional)
1.191     harris41 11760: 
                   11761: =item *
                   11762: 
1.702     albertel 11763: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 11764: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 11765: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  11766: 
1.702     albertel 11767: $range should be either an integer '100' (give me the first 100
                   11768:                                            matching records)
                   11769:               or be  two integers sperated by a - with no spaces
                   11770:                  '30-50' (give me the 30th through the 50th matching
                   11771:                           records)
1.449     matthew  11772: =item *
                   11773: 
                   11774: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   11775: $store can be a scalar, an array reference, or if the amount to be 
                   11776: incremented is > 1, a hash reference.
                   11777: 
                   11778: ($udom and $uname are optional)
1.191     harris41 11779: 
                   11780: =item *
                   11781: 
1.243     albertel 11782: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   11783: ($udom and $uname are optional)
1.191     harris41 11784: 
                   11785: =item *
                   11786: 
1.243     albertel 11787: cput($namespace,$storehash,$udom,$uname) : critical put
                   11788: ($udom and $uname are optional)
1.191     harris41 11789: 
                   11790: =item *
                   11791: 
1.748     albertel 11792: newput($namespace,$storehash,$udom,$uname) :
                   11793: 
                   11794: Attempts to store the items in the $storehash, but only if they don't
                   11795: currently exist, if this succeeds you can be certain that you have 
                   11796: successfully created a new key value pair in the $namespace db.
                   11797: 
                   11798: 
                   11799: Args:
                   11800:  $namespace: name of database to store values to
                   11801:  $storehash: hashref to store to the db
                   11802:  $udom: (optional) domain of user containing the db
                   11803:  $uname: (optional) name of user caontaining the db
                   11804: 
                   11805: Returns:
                   11806:  'ok' -> succeeded in storing all keys of $storehash
                   11807:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   11808:                         least <key> already existed in the db (other
                   11809:                         requested keys may also already exist)
1.967     bisitz   11810:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 11811:  'con_lost' -> unable to contact request server
                   11812:  'refused' -> action was not allowed by remote machine
                   11813: 
                   11814: 
                   11815: =item *
                   11816: 
1.243     albertel 11817: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   11818: reference filled in from namesp (encrypts the return communication)
                   11819: ($udom and $uname are optional)
1.191     harris41 11820: 
                   11821: =item *
                   11822: 
1.243     albertel 11823: log($udom,$name,$home,$message) : write to permanent log for user; use
                   11824: critical subroutine
                   11825: 
1.806     raeburn  11826: =item *
                   11827: 
1.860     raeburn  11828: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   11829: array reference filled in from namespace found in domain level on either
                   11830: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  11831: 
                   11832: =item *
                   11833: 
1.860     raeburn  11834: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   11835: domain level either on specified domain server ($uhome) or primary domain 
                   11836: server ($udom and $uhome are optional)
1.806     raeburn  11837: 
1.943     raeburn  11838: =item * 
                   11839: 
                   11840: get_domain_defaults($target_domain) : returns hash with defaults for
                   11841: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   11842: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   11843: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   11844: Values are retrieved from cache (if current), or from domain's configuration.db
                   11845: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   11846: or lonTabs/domain.tab. 
                   11847: 
                   11848: %domdefaults = &get_auth_defaults($target_domain);
                   11849: 
1.243     albertel 11850: =back
                   11851: 
                   11852: =head2 Network Status Functions
                   11853: 
                   11854: =over 4
1.191     harris41 11855: 
                   11856: =item *
                   11857: 
1.1137    raeburn  11858: dirlist() : return directory list based on URI (first arg).
                   11859: 
                   11860: Inputs: 1 required, 5 optional.
                   11861: 
                   11862: =over
                   11863: 
                   11864: =item 
                   11865: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   11866: 
                   11867: =item
                   11868: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   11869: 
                   11870: =item
                   11871: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   11872: 
                   11873: =item
                   11874: $getpropath - boolean: 1 if prepend path using &propath(). 
                   11875: 
                   11876: =item
                   11877: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   11878: 
                   11879: =item 
                   11880: $alternateRoot - path to prepend in place of path from $uri.
                   11881: 
                   11882: =back
                   11883: 
                   11884: Returns: Array of up to two items.
                   11885: 
                   11886: =over
                   11887: 
                   11888: a reference to an array of files/subdirectories
                   11889: 
                   11890: =over
                   11891: 
                   11892: Each element in the array of files/subdirectories is a & separated list of
                   11893: item name and the result of running stat on the item.  If dirlist was requested
                   11894: for a file instead of a directory, the item name will be ''. For a directory 
                   11895: listing, if the item is a metadata file, the element will end &N&M 
                   11896: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   11897: default copyright set (1).  
                   11898: 
                   11899: =back
                   11900: 
                   11901: a scalar containing error condition (if encountered).
                   11902: 
                   11903: =over
                   11904: 
                   11905: =item 
                   11906: no_host (no homeserver identified for $username:$domain).
                   11907: 
                   11908: =item 
                   11909: no_such_host (server contacted for listing not identified as valid host).
                   11910: 
                   11911: =item 
                   11912: con_lost (connection to remote server failed).
                   11913: 
                   11914: =item 
                   11915: refused (invalid $username:$domain received on lond side).
                   11916: 
                   11917: =item 
                   11918: no_such_dir (directory at specified path on lond side does not exist). 
                   11919: 
                   11920: =item 
                   11921: empty (directory at specified path on lond side is empty).
                   11922: 
                   11923: =over
                   11924: 
                   11925: This is currently not encountered because the &ls3, &ls2, 
                   11926: &ls (_handler) routines on the lond side do not filter out
                   11927: . and .. from a directory listing. 
                   11928: 
                   11929: =back
                   11930: 
                   11931: =back
                   11932: 
                   11933: =back
1.191     harris41 11934: 
                   11935: =item *
                   11936: 
1.243     albertel 11937: spareserver() : find server with least workload from spare.tab
                   11938: 
1.986     foxr     11939: 
                   11940: =item *
                   11941: 
                   11942: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   11943: if there is no corresponding loncapa host.
                   11944: 
1.243     albertel 11945: =back
                   11946: 
1.986     foxr     11947: 
1.243     albertel 11948: =head2 Apache Request
                   11949: 
                   11950: =over 4
1.191     harris41 11951: 
                   11952: =item *
                   11953: 
1.243     albertel 11954: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   11955: localhost, posts hash
                   11956: 
                   11957: =back
                   11958: 
                   11959: =head2 Data to String to Data
                   11960: 
                   11961: =over 4
1.191     harris41 11962: 
                   11963: =item *
                   11964: 
1.243     albertel 11965: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   11966: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 11967: 
                   11968: =item *
                   11969: 
1.243     albertel 11970: hashref2str($hashref) : convert a hashref into a string complete with
                   11971: escaping and '=' and '&' separators, supports elements that are
                   11972: arrayrefs and hashrefs
1.191     harris41 11973: 
                   11974: =item *
                   11975: 
1.243     albertel 11976: arrayref2str($arrayref) : convert an arrayref into a string complete
                   11977: with escaping and '&' separators, supports elements that are arrayrefs
                   11978: and hashrefs
1.191     harris41 11979: 
                   11980: =item *
                   11981: 
1.243     albertel 11982: str2hash($string) : convert string to hash using unescaping and
                   11983: splitting on '=' and '&', supports elements that are arrayrefs and
                   11984: hashrefs
1.191     harris41 11985: 
                   11986: =item *
                   11987: 
1.243     albertel 11988: str2array($string) : convert string to hash using unescaping and
                   11989: splitting on '&', supports elements that are arrayrefs and hashrefs
                   11990: 
                   11991: =back
                   11992: 
                   11993: =head2 Logging Routines
                   11994: 
                   11995: 
                   11996: These routines allow one to make log messages in the lonnet.log and
                   11997: lonnet.perm logfiles.
1.191     harris41 11998: 
1.1119    foxr     11999: =over 4
                   12000: 
1.191     harris41 12001: =item *
                   12002: 
1.243     albertel 12003: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12004: 
                   12005: =item *
                   12006: 
1.243     albertel 12007: logthis() : append message to the normal lonnet.log file, it gets
                   12008: preiodically rolled over and deleted.
1.191     harris41 12009: 
                   12010: =item *
                   12011: 
1.243     albertel 12012: logperm() : append a permanent message to lonnet.perm.log, this log
                   12013: file never gets deleted by any automated portion of the system, only
                   12014: messages of critical importance should go in here.
                   12015: 
1.1119    foxr     12016: 
1.243     albertel 12017: =back
                   12018: 
                   12019: =head2 General File Helper Routines
                   12020: 
                   12021: =over 4
1.191     harris41 12022: 
                   12023: =item *
                   12024: 
1.481     raeburn  12025: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12026: (a) files in /uploaded
                   12027:   (i) If a local copy of the file exists - 
                   12028:       compares modification date of local copy with last-modified date for 
                   12029:       definitive version stored on home server for course. If local copy is 
                   12030:       stale, requests a new version from the home server and stores it. 
                   12031:       If the original has been removed from the home server, then local copy 
                   12032:       is unlinked.
                   12033:   (ii) If local copy does not exist -
                   12034:       requests the file from the home server and stores it. 
                   12035:   
                   12036:   If $caller is 'uploadrep':  
                   12037:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12038:     for request for files originally uploaded via DOCS. 
                   12039:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12040:   
                   12041:   Otherwise:
                   12042:      This indicates a call from the content generation phase of the request.
                   12043:      -  returns the entire contents of the file or -1.
                   12044:      
                   12045: (b) files in /res
                   12046:    - returns the entire contents of a file or -1; 
                   12047:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12048: 
1.712     albertel 12049: 
                   12050: =item *
                   12051: 
                   12052: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12053:                   reference
                   12054: 
                   12055: returns either a stat() list of data about the file or an empty list
                   12056: if the file doesn't exist or couldn't find out about it (connection
                   12057: problems or user unknown)
                   12058: 
1.191     harris41 12059: =item *
                   12060: 
1.243     albertel 12061: filelocation($dir,$file) : returns file system location of a file
                   12062: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12063: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12064: and a file of ../bob will become /a/bob)
1.191     harris41 12065: 
                   12066: =item *
                   12067: 
                   12068: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12069: filelocation except for hrefs
                   12070: 
                   12071: =item *
                   12072: 
                   12073: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12074: 
1.243     albertel 12075: =back
                   12076: 
1.608     albertel 12077: =head2 Usererfile file routines (/uploaded*)
                   12078: 
                   12079: =over 4
                   12080: 
                   12081: =item *
                   12082: 
                   12083: userfileupload(): main rotine for putting a file in a user or course's
                   12084:                   filespace, arguments are,
                   12085: 
1.620     albertel 12086:  formname - required - this is the name of the element in $env where the
1.608     albertel 12087:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12088:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12089:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12090:  context - if coursedoc, store the file in the course of the active role
                   12091:              of the current user; 
                   12092:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12093:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12094:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12095:          if undefined, it will be placed in "unknown"
                   12096: 
                   12097:  (This routine calls clean_filename() to remove any dangerous
                   12098:  characters from the filename, and then calls finuserfileupload() to
                   12099:  complete the transaction)
                   12100: 
                   12101:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12102:  and /adm/notfound.html if unsuccessful
                   12103: 
                   12104: =item *
                   12105: 
                   12106: clean_filename(): routine for cleaing a filename up for storage in
                   12107:                  userfile space, argument is:
                   12108: 
                   12109:  filename - proposed filename
                   12110: 
                   12111: returns: the new clean filename
                   12112: 
                   12113: =item *
                   12114: 
1.1090    raeburn  12115: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12116: userspace, probably shouldn't be called directly
                   12117: 
                   12118:   docuname: username or courseid of destination for the file
                   12119:   docudom: domain of user/course of destination for the file
                   12120:   formname: same as for userfileupload()
1.1090    raeburn  12121:   fname: filename (including subdirectories) for the file
                   12122:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12123:   allfiles: reference to hash used to store objects found by parser
                   12124:   codebase: reference to hash used for codebases of java objects found by parser
                   12125:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12126:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12127:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12128:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12129:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12130:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12131:   mimetype: reference to scalar to accommodate mime type determined
                   12132:             from File::MMagic if $parser = parse.
1.608     albertel 12133: 
                   12134:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12135:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12136:  was 'overwrite').
                   12137:  
1.608     albertel 12138: 
                   12139: =item *
                   12140: 
                   12141: renameuserfile(): renames an existing userfile to a new name
                   12142: 
                   12143:   Args:
                   12144:    docuname: username or courseid of destination for the file
                   12145:    docudom: domain of user/course of destination for the file
                   12146:    old: current file name (including any subdirs under userfiles)
                   12147:    new: desired file name (including any subdirs under userfiles)
                   12148: 
                   12149: =item *
                   12150: 
                   12151: mkdiruserfile(): creates a directory is a userfiles dir
                   12152: 
                   12153:   Args:
                   12154:    docuname: username or courseid of destination for the file
                   12155:    docudom: domain of user/course of destination for the file
                   12156:    dir: dir to create (including any subdirs under userfiles)
                   12157: 
                   12158: =item *
                   12159: 
                   12160: removeuserfile(): removes a file that exists in userfiles
                   12161: 
                   12162:   Args:
                   12163:    docuname: username or courseid of destination for the file
                   12164:    docudom: domain of user/course of destination for the file
                   12165:    fname: filname to delete (including any subdirs under userfiles)
                   12166: 
                   12167: =item *
                   12168: 
                   12169: removeuploadedurl(): convience function for removeuserfile()
                   12170: 
                   12171:   Args:
                   12172:    url:  a full /uploaded/... url to delete
                   12173: 
1.747     albertel 12174: =item * 
                   12175: 
                   12176: get_portfile_permissions():
                   12177:   Args:
                   12178:     domain: domain of user or course contain the portfolio files
                   12179:     user: name of user or num of course contain the portfolio files
                   12180:   Returns:
                   12181:     hashref of a dump of the proper file_permissions.db
                   12182:    
                   12183: 
                   12184: =item * 
                   12185: 
                   12186: get_access_controls():
                   12187: 
                   12188: Args:
                   12189:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12190:   group: (optional) the group you want the files associated with
                   12191:   file: (optional) the file you want access info on
                   12192: 
                   12193: Returns:
1.749     raeburn  12194:     a hash (keys are file names) of hashes containing
                   12195:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12196:         values are XML containing access control settings (see below) 
1.747     albertel 12197: 
                   12198: Internal notes:
                   12199: 
1.749     raeburn  12200:  access controls are stored in file_permissions.db as key=value pairs.
                   12201:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12202:         where scope -> public,guest,course,group,domains or users.
                   12203:               end -> UNIX time for end of access (0 -> no end date)
                   12204:               start -> UNIX time for start of access
                   12205: 
                   12206:     value -> XML description of access control
                   12207:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12208:             <start></start>
                   12209:             <end></end>
                   12210: 
                   12211:             <password></password>  for scope type = guest
                   12212: 
                   12213:             <domain></domain>     for scope type = course or group
                   12214:             <number></number>
                   12215:             <roles id="">
                   12216:              <role></role>
                   12217:              <access></access>
                   12218:              <section></section>
                   12219:              <group></group>
                   12220:             </roles>
                   12221: 
                   12222:             <dom></dom>         for scope type = domains
                   12223: 
                   12224:             <users>             for scope type = users
                   12225:              <user>
                   12226:               <uname></uname>
                   12227:               <udom></udom>
                   12228:              </user>
                   12229:             </users>
                   12230:            </scope> 
                   12231:               
                   12232:  Access data is also aggregated for each file in an additional key=value pair:
                   12233:  key -> path to file/file_name\0accesscontrol 
                   12234:  value -> reference to hash
                   12235:           hash contains key = value pairs
                   12236:           where key = uniqueID:scope_end_start
                   12237:                 value = UNIX time record was last updated
                   12238: 
                   12239:           Used to improve speed of look-ups of access controls for each file.  
                   12240:  
                   12241:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12242: 
                   12243: modify_access_controls():
                   12244: 
                   12245: Modifies access controls for a portfolio file
                   12246: Args
                   12247: 1. file name
                   12248: 2. reference to hash of required changes,
                   12249: 3. domain
                   12250: 4. username
                   12251:   where domain,username are the domain of the portfolio owner 
                   12252:   (either a user or a course) 
                   12253: 
                   12254: Returns:
                   12255: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12256: 2. result of deletions ('ok' or 'error', with error message).
                   12257: 3. reference to hash of any new or updated access controls.
                   12258: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12259:    key = integer (inbound ID)
                   12260:    value = uniqueID  
1.747     albertel 12261: 
1.608     albertel 12262: =back
                   12263: 
1.243     albertel 12264: =head2 HTTP Helper Routines
                   12265: 
                   12266: =over 4
                   12267: 
1.191     harris41 12268: =item *
                   12269: 
                   12270: escape() : unpack non-word characters into CGI-compatible hex codes
                   12271: 
                   12272: =item *
                   12273: 
                   12274: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12275: 
1.243     albertel 12276: =back
                   12277: 
                   12278: =head1 PRIVATE SUBROUTINES
                   12279: 
                   12280: =head2 Underlying communication routines (Shouldn't call)
                   12281: 
                   12282: =over 4
                   12283: 
                   12284: =item *
                   12285: 
                   12286: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12287: 
                   12288: =item *
                   12289: 
                   12290: reply() : uses subreply to send a message to remote machine, logs all failures
                   12291: 
                   12292: =item *
                   12293: 
                   12294: critical() : passes a critical message to another server; if cannot
                   12295: get through then place message in connection buffer directory and
                   12296: returns con_delayed, if incapable of saving message, returns
                   12297: con_failed
                   12298: 
                   12299: =item *
                   12300: 
                   12301: reconlonc() : tries to reconnect lonc client processes.
                   12302: 
                   12303: =back
                   12304: 
                   12305: =head2 Resource Access Logging
                   12306: 
                   12307: =over 4
                   12308: 
                   12309: =item *
                   12310: 
                   12311: flushcourselogs() : flush (save) buffer logs and access logs
                   12312: 
                   12313: =item *
                   12314: 
                   12315: courselog($what) : save message for course in hash
                   12316: 
                   12317: =item *
                   12318: 
                   12319: courseacclog($what) : save message for course using &courselog().  Perform
                   12320: special processing for specific resource types (problems, exams, quizzes, etc).
                   12321: 
1.191     harris41 12322: =item *
                   12323: 
                   12324: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12325: as a PerlChildExitHandler
1.243     albertel 12326: 
                   12327: =back
                   12328: 
                   12329: =head2 Other
                   12330: 
                   12331: =over 4
                   12332: 
                   12333: =item *
                   12334: 
                   12335: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12336: 
                   12337: =back
                   12338: 
                   12339: =cut
1.877     foxr     12340: 

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