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

1.1       albertel    1: # The LearningOnline Network
                      2: # TCP networking package
1.12      www         3: #
1.1175  ! raeburn     4: # $Id: lonnet.pm,v 1.1174 2012/05/28 12:28:14 raeburn Exp $
1.178     www         5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.169     harris41   28: ###
                     29: 
1.971     jms        30: =pod
                     31: 
1.972     jms        32: =head1 NAME
                     33: 
                     34: Apache::lonnet.pm
                     35: 
                     36: =head1 SYNOPSIS
                     37: 
                     38: This file is an interface to the lonc processes of
                     39: the LON-CAPA network as well as set of elaborated functions for handling information
                     40: necessary for navigating through a given cluster of LON-CAPA machines within a
                     41: domain. There are over 40 specialized functions in this module which handle the
                     42: reading and transmission of metadata, user information (ids, names, environments, roles,
                     43: logs), file information (storage, reading, directories, extensions, replication, embedded
                     44: styles and descriptors), educational resources (course descriptions, section names and
                     45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
                     46: and from more descriptive phrases or explanations.
                     47: 
                     48: This is part of the LearningOnline Network with CAPA project
                     49: described at http://www.lon-capa.org.
                     50: 
1.971     jms        51: =head1 Package Variables
                     52: 
                     53: These are largely undocumented, so if you decipher one please note it here.
                     54: 
                     55: =over 4
                     56: 
                     57: =item $processmarker
                     58: 
                     59: Contains the time this process was started and this servers host id.
                     60: 
                     61: =item $dumpcount
                     62: 
                     63: Counts the number of times a message log flush has been attempted (regardless
                     64: of success) by this process.  Used as part of the filename when messages are
                     65: delayed.
                     66: 
                     67: =back
                     68: 
                     69: =cut
                     70: 
1.1       albertel   71: package Apache::lonnet;
                     72: 
                     73: use strict;
1.8       www        74: use LWP::UserAgent();
1.486     www        75: use HTTP::Date;
1.977     amueller   76: use Image::Magick;
                     77: 
1.1173    foxr       78: use Encode;
                     79: 
1.871     albertel   80: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138    raeburn    81:             $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
                     82:             %managerstab);
1.871     albertel   83: 
                     84: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
                     85:     %userrolehash, $processmarker, $dumpcount, %coursedombuf,
                     86:     %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958     www        87:     %courseownerbuf, %coursetypebuf,$locknum);
1.403     www        88: 
1.1       albertel   89: use IO::Socket;
1.31      www        90: use GDBM_File;
1.208     albertel   91: use HTML::LCParser;
1.88      www        92: use Fcntl qw(:flock);
1.870     albertel   93: use Storable qw(thaw nfreeze);
1.539     albertel   94: use Time::HiRes qw( gettimeofday tv_interval );
1.599     albertel   95: use Cache::Memcached;
1.676     albertel   96: use Digest::MD5;
1.790     albertel   97: use Math::Random;
1.1024    raeburn    98: use File::MMagic;
1.807     albertel   99: use LONCAPA qw(:DEFAULT :match);
1.740     www       100: use LONCAPA::Configuration;
1.1160    www       101: use LONCAPA::lonmetadata;
1.1167    droeschl  102: use LONCAPA::Lond;
1.1117    foxr      103: 
1.1090    raeburn   104: use File::Copy;
1.676     albertel  105: 
1.195     www       106: my $readit;
1.550     foxr      107: my $max_connection_retries = 10;     # Or some such value.
1.1       albertel  108: 
1.619     albertel  109: require Exporter;
                    110: 
                    111: our @ISA = qw (Exporter);
                    112: our @EXPORT = qw(%env);
                    113: 
1.449     matthew   114: 
1.1       albertel  115: # --------------------------------------------------------------------- Logging
1.729     www       116: {
                    117:     my $logid;
                    118:     sub instructor_log {
1.957     raeburn   119: 	my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
                    120:         if (($cnum eq '') || ($cdom eq '')) {
                    121:             $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                    122:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                    123:         }
1.729     www       124: 	$logid++;
1.957     raeburn   125:         my $now = time();
                    126: 	my $id=$now.'00000'.$$.'00000'.$logid;
1.729     www       127: 	return &Apache::lonnet::put('nohist_'.$hash_name,
1.730     www       128: 				    { $id => {
                    129: 					'exe_uname' => $env{'user.name'},
                    130: 					'exe_udom'  => $env{'user.domain'},
1.957     raeburn   131: 					'exe_time'  => $now,
1.730     www       132: 					'exe_ip'    => $ENV{'REMOTE_ADDR'},
                    133: 					'delflag'   => $delflag,
                    134: 					'logentry'  => $storehash,
                    135: 					'uname'     => $uname,
                    136: 					'udom'      => $udom,
                    137: 				    }
1.957     raeburn   138: 				  },$cdom,$cnum);
1.729     www       139:     }
                    140: }
1.1       albertel  141: 
1.163     harris41  142: sub logtouch {
                    143:     my $execdir=$perlvar{'lonDaemons'};
1.448     albertel  144:     unless (-e "$execdir/logs/lonnet.log") {	
                    145: 	open(my $fh,">>$execdir/logs/lonnet.log");
1.163     harris41  146: 	close $fh;
                    147:     }
                    148:     my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
                    149:     chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
                    150: }
                    151: 
1.1       albertel  152: sub logthis {
                    153:     my $message=shift;
                    154:     my $execdir=$perlvar{'lonDaemons'};
                    155:     my $now=time;
                    156:     my $local=localtime($now);
1.448     albertel  157:     if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986     foxr      158: 	my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
                    159: 	print $fh $logstring;
1.448     albertel  160: 	close($fh);
                    161:     }
1.1       albertel  162:     return 1;
                    163: }
                    164: 
                    165: sub logperm {
                    166:     my $message=shift;
                    167:     my $execdir=$perlvar{'lonDaemons'};
                    168:     my $now=time;
                    169:     my $local=localtime($now);
1.448     albertel  170:     if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
                    171: 	print $fh "$now:$message:$local\n";
                    172: 	close($fh);
                    173:     }
1.1       albertel  174:     return 1;
                    175: }
                    176: 
1.850     albertel  177: sub create_connection {
1.853     albertel  178:     my ($hostname,$lonid) = @_;
1.851     albertel  179:     my $client=IO::Socket::UNIX->new(Peer    => $perlvar{'lonSockCreate'},
1.850     albertel  180: 				     Type    => SOCK_STREAM,
                    181: 				     Timeout => 10);
                    182:     return 0 if (!$client);
1.890     albertel  183:     print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850     albertel  184:     my $result = <$client>;
                    185:     chomp($result);
                    186:     return 1 if ($result eq 'done');
                    187:     return 0;
                    188: }
                    189: 
1.983     raeburn   190: sub get_server_timezone {
                    191:     my ($cnum,$cdom) = @_;
                    192:     my $home=&homeserver($cnum,$cdom);
                    193:     if ($home ne 'no_host') {
                    194:         my $cachetime = 24*3600;
                    195:         my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
                    196:         if (defined($cached)) {
                    197:             return $timezone;
                    198:         } else {
                    199:             my $timezone = &reply('servertimezone',$home);
                    200:             return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
                    201:         }
                    202:     }
                    203: }
1.850     albertel  204: 
1.1106    raeburn   205: sub get_server_distarch {
                    206:     my ($lonhost,$ignore_cache) = @_;
                    207:     if (defined($lonhost)) {
                    208:         if (!defined(&hostname($lonhost))) {
                    209:             return;
                    210:         }
                    211:         my $cachetime = 12*3600;
                    212:         if (!$ignore_cache) {
                    213:             my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
                    214:             if (defined($cached)) {
                    215:                 return $distarch;
                    216:             }
                    217:         }
                    218:         my $rep = &reply('serverdistarch',$lonhost);
                    219:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
                    220:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                    221:                 $rep eq '') {
                    222:             return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
                    223:         }
                    224:     }
                    225:     return;
                    226: }
                    227: 
1.993     raeburn   228: sub get_server_loncaparev {
1.1073    raeburn   229:     my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993     raeburn   230:     if (defined($lonhost)) {
                    231:         if (!defined(&hostname($lonhost))) {
                    232:             undef($lonhost);
                    233:         }
                    234:     }
                    235:     if (!defined($lonhost)) {
                    236:         if (defined(&domain($dom,'primary'))) {
                    237:             $lonhost=&domain($dom,'primary');
                    238:             if ($lonhost eq 'no_host') {
                    239:                 undef($lonhost);
                    240:             }
                    241:         }
                    242:     }
                    243:     if (defined($lonhost)) {
1.1073    raeburn   244:         my $cachetime = 12*3600;
                    245:         if (!$ignore_cache) {
                    246:             my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
                    247:             if (defined($cached)) {
                    248:                 return $loncaparev;
                    249:             }
                    250:         }
                    251:         my ($answer,$loncaparev);
                    252:         my @ids=&current_machine_ids();
                    253:         if (grep(/^\Q$lonhost\E$/,@ids)) {
                    254:             $answer = $perlvar{'lonVersion'};
1.1081    raeburn   255:             if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   256:                 $loncaparev = $1;
                    257:             }
                    258:         } else {
                    259:             $answer = &reply('serverloncaparev',$lonhost);
                    260:             if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
                    261:                 if ($caller eq 'loncron') {
                    262:                     my $ua=new LWP::UserAgent;
1.1082    raeburn   263:                     $ua->timeout(4);
1.1073    raeburn   264:                     my $protocol = $protocol{$lonhost};
                    265:                     $protocol = 'http' if ($protocol ne 'https');
                    266:                     my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
                    267:                     my $request=new HTTP::Request('GET',$url);
                    268:                     my $response=$ua->request($request);
                    269:                     unless ($response->is_error()) {
                    270:                         my $content = $response->content;
1.1081    raeburn   271:                         if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073    raeburn   272:                             $loncaparev = $1;
                    273:                         }
                    274:                     }
                    275:                 } else {
                    276:                     $loncaparev = $loncaparevs{$lonhost};
                    277:                 }
1.1081    raeburn   278:             } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073    raeburn   279:                 $loncaparev = $1;
                    280:             }
1.993     raeburn   281:         }
1.1073    raeburn   282:         return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993     raeburn   283:     }
                    284: }
                    285: 
1.1074    raeburn   286: sub get_server_homeID {
                    287:     my ($hostname,$ignore_cache,$caller) = @_;
                    288:     unless ($ignore_cache) {
                    289:         my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
                    290:         if (defined($cached)) {
                    291:             return $serverhomeID;
                    292:         }
                    293:     }
                    294:     my $cachetime = 12*3600;
                    295:     my $serverhomeID;
                    296:     if ($caller eq 'loncron') { 
                    297:         my @machine_ids = &machine_ids($hostname);
                    298:         foreach my $id (@machine_ids) {
                    299:             my $response = &reply('serverhomeID',$id);
                    300:             unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
                    301:                 $serverhomeID = $response;
                    302:                 last;
                    303:             }
                    304:         }
                    305:         if ($serverhomeID eq '') {
                    306:             $serverhomeID = $machine_ids[-1];
                    307:         }
                    308:     } else {
                    309:         $serverhomeID = $serverhomeIDs{$hostname};
                    310:     }
                    311:     return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
                    312: }
                    313: 
1.1121    raeburn   314: sub get_remote_globals {
                    315:     my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125    raeburn   316:     my ($result,%returnhash,%whatneeded);
                    317:     if (ref($whathash) eq 'HASH') {
1.1121    raeburn   318:         foreach my $what (sort(keys(%{$whathash}))) {
                    319:             my $hashid = $lonhost.'-'.$what;
1.1125    raeburn   320:             my ($response,$cached);
1.1121    raeburn   321:             unless ($ignore_cache) {
1.1125    raeburn   322:                 ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121    raeburn   323:             }
                    324:             if (defined($cached)) {
1.1125    raeburn   325:                 $returnhash{$what} = $response;
1.1121    raeburn   326:             } else {
1.1125    raeburn   327:                 $whatneeded{$what} = 1;
1.1121    raeburn   328:             }
                    329:         }
1.1125    raeburn   330:         if (keys(%whatneeded) == 0) {
                    331:             $result = 'ok';
                    332:         } else {
1.1121    raeburn   333:             my $requested = &freeze_escape(\%whatneeded);
                    334:             my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125    raeburn   335:             if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
                    336:                 ($rep eq 'unknown_cmd')) {
                    337:                 $result = $rep;
                    338:             } else {
                    339:                 $result = 'ok';
1.1121    raeburn   340:                 my @pairs=split(/\&/,$rep);
1.1125    raeburn   341:                 foreach my $item (@pairs) {
                    342:                     my ($key,$value)=split(/=/,$item,2);
                    343:                     my $what = &unescape($key);
                    344:                     my $hashid = $lonhost.'-'.$what;
                    345:                     $returnhash{$what}=&thaw_unescape($value);
                    346:                     &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121    raeburn   347:                 }
                    348:             }
                    349:         }
                    350:     }
1.1125    raeburn   351:     return ($result,\%returnhash);
1.1121    raeburn   352: }
                    353: 
1.1124    raeburn   354: sub remote_devalidate_cache {
                    355:     my ($lonhost,$name,$id) = @_;
1.1130    raeburn   356:     my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124    raeburn   357:     return $response;
                    358: }
                    359: 
1.1       albertel  360: # -------------------------------------------------- Non-critical communication
                    361: sub subreply {
                    362:     my ($cmd,$server)=@_;
1.838     albertel  363:     my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549     foxr      364:     #
                    365:     #  With loncnew process trimming, there's a timing hole between lonc server
                    366:     #  process exit and the master server picking up the listen on the AF_UNIX
                    367:     #  socket.  In that time interval, a lock file will exist:
                    368: 
                    369:     my $lockfile=$peerfile.".lock";
                    370:     while (-e $lockfile) {	# Need to wait for the lockfile to disappear.
                    371: 	sleep(1);
                    372:     }
                    373:     # At this point, either a loncnew parent is listening or an old lonc
1.550     foxr      374:     # or loncnew child is listening so we can connect or everything's dead.
1.549     foxr      375:     #
1.550     foxr      376:     #   We'll give the connection a few tries before abandoning it.  If
                    377:     #   connection is not possible, we'll con_lost back to the client.
                    378:     #   
                    379:     my $client;
                    380:     for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
                    381: 	$client=IO::Socket::UNIX->new(Peer    =>"$peerfile",
                    382: 				      Type    => SOCK_STREAM,
                    383: 				      Timeout => 10);
1.869     albertel  384: 	if ($client) {
1.550     foxr      385: 	    last;		# Connected!
1.850     albertel  386: 	} else {
1.853     albertel  387: 	    &create_connection(&hostname($server),$server);
1.550     foxr      388: 	}
1.850     albertel  389:         sleep(1);		# Try again later if failed connection.
1.550     foxr      390:     }
                    391:     my $answer;
                    392:     if ($client) {
1.704     albertel  393: 	print $client "sethost:$server:$cmd\n";
1.550     foxr      394: 	$answer=<$client>;
                    395: 	if (!$answer) { $answer="con_lost"; }
                    396: 	chomp($answer);
                    397:     } else {
                    398: 	$answer = 'con_lost';	# Failed connection.
                    399:     }
1.1       albertel  400:     return $answer;
                    401: }
                    402: 
                    403: sub reply {
                    404:     my ($cmd,$server)=@_;
1.838     albertel  405:     unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1       albertel  406:     my $answer=subreply($cmd,$server);
1.65      www       407:     if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672     albertel  408:        &logthis("<font color=\"blue\">WARNING:".
1.12      www       409:                 " $cmd to $server returned $answer</font>");
                    410:     }
1.1       albertel  411:     return $answer;
                    412: }
                    413: 
                    414: # ----------------------------------------------------------- Send USR1 to lonc
                    415: 
                    416: sub reconlonc {
1.891     albertel  417:     my ($lonid) = @_;
                    418:     my $hostname = &hostname($lonid);
                    419:     if ($lonid) {
                    420: 	my $peerfile="$perlvar{'lonSockDir'}/$hostname";
                    421: 	if ($hostname && -e $peerfile) {
                    422: 	    &logthis("Trying to reconnect lonc for $lonid ($hostname)");
                    423: 	    my $client=IO::Socket::UNIX->new(Peer    => $peerfile,
                    424: 					     Type    => SOCK_STREAM,
                    425: 					     Timeout => 10);
                    426: 	    if ($client) {
                    427: 		print $client ("reset_retries\n");
                    428: 		my $answer=<$client>;
                    429: 		#reset just this one.
                    430: 	    }
                    431: 	}
                    432: 	return;
                    433:     }
                    434: 
1.836     www       435:     &logthis("Trying to reconnect lonc");
1.1       albertel  436:     my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448     albertel  437:     if (open(my $fh,"<$loncfile")) {
1.1       albertel  438: 	my $loncpid=<$fh>;
                    439:         chomp($loncpid);
                    440:         if (kill 0 => $loncpid) {
                    441: 	    &logthis("lonc at pid $loncpid responding, sending USR1");
                    442:             kill USR1 => $loncpid;
                    443:             sleep 1;
1.836     www       444:          } else {
1.12      www       445: 	    &logthis(
1.672     albertel  446:                "<font color=\"blue\">WARNING:".
1.12      www       447:                " lonc at pid $loncpid not responding, giving up</font>");
1.1       albertel  448:         }
                    449:     } else {
1.836     www       450: 	&logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1       albertel  451:     }
                    452: }
                    453: 
                    454: # ------------------------------------------------------ Critical communication
1.12      www       455: 
1.1       albertel  456: sub critical {
                    457:     my ($cmd,$server)=@_;
1.838     albertel  458:     unless (&hostname($server)) {
1.672     albertel  459:         &logthis("<font color=\"blue\">WARNING:".
1.89      www       460:                " Critical message to unknown server ($server)</font>");
                    461:         return 'no_such_host';
                    462:     }
1.1       albertel  463:     my $answer=reply($cmd,$server);
                    464:     if ($answer eq 'con_lost') {
                    465: 	&reconlonc("$perlvar{'lonSockDir'}/$server");
1.589     albertel  466: 	my $answer=reply($cmd,$server);
1.1       albertel  467:         if ($answer eq 'con_lost') {
                    468:             my $now=time;
                    469:             my $middlename=$cmd;
1.5       www       470:             $middlename=substr($middlename,0,16);
1.1       albertel  471:             $middlename=~s/\W//g;
                    472:             my $dfilename=
1.305     www       473:       "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
                    474:             $dumpcount++;
1.1       albertel  475:             {
1.448     albertel  476: 		my $dfh;
                    477: 		if (open($dfh,">$dfilename")) {
                    478: 		    print $dfh "$cmd\n"; 
                    479: 		    close($dfh);
                    480: 		}
1.1       albertel  481:             }
                    482:             sleep 2;
                    483:             my $wcmd='';
                    484:             {
1.448     albertel  485: 		my $dfh;
                    486: 		if (open($dfh,"<$dfilename")) {
                    487: 		    $wcmd=<$dfh>; 
                    488: 		    close($dfh);
                    489: 		}
1.1       albertel  490:             }
                    491:             chomp($wcmd);
1.7       www       492:             if ($wcmd eq $cmd) {
1.672     albertel  493: 		&logthis("<font color=\"blue\">WARNING: ".
1.12      www       494:                          "Connection buffer $dfilename: $cmd</font>");
1.1       albertel  495:                 &logperm("D:$server:$cmd");
                    496: 	        return 'con_delayed';
                    497:             } else {
1.672     albertel  498:                 &logthis("<font color=\"red\">CRITICAL:"
1.12      www       499:                         ." Critical connection failed: $server $cmd</font>");
1.1       albertel  500:                 &logperm("F:$server:$cmd");
                    501:                 return 'con_failed';
                    502:             }
                    503:         }
                    504:     }
                    505:     return $answer;
1.405     albertel  506: }
                    507: 
1.755     albertel  508: # ------------------------------------------- check if return value is an error
                    509: 
                    510: sub error {
                    511:     my ($result) = @_;
1.756     albertel  512:     if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755     albertel  513: 	if ($2 == 2) { return undef; }
                    514: 	return $1;
                    515:     }
                    516:     return undef;
                    517: }
                    518: 
1.783     albertel  519: sub convert_and_load_session_env {
                    520:     my ($lonidsdir,$handle)=@_;
                    521:     my @profile;
                    522:     {
1.917     albertel  523: 	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    524: 	if (!$opened) {
1.915     albertel  525: 	    return 0;
                    526: 	}
1.783     albertel  527: 	flock($idf,LOCK_SH);
                    528: 	@profile=<$idf>;
                    529: 	close($idf);
                    530:     }
                    531:     my %temp_env;
                    532:     foreach my $line (@profile) {
1.786     albertel  533: 	if ($line !~ m/=/) {
                    534: 	    return 0;
                    535: 	}
1.783     albertel  536: 	chomp($line);
                    537: 	my ($envname,$envvalue)=split(/=/,$line,2);
                    538: 	$temp_env{&unescape($envname)} = &unescape($envvalue);
                    539:     }
                    540:     unlink("$lonidsdir/$handle.id");
                    541:     if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
                    542: 	    0640)) {
                    543: 	%disk_env = %temp_env;
                    544: 	@env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
                    545: 	untie(%disk_env);
                    546:     }
1.786     albertel  547:     return 1;
1.783     albertel  548: }
                    549: 
1.374     www       550: # ------------------------------------------- Transfer profile into environment
1.780     albertel  551: my $env_loaded;
                    552: sub transfer_profile_to_env {
1.788     albertel  553:     my ($lonidsdir,$handle,$force_transfer) = @_;
                    554:     if (!$force_transfer && $env_loaded) { return; } 
1.374     www       555: 
1.720     albertel  556:     if (!defined($lonidsdir)) {
                    557: 	$lonidsdir = $perlvar{'lonIDsDir'};
                    558:     }
                    559:     if (!defined($handle)) {
                    560:         ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
                    561:     }
                    562: 
1.786     albertel  563:     my $convert;
                    564:     {
1.917     albertel  565:     	my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    566: 	if (!$opened) {
1.915     albertel  567: 	    return;
                    568: 	}
1.786     albertel  569: 	flock($idf,LOCK_SH);
                    570: 	if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    571: 		&GDBM_READER(),0640)) {
                    572: 	    @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
                    573: 	    untie(%disk_env);
                    574: 	} else {
                    575: 	    $convert = 1;
                    576: 	}
                    577:     }
                    578:     if ($convert) {
                    579: 	if (!&convert_and_load_session_env($lonidsdir,$handle)) {
                    580: 	    &logthis("Failed to load session, or convert session.");
                    581: 	}
1.374     www       582:     }
1.783     albertel  583: 
1.786     albertel  584:     my %remove;
1.783     albertel  585:     while ( my $envname = each(%env) ) {
1.433     matthew   586:         if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
                    587:             if ($time < time-300) {
1.783     albertel  588:                 $remove{$key}++;
1.433     matthew   589:             }
                    590:         }
                    591:     }
1.783     albertel  592: 
1.619     albertel  593:     $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780     albertel  594:     $env_loaded=1;
1.783     albertel  595:     foreach my $expired_key (keys(%remove)) {
1.433     matthew   596:         &delenv($expired_key);
1.374     www       597:     }
1.1       albertel  598: }
                    599: 
1.916     albertel  600: # ---------------------------------------------------- Check for valid session 
                    601: sub check_for_valid_session {
1.1155    raeburn   602:     my ($r,$name) = @_;
1.916     albertel  603:     my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155    raeburn   604:     if ($name eq '') {
                    605:         $name = 'lonID';
                    606:     }
                    607:     my $lonid=$cookies{$name};
1.916     albertel  608:     return undef if (!$lonid);
                    609: 
                    610:     my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155    raeburn   611:     my $lonidsdir;
                    612:     if ($name eq 'lonDAV') {
                    613:         $lonidsdir=$r->dir_config('lonDAVsessDir');
                    614:     } else {
                    615:         $lonidsdir=$r->dir_config('lonIDsDir');
                    616:     }
1.916     albertel  617:     return undef if (!-e "$lonidsdir/$handle.id");
                    618: 
1.917     albertel  619:     my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
                    620:     return undef if (!$opened);
1.916     albertel  621: 
                    622:     flock($idf,LOCK_SH);
                    623:     my %disk_env;
                    624:     if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
                    625: 	    &GDBM_READER(),0640)) {
                    626: 	return undef;	
                    627:     }
                    628: 
                    629:     if (!defined($disk_env{'user.name'})
                    630: 	|| !defined($disk_env{'user.domain'})) {
                    631: 	return undef;
                    632:     }
                    633:     return $handle;
                    634: }
                    635: 
1.830     albertel  636: sub timed_flock {
                    637:     my ($file,$lock_type) = @_;
                    638:     my $failed=0;
                    639:     eval {
                    640: 	local $SIG{__DIE__}='DEFAULT';
                    641: 	local $SIG{ALRM}=sub {
                    642: 	    $failed=1;
                    643: 	    die("failed lock");
                    644: 	};
                    645: 	alarm(13);
                    646: 	flock($file,$lock_type);
                    647: 	alarm(0);
                    648:     };
                    649:     if ($failed) {
                    650: 	return undef;
                    651:     } else {
                    652: 	return 1;
                    653:     }
                    654: }
                    655: 
1.5       www       656: # ---------------------------------------------------------- Append Environment
                    657: 
                    658: sub appenv {
1.949     raeburn   659:     my ($newenv,$roles) = @_;
                    660:     if (ref($newenv) eq 'HASH') {
                    661:         foreach my $key (keys(%{$newenv})) {
                    662:             my $refused = 0;
                    663: 	    if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
                    664:                 $refused = 1;
                    665:                 if (ref($roles) eq 'ARRAY') {
                    666:                     my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
                    667:                     if (grep(/^\Q$role\E$/,@{$roles})) {
                    668:                         $refused = 0;
                    669:                     }
                    670:                 }
                    671:             }
                    672:             if ($refused) {
                    673:                 &logthis("<font color=\"blue\">WARNING: ".
                    674:                          "Attempt to modify environment ".$key." to ".$newenv->{$key}
                    675:                          .'</font>');
                    676: 	        delete($newenv->{$key});
                    677:             } else {
                    678:                 $env{$key}=$newenv->{$key};
                    679:             }
                    680:         }
                    681:         my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    682:         if ($opened
                    683: 	    && &timed_flock($env_file,LOCK_EX)
                    684: 	    &&
                    685: 	    tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    686: 	        (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
                    687: 	    while (my ($key,$value) = each(%{$newenv})) {
                    688: 	        $disk_env{$key} = $value;
                    689: 	    }
                    690: 	    untie(%disk_env);
1.35      www       691:         }
1.191     harris41  692:     }
1.56      www       693:     return 'ok';
                    694: }
                    695: # ----------------------------------------------------- Delete from Environment
                    696: 
                    697: sub delenv {
1.1104    raeburn   698:     my ($delthis,$regexp,$roles) = @_;
                    699:     if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
                    700:         my $refused = 1;
                    701:         if (ref($roles) eq 'ARRAY') {
                    702:             my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
                    703:             if (grep(/^\Q$role\E$/,@{$roles})) {
                    704:                 $refused = 0;
                    705:             }
                    706:         }
                    707:         if ($refused) {
                    708:             &logthis("<font color=\"blue\">WARNING: ".
                    709:                      "Attempt to delete from environment ".$delthis);
                    710:             return 'error';
                    711:         }
1.56      www       712:     }
1.917     albertel  713:     my $opened = open(my $env_file,'+<',$env{'user.environment'});
                    714:     if ($opened
1.915     albertel  715: 	&& &timed_flock($env_file,LOCK_EX)
1.830     albertel  716: 	&&
                    717: 	tie(my %disk_env,'GDBM_File',$env{'user.environment'},
                    718: 	    (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783     albertel  719: 	foreach my $key (keys(%disk_env)) {
1.987     raeburn   720: 	    if ($regexp) {
                    721:                 if ($key=~/^$delthis/) {
                    722:                     delete($env{$key});
                    723:                     delete($disk_env{$key});
                    724:                 } 
                    725:             } else {
                    726:                 if ($key=~/^\Q$delthis\E/) {
                    727: 		    delete($env{$key});
                    728: 		    delete($disk_env{$key});
                    729: 	        }
                    730:             }
1.448     albertel  731: 	}
1.783     albertel  732: 	untie(%disk_env);
1.5       www       733:     }
                    734:     return 'ok';
1.369     albertel  735: }
                    736: 
1.790     albertel  737: sub get_env_multiple {
                    738:     my ($name) = @_;
                    739:     my @values;
                    740:     if (defined($env{$name})) {
                    741:         # exists is it an array
                    742:         if (ref($env{$name})) {
                    743:             @values=@{ $env{$name} };
                    744:         } else {
                    745:             $values[0]=$env{$name};
                    746:         }
                    747:     }
                    748:     return(@values);
                    749: }
                    750: 
1.958     www       751: # ------------------------------------------------------------------- Locking
                    752: 
                    753: sub set_lock {
                    754:     my ($text)=@_;
                    755:     $locknum++;
                    756:     my $id=$$.'-'.$locknum;
                    757:     &appenv({'session.locks' => $env{'session.locks'}.','.$id,
                    758:              'session.lock.'.$id => $text});
                    759:     return $id;
                    760: }
                    761: 
                    762: sub get_locks {
                    763:     my $num=0;
                    764:     my %texts=();
                    765:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    766:        if ($lock=~/\w/) {
                    767:           $num++;
                    768:           $texts{$lock}=$env{'session.lock.'.$lock};
                    769:        }
                    770:    }
                    771:    return ($num,%texts);
                    772: }
                    773: 
                    774: sub remove_lock {
                    775:     my ($id)=@_;
                    776:     my $newlocks='';
                    777:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    778:        if (($lock=~/\w/) && ($lock ne $id)) {
                    779:           $newlocks.=','.$lock;
                    780:        }
                    781:     }
                    782:     &appenv({'session.locks' => $newlocks});
                    783:     &delenv('session.lock.'.$id);
                    784: }
                    785: 
                    786: sub remove_all_locks {
                    787:     my $activelocks=$env{'session.locks'};
                    788:     foreach my $lock (split(/\,/,$env{'session.locks'})) {
                    789:        if ($lock=~/\w/) {
                    790:           &remove_lock($lock);
                    791:        }
                    792:     }
                    793: }
                    794: 
                    795: 
1.369     albertel  796: # ------------------------------------------ Find out current server userload
                    797: sub userload {
                    798:     my $numusers=0;
                    799:     {
                    800: 	opendir(LONIDS,$perlvar{'lonIDsDir'});
                    801: 	my $filename;
                    802: 	my $curtime=time;
                    803: 	while ($filename=readdir(LONIDS)) {
1.925     albertel  804: 	    next if ($filename eq '.' || $filename eq '..');
                    805: 	    next if ($filename =~ /publicuser_\d+\.id/);
1.404     albertel  806: 	    my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437     albertel  807: 	    if ($curtime-$mtime < 1800) { $numusers++; }
1.369     albertel  808: 	}
                    809: 	closedir(LONIDS);
                    810:     }
                    811:     my $userloadpercent=0;
                    812:     my $maxuserload=$perlvar{'lonUserLoadLim'};
                    813:     if ($maxuserload) {
1.371     albertel  814: 	$userloadpercent=100*$numusers/$maxuserload;
1.369     albertel  815:     }
1.372     albertel  816:     $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369     albertel  817:     return $userloadpercent;
1.283     www       818: }
                    819: 
1.1       albertel  820: # ------------------------------ Find server with least workload from spare.tab
1.11      www       821: 
1.1       albertel  822: sub spareserver {
1.1083    raeburn   823:     my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784     albertel  824:     my $spare_server;
1.370     albertel  825:     if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784     albertel  826:     my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent 
                    827:                                                      :  $userloadpercent;
1.1083    raeburn   828:     my ($uint_dom,$remotesessions);
                    829:     if (($udom ne '') && (&domain($udom) ne '')) {
                    830:         my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                    831:         $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
                    832:         my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
                    833:         $remotesessions = $udomdefaults{'remotesessions'};
                    834:     }
1.1123    raeburn   835:     my $spareshash = &this_host_spares($udom);
                    836:     if (ref($spareshash) eq 'HASH') {
                    837:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    838:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    839:                 if ($uint_dom) {
                    840:                     next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
                    841:                                                  $try_server));
                    842:                 }
                    843: 	        ($spare_server, $lowest_load) =
                    844: 	            &compare_server_load($try_server, $spare_server, $lowest_load);
                    845:             }
1.1083    raeburn   846:         }
1.784     albertel  847: 
1.1123    raeburn   848:         my $found_server = ($spare_server ne '' && $lowest_load < 100);
                    849: 
                    850:         if (!$found_server) {
                    851:             if (ref($spareshash->{'default'}) eq 'ARRAY') { 
                    852: 	        foreach my $try_server (@{ $spareshash->{'default'} }) {
                    853:                     if ($uint_dom) {
                    854:                         next unless (&spare_can_host($udom,$uint_dom,
                    855:                                                      $remotesessions,$try_server));
                    856:                     }
                    857: 	            ($spare_server, $lowest_load) =
                    858: 		        &compare_server_load($try_server, $spare_server, $lowest_load);
                    859:                 }
                    860: 	    }
                    861:         }
1.784     albertel  862:     }
                    863: 
                    864:     if (!$want_server_name) {
1.968     raeburn   865:         my $protocol = 'http';
                    866:         if ($protocol{$spare_server} eq 'https') {
                    867:             $protocol = $protocol{$spare_server};
                    868:         }
1.1001    raeburn   869:         if (defined($spare_server)) {
                    870:             my $hostname = &hostname($spare_server);
1.1083    raeburn   871:             if (defined($hostname)) {
1.1001    raeburn   872: 	        $spare_server = $protocol.'://'.$hostname;
                    873:             }
                    874:         }
1.784     albertel  875:     }
                    876:     return $spare_server;
                    877: }
                    878: 
                    879: sub compare_server_load {
                    880:     my ($try_server, $spare_server, $lowest_load) = @_;
                    881: 
                    882:     my $loadans     = &reply('load',    $try_server);
                    883:     my $userloadans = &reply('userload',$try_server);
                    884: 
                    885:     if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114    raeburn   886: 	return ($spare_server, $lowest_load); #didn't get a number from the server
1.784     albertel  887:     }
                    888: 
                    889:     my $load;
                    890:     if ($loadans =~ /\d/) {
                    891: 	if ($userloadans =~ /\d/) {
                    892: 	    #both are numbers, pick the bigger one
                    893: 	    $load = ($loadans > $userloadans) ? $loadans 
                    894: 		                              : $userloadans;
1.411     albertel  895: 	} else {
1.784     albertel  896: 	    $load = $loadans;
1.411     albertel  897: 	}
1.784     albertel  898:     } else {
                    899: 	$load = $userloadans;
                    900:     }
                    901: 
                    902:     if (($load =~ /\d/) && ($load < $lowest_load)) {
                    903: 	$spare_server = $try_server;
                    904: 	$lowest_load  = $load;
1.370     albertel  905:     }
1.784     albertel  906:     return ($spare_server,$lowest_load);
1.202     matthew   907: }
1.914     albertel  908: 
                    909: # --------------------------- ask offload servers if user already has a session
                    910: sub find_existing_session {
                    911:     my ($udom,$uname) = @_;
1.1123    raeburn   912:     my $spareshash = &this_host_spares($udom);
                    913:     if (ref($spareshash) eq 'HASH') {
                    914:         if (ref($spareshash->{'primary'}) eq 'ARRAY') {
                    915:             foreach my $try_server (@{ $spareshash->{'primary'} }) {
                    916:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    917:             }
                    918:         }
                    919:         if (ref($spareshash->{'default'}) eq 'ARRAY') {
                    920:             foreach my $try_server (@{ $spareshash->{'default'} }) {
                    921:                 return $try_server if (&has_user_session($try_server, $udom, $uname));
                    922:             }
                    923:         }
1.914     albertel  924:     }
                    925:     return;
                    926: }
                    927: 
                    928: # -------------------------------- ask if server already has a session for user
                    929: sub has_user_session {
                    930:     my ($lonid,$udom,$uname) = @_;
                    931:     my $result = &reply(join(':','userhassession',
                    932: 			     map {&escape($_)} ($udom,$uname)),$lonid);
                    933:     return 1 if ($result eq 'ok');
                    934: 
                    935:     return 0;
                    936: }
                    937: 
1.1076    raeburn   938: # --------- determine least loaded server in a user's domain which allows login
                    939: 
                    940: sub choose_server {
1.1115    raeburn   941:     my ($udom,$checkloginvia) = @_;
1.1076    raeburn   942:     my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077    raeburn   943:     my %servers = &get_servers($udom);
1.1076    raeburn   944:     my $lowest_load = 30000;
1.1151    raeburn   945:     my ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   946:     foreach my $lonhost (keys(%servers)) {
1.1115    raeburn   947:         my $loginvia;
                    948:         if ($checkloginvia) {
                    949:             $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116    raeburn   950:             if ($loginvia) {
                    951:                 my ($server,$path) = split(/:/,$loginvia);
                    952:                 ($login_host, $lowest_load) =
                    953:                     &compare_server_load($server, $login_host, $lowest_load);
                    954:                 if ($login_host eq $server) {
                    955:                     $portal_path = $path;
1.1151    raeburn   956:                     $isredirect = 1;
1.1116    raeburn   957:                 }
                    958:             } else {
                    959:                 ($login_host, $lowest_load) =
                    960:                     &compare_server_load($lonhost, $login_host, $lowest_load);
                    961:                 if ($login_host eq $lonhost) {
                    962:                     $portal_path = '';
1.1151    raeburn   963:                     $isredirect = ''; 
1.1116    raeburn   964:                 }
                    965:             }
                    966:         } else {
1.1076    raeburn   967:             ($login_host, $lowest_load) =
1.1116    raeburn   968:                 &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076    raeburn   969:         }
                    970:     }
                    971:     if ($login_host ne '') {
1.1116    raeburn   972:         $hostname = &hostname($login_host);
1.1076    raeburn   973:     }
1.1151    raeburn   974:     return ($login_host,$hostname,$portal_path,$isredirect);
1.1076    raeburn   975: }
                    976: 
1.202     matthew   977: # --------------------------------------------- Try to change a user's password
                    978: 
                    979: sub changepass {
1.799     raeburn   980:     my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202     matthew   981:     $currentpass = &escape($currentpass);
                    982:     $newpass     = &escape($newpass);
1.1030    raeburn   983:     my $lonhost = $perlvar{'lonHostID'};
                    984:     my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202     matthew   985: 		       $server);
                    986:     if (! $answer) {
                    987: 	&logthis("No reply on password change request to $server ".
                    988: 		 "by $uname in domain $udom.");
                    989:     } elsif ($answer =~ "^ok") {
                    990:         &logthis("$uname in $udom successfully changed their password ".
                    991: 		 "on $server.");
                    992:     } elsif ($answer =~ "^pwchange_failure") {
                    993: 	&logthis("$uname in $udom was unable to change their password ".
                    994: 		 "on $server.  The action was blocked by either lcpasswd ".
                    995: 		 "or pwchange");
                    996:     } elsif ($answer =~ "^non_authorized") {
                    997:         &logthis("$uname in $udom did not get their password correct when ".
                    998: 		 "attempting to change it on $server.");
                    999:     } elsif ($answer =~ "^auth_mode_error") {
                   1000:         &logthis("$uname in $udom attempted to change their password despite ".
                   1001: 		 "not being locally or internally authenticated on $server.");
                   1002:     } elsif ($answer =~ "^unknown_user") {
                   1003:         &logthis("$uname in $udom attempted to change their password ".
                   1004: 		 "on $server but were unable to because $server is not ".
                   1005: 		 "their home server.");
                   1006:     } elsif ($answer =~ "^refused") {
                   1007: 	&logthis("$server refused to change $uname in $udom password because ".
                   1008: 		 "it was sent an unencrypted request to change the password.");
1.1030    raeburn  1009:     } elsif ($answer =~ "invalid_client") {
                   1010:         &logthis("$server refused to change $uname in $udom password because ".
                   1011:                  "it was a reset by e-mail originating from an invalid server.");
1.202     matthew  1012:     }
                   1013:     return $answer;
1.1       albertel 1014: }
                   1015: 
1.169     harris41 1016: # ----------------------- Try to determine user's current authentication scheme
                   1017: 
                   1018: sub queryauthenticate {
                   1019:     my ($uname,$udom)=@_;
1.456     albertel 1020:     my $uhome=&homeserver($uname,$udom);
                   1021:     if (!$uhome) {
                   1022: 	&logthis("User $uname at $udom is unknown when looking for authentication mechanism");
                   1023: 	return 'no_host';
                   1024:     }
                   1025:     my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
                   1026:     if ($answer =~ /^(unknown_user|refused|con_lost)/) {
                   1027: 	&logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169     harris41 1028:     }
1.456     albertel 1029:     return $answer;
1.169     harris41 1030: }
                   1031: 
1.1       albertel 1032: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11      www      1033: 
1.1       albertel 1034: sub authenticate {
1.1073    raeburn  1035:     my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807     albertel 1036:     $upass=&escape($upass);
                   1037:     $uname= &LONCAPA::clean_username($uname);
1.836     www      1038:     my $uhome=&homeserver($uname,$udom,1);
1.952     raeburn  1039:     my $newhome;
1.836     www      1040:     if ((!$uhome) || ($uhome eq 'no_host')) {
                   1041: # Maybe the machine was offline and only re-appeared again recently?
                   1042:         &reconlonc();
                   1043: # One more
1.952     raeburn  1044: 	$uhome=&homeserver($uname,$udom,1);
                   1045:         if (($uhome eq 'no_host') && $checkdefauth) {
                   1046:             if (defined(&domain($udom,'primary'))) {
                   1047:                 $newhome=&domain($udom,'primary');
                   1048:             }
                   1049:             if ($newhome ne '') {
                   1050:                 $uhome = $newhome;
                   1051:             }
                   1052:         }
1.836     www      1053: 	if ((!$uhome) || ($uhome eq 'no_host')) {
                   1054: 	    &logthis("User $uname at $udom is unknown in authenticate");
1.952     raeburn  1055: 	    return 'no_host';
                   1056:         }
1.1       albertel 1057:     }
1.1073    raeburn  1058:     my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471     albertel 1059:     if ($answer eq 'authorized') {
1.952     raeburn  1060:         if ($newhome) {
                   1061:             &logthis("User $uname at $udom authorized by $uhome, but needs account");
                   1062:             return 'no_account_on_host'; 
                   1063:         } else {
                   1064:             &logthis("User $uname at $udom authorized by $uhome");
                   1065:             return $uhome;
                   1066:         }
1.471     albertel 1067:     }
                   1068:     if ($answer eq 'non_authorized') {
                   1069: 	&logthis("User $uname at $udom rejected by $uhome");
                   1070: 	return 'no_host'; 
1.9       www      1071:     }
1.471     albertel 1072:     &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1       albertel 1073:     return 'no_host';
                   1074: }
                   1075: 
1.1073    raeburn  1076: sub can_host_session {
1.1074    raeburn  1077:     my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073    raeburn  1078:     my $canhost = 1;
1.1074    raeburn  1079:     my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073    raeburn  1080:     if (ref($remotesessions) eq 'HASH') {
                   1081:         if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074    raeburn  1082:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073    raeburn  1083:                 $canhost = 0;
                   1084:             } else {
                   1085:                 $canhost = 1;
                   1086:             }
                   1087:         }
                   1088:         if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074    raeburn  1089:             if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073    raeburn  1090:                 $canhost = 1;
                   1091:             } else {
                   1092:                 $canhost = 0;
                   1093:             }
                   1094:         }
                   1095:         if ($canhost) {
                   1096:             if ($remotesessions->{'version'} ne '') {
                   1097:                 my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
                   1098:                 if ($reqmajor ne '' && $reqminor ne '') {
                   1099:                     if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
                   1100:                         my $major = $1;
                   1101:                         my $minor = $2;
                   1102:                         if (($major < $reqmajor ) ||
                   1103:                             (($major == $reqmajor) && ($minor < $reqminor))) {
                   1104:                             $canhost = 0;
                   1105:                         }
                   1106:                     } else {
                   1107:                         $canhost = 0;
                   1108:                     }
                   1109:                 }
                   1110:             }
                   1111:         }
                   1112:     }
                   1113:     if ($canhost) {
                   1114:         if (ref($hostedsessions) eq 'HASH') {
1.1120    raeburn  1115:             my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1116:             my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073    raeburn  1117:             if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120    raeburn  1118:                 if (($uint_dom ne '') && 
                   1119:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073    raeburn  1120:                     $canhost = 0;
                   1121:                 } else {
                   1122:                     $canhost = 1;
                   1123:                 }
                   1124:             }
                   1125:             if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120    raeburn  1126:                 if (($uint_dom ne '') && 
                   1127:                     (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073    raeburn  1128:                     $canhost = 1;
                   1129:                 } else {
                   1130:                     $canhost = 0;
                   1131:                 }
                   1132:             }
                   1133:         }
                   1134:     }
                   1135:     return $canhost;
                   1136: }
                   1137: 
1.1083    raeburn  1138: sub spare_can_host {
                   1139:     my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
                   1140:     my $canhost=1;
                   1141:     my @intdoms;
                   1142:     my $internet_names = &Apache::lonnet::get_internet_names($try_server);
                   1143:     if (ref($internet_names) eq 'ARRAY') {
                   1144:         @intdoms = @{$internet_names};
                   1145:     }
                   1146:     unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
                   1147:         my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
                   1148:         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   1149:         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   1150:         my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
                   1151:         $canhost = &can_host_session($udom,$try_server,$remoterev,
                   1152:                                      $remotesessions,
                   1153:                                      $defdomdefaults{'hostedsessions'});
                   1154:     }
                   1155:     return $canhost;
                   1156: }
                   1157: 
1.1123    raeburn  1158: sub this_host_spares {
                   1159:     my ($dom) = @_;
1.1126    raeburn  1160:     my ($dom_in_use,$lonhost_in_use,$result);
1.1123    raeburn  1161:     my @hosts = &current_machine_ids();
                   1162:     foreach my $lonhost (@hosts) {
                   1163:         if (&host_domain($lonhost) eq $dom) {
1.1126    raeburn  1164:             $dom_in_use = $dom;
                   1165:             $lonhost_in_use = $lonhost;
1.1123    raeburn  1166:             last;
                   1167:         }
                   1168:     }
1.1126    raeburn  1169:     if ($dom_in_use ne '') {
                   1170:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1171:     }
                   1172:     if (ref($result) ne 'HASH') {
                   1173:         $lonhost_in_use = $perlvar{'lonHostID'};
                   1174:         $dom_in_use = &host_domain($lonhost_in_use);
                   1175:         $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
                   1176:         if (ref($result) ne 'HASH') {
                   1177:             $result = \%spareid;
                   1178:         }
                   1179:     }
                   1180:     return $result;
                   1181: }
                   1182: 
                   1183: sub spares_for_offload  {
                   1184:     my ($dom_in_use,$lonhost_in_use) = @_;
                   1185:     my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123    raeburn  1186:     if (defined($cached)) {
                   1187:         return $result;
                   1188:     } else {
1.1126    raeburn  1189:         my $cachetime = 60*60*24;
                   1190:         my %domconfig =
                   1191:             &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
                   1192:         if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1193:             if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
                   1194:                 if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
                   1195:                     return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123    raeburn  1196:                 }
                   1197:             }
                   1198:         }
                   1199:     }
1.1126    raeburn  1200:     return;
1.1123    raeburn  1201: }
                   1202: 
1.1129    raeburn  1203: sub get_lonbalancer_config {
                   1204:     my ($servers) = @_;
                   1205:     my ($currbalancer,$currtargets);
                   1206:     if (ref($servers) eq 'HASH') {
                   1207:         foreach my $server (keys(%{$servers})) {
                   1208:             my %what = (
                   1209:                          spareid => 1,
                   1210:                          perlvar => 1,
                   1211:                        );
                   1212:             my ($result,$returnhash) = &get_remote_globals($server,\%what);
                   1213:             if ($result eq 'ok') {
                   1214:                 if (ref($returnhash) eq 'HASH') {
                   1215:                     if (ref($returnhash->{'perlvar'}) eq 'HASH') {
                   1216:                         if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
                   1217:                             $currbalancer = $server;
                   1218:                             $currtargets = {};
                   1219:                             if (ref($returnhash->{'spareid'}) eq 'HASH') {
                   1220:                                 if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
                   1221:                                     $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
                   1222:                                 }
                   1223:                                 if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
                   1224:                                     $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
                   1225:                                 }
                   1226:                             }
                   1227:                             last;
                   1228:                         }
                   1229:                     }
                   1230:                 }
                   1231:             }
                   1232:         }
                   1233:     }
                   1234:     return ($currbalancer,$currtargets);
                   1235: }
                   1236: 
                   1237: sub check_loadbalancing {
                   1238:     my ($uname,$udom) = @_;
                   1239:     my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
                   1240:         $offloadto,$otherserver);
                   1241:     my $lonhost = $perlvar{'lonHostID'};
1.1175  ! raeburn  1242:     my @hosts = &current_machine_ids();
1.1129    raeburn  1243:     my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
                   1244:     my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
                   1245:     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   1246:     my $serverhomedom = &host_domain($lonhost);
                   1247: 
                   1248:     my $cachetime = 60*60*24;
                   1249: 
                   1250:     if (($uintdom ne '') && ($uintdom eq $intdom)) {
                   1251:         $dom_in_use = $udom;
                   1252:         $homeintdom = 1;
                   1253:     } else {
                   1254:         $dom_in_use = $serverhomedom;
                   1255:     }
                   1256:     my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
                   1257:     unless (defined($cached)) {
                   1258:         my %domconfig =
                   1259:             &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
                   1260:         if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1261:             $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1262:         }
                   1263:     }
                   1264:     if (ref($result) eq 'HASH') {
                   1265:         my $currbalancer = $result->{'lonhost'};
                   1266:         my $currtargets = $result->{'targets'};
                   1267:         my $currrules = $result->{'rules'};
                   1268:         if ($currbalancer ne '') {
                   1269:             if (grep(/^\Q$currbalancer\E$/,@hosts)) {
                   1270:                 $is_balancer = 1;
                   1271:             }
                   1272:         }
                   1273:         if ($is_balancer) {
                   1274:             if (ref($currrules) eq 'HASH') {
                   1275:                 if ($homeintdom) {
                   1276:                     if ($uname ne '') {
                   1277:                         if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
                   1278:                             my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
                   1279:                             if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
                   1280:                                 $rule_in_effect = $currrules->{'_LC_author'};
                   1281:                             } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
                   1282:                                 $rule_in_effect = $currrules->{'_LC_adv'}
                   1283:                             }
                   1284:                         }
                   1285:                         if ($rule_in_effect eq '') {
                   1286:                             my %userenv = &userenvironment($udom,$uname,'inststatus');
                   1287:                             if ($userenv{'inststatus'} ne '') {
                   1288:                                 my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
                   1289:                                 my ($othertitle,$usertypes,$types) =
                   1290:                                     &Apache::loncommon::sorted_inst_types($udom);
                   1291:                                 if (ref($types) eq 'ARRAY') {
                   1292:                                     foreach my $type (@{$types}) {
                   1293:                                         if (grep(/^\Q$type\E$/,@statuses)) {
                   1294:                                             if (exists($currrules->{$type})) {
                   1295:                                                 $rule_in_effect = $currrules->{$type};
                   1296:                                             }
                   1297:                                         }
                   1298:                                     }
                   1299:                                 }
                   1300:                             } else {
                   1301:                                 if (exists($currrules->{'default'})) {
                   1302:                                     $rule_in_effect = $currrules->{'default'};
                   1303:                                 }
                   1304:                             }
                   1305:                         }
                   1306:                     } else {
                   1307:                         if (exists($currrules->{'default'})) {
                   1308:                             $rule_in_effect = $currrules->{'default'};
                   1309:                         }
                   1310:                     }
                   1311:                 } else {
                   1312:                     if ($currrules->{'_LC_external'} ne '') {
                   1313:                         $rule_in_effect = $currrules->{'_LC_external'};
                   1314:                     }
                   1315:                 }
                   1316:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1317:                                                        $uname,$udom);
                   1318:             }
                   1319:         }
                   1320:     } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
                   1321:         my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
                   1322:         unless (defined($cached)) {
                   1323:             my %domconfig =
                   1324:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
                   1325:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130    raeburn  1326:                 $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129    raeburn  1327:             }
                   1328:         }
                   1329:         if (ref($result) eq 'HASH') {
                   1330:             my $currbalancer = $result->{'lonhost'};
                   1331:             my $currtargets = $result->{'targets'};
                   1332:             my $currrules = $result->{'rules'};
                   1333: 
                   1334:             if ($currbalancer eq $lonhost) {
                   1335:                 $is_balancer = 1;
                   1336:                 if (ref($currrules) eq 'HASH') {
                   1337:                     if ($currrules->{'_LC_internetdom'} ne '') {
                   1338:                         $rule_in_effect = $currrules->{'_LC_internetdom'};
                   1339:                     }
                   1340:                 }
                   1341:                 $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
                   1342:                                                        $uname,$udom);
                   1343:             }
                   1344:         } else {
                   1345:             if ($perlvar{'lonBalancer'} eq 'yes') {
                   1346:                 $is_balancer = 1;
                   1347:                 $offloadto = &this_host_spares($dom_in_use);
                   1348:             }
                   1349:         }
                   1350:     } else {
                   1351:         if ($perlvar{'lonBalancer'} eq 'yes') {
                   1352:             $is_balancer = 1;
                   1353:             $offloadto = &this_host_spares($dom_in_use);
                   1354:         }
                   1355:     }
                   1356:     my $lowest_load = 30000;
                   1357:     if (ref($offloadto) eq 'HASH') {
                   1358:         if (ref($offloadto->{'primary'}) eq 'ARRAY') {
                   1359:             foreach my $try_server (@{$offloadto->{'primary'}}) {
                   1360:                 ($otherserver,$lowest_load) =
                   1361:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1362:             }
                   1363:         }
                   1364:         my $found_server = ($otherserver ne '' && $lowest_load < 100);
                   1365: 
                   1366:         if (!$found_server) {
                   1367:             if (ref($offloadto->{'default'}) eq 'ARRAY') {
                   1368:                 foreach my $try_server (@{$offloadto->{'default'}}) {
                   1369:                     ($otherserver,$lowest_load) =
                   1370:                         &compare_server_load($try_server,$otherserver,$lowest_load);
                   1371:                 }
                   1372:             }
                   1373:         }
                   1374:     } elsif (ref($offloadto) eq 'ARRAY') {
                   1375:         if (@{$offloadto} == 1) {
                   1376:             $otherserver = $offloadto->[0];
                   1377:         } elsif (@{$offloadto} > 1) {
                   1378:             foreach my $try_server (@{$offloadto}) {
                   1379:                 ($otherserver,$lowest_load) =
                   1380:                     &compare_server_load($try_server,$otherserver,$lowest_load);
                   1381:             }
                   1382:         }
                   1383:     }
1.1175  ! raeburn  1384:     if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
        !          1385:         $is_balancer = 0;
        !          1386:     }
1.1129    raeburn  1387:     return ($is_balancer,$otherserver);
                   1388: }
                   1389: 
                   1390: sub get_loadbalancer_targets {
                   1391:     my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
                   1392:     my $offloadto;
1.1175  ! raeburn  1393:     if ($rule_in_effect eq 'none') {
        !          1394:         return [$perlvar{'lonHostID'}];
        !          1395:     } elsif ($rule_in_effect eq '') {
1.1129    raeburn  1396:         $offloadto = $currtargets;
                   1397:     } else {
                   1398:         if ($rule_in_effect eq 'homeserver') {
                   1399:             my $homeserver = &homeserver($uname,$udom);
                   1400:             if ($homeserver ne 'no_host') {
                   1401:                 $offloadto = [$homeserver];
                   1402:             }
                   1403:         } elsif ($rule_in_effect eq 'externalbalancer') {
                   1404:             my %domconfig =
                   1405:                 &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
                   1406:             if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
                   1407:                 if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
                   1408:                     if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
                   1409:                         $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
                   1410:                     }
                   1411:                 }
                   1412:             } else {
                   1413:                 my %servers = &dom_servers($udom);
                   1414:                 my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
                   1415:                 if (&hostname($remotebalancer) ne '') {
                   1416:                     $offloadto = [$remotebalancer];
                   1417:                 }
                   1418:             }
                   1419:         } elsif (&hostname($rule_in_effect) ne '') {
                   1420:             $offloadto = [$rule_in_effect];
                   1421:         }
                   1422:     }
                   1423:     return $offloadto;
                   1424: }
                   1425: 
1.1127    raeburn  1426: sub internet_dom_servers {
                   1427:     my ($dom) = @_;
                   1428:     my (%uniqservers,%servers);
                   1429:     my $primaryserver = &hostname(&domain($dom,'primary'));
                   1430:     my @machinedoms = &machine_domains($primaryserver);
                   1431:     foreach my $mdom (@machinedoms) {
                   1432:         my %currservers = %servers;
                   1433:         my %server = &get_servers($mdom);
                   1434:         %servers = (%currservers,%server);
                   1435:     }
                   1436:     my %by_hostname;
                   1437:     foreach my $id (keys(%servers)) {
                   1438:         push(@{$by_hostname{$servers{$id}}},$id);
                   1439:     }
                   1440:     foreach my $hostname (sort(keys(%by_hostname))) {
                   1441:         if (@{$by_hostname{$hostname}} > 1) {
                   1442:             my $match = 0;
                   1443:             foreach my $id (@{$by_hostname{$hostname}}) {
                   1444:                 if (&host_domain($id) eq $dom) {
                   1445:                     $uniqservers{$id} = $hostname;
                   1446:                     $match = 1;
                   1447:                 }
                   1448:             }
                   1449:             unless ($match) {
                   1450:                 $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1451:             }
                   1452:         } else {
                   1453:             $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
                   1454:         }
                   1455:     }
                   1456:     return %uniqservers;
                   1457: }
                   1458: 
1.1       albertel 1459: # ---------------------- Find the homebase for a user from domain's lib servers
1.11      www      1460: 
1.599     albertel 1461: my %homecache;
1.1       albertel 1462: sub homeserver {
1.230     stredwic 1463:     my ($uname,$udom,$ignoreBadCache)=@_;
1.1       albertel 1464:     my $index="$uname:$udom";
1.426     albertel 1465: 
1.599     albertel 1466:     if (exists($homecache{$index})) { return $homecache{$index}; }
1.841     albertel 1467: 
                   1468:     my %servers = &get_servers($udom,'library');
                   1469:     foreach my $tryserver (keys(%servers)) {
1.230     stredwic 1470:         next if ($ignoreBadCache ne 'true' && 
1.231     stredwic 1471: 		 exists($badServerCache{$tryserver}));
1.841     albertel 1472: 
                   1473: 	my $answer=reply("home:$udom:$uname",$tryserver);
                   1474: 	if ($answer eq 'found') {
                   1475: 	    delete($badServerCache{$tryserver}); 
                   1476: 	    return $homecache{$index}=$tryserver;
                   1477: 	} elsif ($answer eq 'no_host') {
                   1478: 	    $badServerCache{$tryserver}=1;
                   1479: 	}
1.1       albertel 1480:     }    
                   1481:     return 'no_host';
1.70      www      1482: }
                   1483: 
                   1484: # ------------------------------------- Find the usernames behind a list of IDs
                   1485: 
                   1486: sub idget {
                   1487:     my ($udom,@ids)=@_;
                   1488:     my %returnhash=();
                   1489:     
1.841     albertel 1490:     my %servers = &get_servers($udom,'library');
                   1491:     foreach my $tryserver (keys(%servers)) {
                   1492: 	my $idlist=join('&',@ids);
                   1493: 	$idlist=~tr/A-Z/a-z/; 
                   1494: 	my $reply=&reply("idget:$udom:".$idlist,$tryserver);
                   1495: 	my @answer=();
                   1496: 	if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
                   1497: 	    @answer=split(/\&/,$reply);
                   1498: 	}                    ;
                   1499: 	my $i;
                   1500: 	for ($i=0;$i<=$#ids;$i++) {
                   1501: 	    if ($answer[$i]) {
                   1502: 		$returnhash{$ids[$i]}=$answer[$i];
                   1503: 	    } 
                   1504: 	}
                   1505:     } 
1.70      www      1506:     return %returnhash;
                   1507: }
                   1508: 
                   1509: # ------------------------------------- Find the IDs behind a list of usernames
                   1510: 
                   1511: sub idrget {
                   1512:     my ($udom,@unames)=@_;
                   1513:     my %returnhash=();
1.800     albertel 1514:     foreach my $uname (@unames) {
                   1515:         $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191     harris41 1516:     }
1.70      www      1517:     return %returnhash;
                   1518: }
                   1519: 
                   1520: # ------------------------------- Store away a list of names and associated IDs
                   1521: 
                   1522: sub idput {
                   1523:     my ($udom,%ids)=@_;
                   1524:     my %servers=();
1.800     albertel 1525:     foreach my $uname (keys(%ids)) {
                   1526: 	&cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
                   1527:         my $uhom=&homeserver($uname,$udom);
1.70      www      1528:         if ($uhom ne 'no_host') {
1.800     albertel 1529:             my $id=&escape($ids{$uname});
1.70      www      1530:             $id=~tr/A-Z/a-z/;
1.800     albertel 1531:             my $esc_unam=&escape($uname);
1.70      www      1532: 	    if ($servers{$uhom}) {
1.800     albertel 1533: 		$servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70      www      1534:             } else {
1.800     albertel 1535:                 $servers{$uhom}=$id.'='.$esc_unam;
1.70      www      1536:             }
                   1537:         }
1.191     harris41 1538:     }
1.800     albertel 1539:     foreach my $server (keys(%servers)) {
                   1540:         &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191     harris41 1541:     }
1.344     www      1542: }
                   1543: 
1.1023    raeburn  1544: # ------------------------------dump from db file owned by domainconfig user
1.1012    raeburn  1545: sub dump_dom {
1.1165    droeschl 1546:     my ($namespace, $udom, $regexp) = @_;
                   1547: 
                   1548:     $udom ||= $env{'user.domain'};
                   1549: 
                   1550:     return () unless $udom;
                   1551: 
                   1552:     return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012    raeburn  1553: }
                   1554: 
1.1023    raeburn  1555: # ------------------------------------------ get items from domain db files   
1.806     raeburn  1556: 
                   1557: sub get_dom {
1.860     raeburn  1558:     my ($namespace,$storearr,$udom,$uhome)=@_;
1.806     raeburn  1559:     my $items='';
                   1560:     foreach my $item (@$storearr) {
                   1561:         $items.=&escape($item).'&';
                   1562:     }
                   1563:     $items=~s/\&$//;
1.860     raeburn  1564:     if (!$udom) {
                   1565:         $udom=$env{'user.domain'};
                   1566:         if (defined(&domain($udom,'primary'))) {
                   1567:             $uhome=&domain($udom,'primary');
                   1568:         } else {
1.874     albertel 1569:             undef($uhome);
1.860     raeburn  1570:         }
                   1571:     } else {
                   1572:         if (!$uhome) {
                   1573:             if (defined(&domain($udom,'primary'))) {
                   1574:                 $uhome=&domain($udom,'primary');
                   1575:             }
                   1576:         }
                   1577:     }
                   1578:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1579:         my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866     raeburn  1580:         my %returnhash;
1.875     albertel 1581:         if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866     raeburn  1582:             return %returnhash;
                   1583:         }
1.806     raeburn  1584:         my @pairs=split(/\&/,$rep);
                   1585:         if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   1586:             return @pairs;
                   1587:         }
                   1588:         my $i=0;
                   1589:         foreach my $item (@$storearr) {
                   1590:             $returnhash{$item}=&thaw_unescape($pairs[$i]);
                   1591:             $i++;
                   1592:         }
                   1593:         return %returnhash;
                   1594:     } else {
1.880     banghart 1595:         &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806     raeburn  1596:     }
                   1597: }
                   1598: 
                   1599: # -------------------------------------------- put items in domain db files 
                   1600: 
                   1601: sub put_dom {
1.860     raeburn  1602:     my ($namespace,$storehash,$udom,$uhome)=@_;
                   1603:     if (!$udom) {
                   1604:         $udom=$env{'user.domain'};
                   1605:         if (defined(&domain($udom,'primary'))) {
                   1606:             $uhome=&domain($udom,'primary');
                   1607:         } else {
1.874     albertel 1608:             undef($uhome);
1.860     raeburn  1609:         }
                   1610:     } else {
                   1611:         if (!$uhome) {
                   1612:             if (defined(&domain($udom,'primary'))) {
                   1613:                 $uhome=&domain($udom,'primary');
                   1614:             }
                   1615:         }
                   1616:     } 
                   1617:     if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806     raeburn  1618:         my $items='';
                   1619:         foreach my $item (keys(%$storehash)) {
                   1620:             $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
                   1621:         }
                   1622:         $items=~s/\&$//;
                   1623:         return &reply("putdom:$udom:$namespace:$items",$uhome);
                   1624:     } else {
1.860     raeburn  1625:         &logthis("put_dom failed - no homeserver and/or domain");
1.806     raeburn  1626:     }
                   1627: }
                   1628: 
1.1023    raeburn  1629: # --------------------- newput for items in db file owned by domainconfig user
1.1012    raeburn  1630: sub newput_dom {
1.1023    raeburn  1631:     my ($namespace,$storehash,$udom) = @_;
1.1012    raeburn  1632:     my $result;
                   1633:     if (!$udom) {
                   1634:         $udom=$env{'user.domain'};
                   1635:     }
1.1023    raeburn  1636:     if ($udom) {
                   1637:         my $uname = &get_domainconfiguser($udom);
                   1638:         $result = &newput($namespace,$storehash,$udom,$uname);
1.1012    raeburn  1639:     }
                   1640:     return $result;
                   1641: }
                   1642: 
1.1023    raeburn  1643: # --------------------- delete for items in db file owned by domainconfig user
1.1012    raeburn  1644: sub del_dom {
1.1023    raeburn  1645:     my ($namespace,$storearr,$udom)=@_;
1.1012    raeburn  1646:     if (ref($storearr) eq 'ARRAY') {
                   1647:         if (!$udom) {
                   1648:             $udom=$env{'user.domain'};
                   1649:         }
1.1023    raeburn  1650:         if ($udom) {
                   1651:             my $uname = &get_domainconfiguser($udom); 
                   1652:             return &del($namespace,$storearr,$udom,$uname);
1.1012    raeburn  1653:         }
                   1654:     }
                   1655: }
                   1656: 
1.1023    raeburn  1657: # ----------------------------------construct domainconfig user for a domain 
                   1658: sub get_domainconfiguser {
                   1659:     my ($udom) = @_;
                   1660:     return $udom.'-domainconfig';
                   1661: }
                   1662: 
1.837     raeburn  1663: sub retrieve_inst_usertypes {
                   1664:     my ($udom) = @_;
                   1665:     my (%returnhash,@order);
1.989     raeburn  1666:     my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
                   1667:     if ((ref($domdefs{'inststatustypes'}) eq 'HASH') && 
                   1668:         (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
                   1669:         %returnhash = %{$domdefs{'inststatustypes'}};
                   1670:         @order = @{$domdefs{'inststatusorder'}};
                   1671:     } else {
                   1672:         if (defined(&domain($udom,'primary'))) {
                   1673:             my $uhome=&domain($udom,'primary');
                   1674:             my $rep=&reply("inst_usertypes:$udom",$uhome);
                   1675:             if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
                   1676:                 &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
                   1677:                 return (\%returnhash,\@order);
                   1678:             }
                   1679:             my ($hashitems,$orderitems) = split(/:/,$rep); 
                   1680:             my @pairs=split(/\&/,$hashitems);
                   1681:             foreach my $item (@pairs) {
                   1682:                 my ($key,$value)=split(/=/,$item,2);
                   1683:                 $key = &unescape($key);
                   1684:                 next if ($key =~ /^error: 2 /);
                   1685:                 $returnhash{$key}=&thaw_unescape($value);
                   1686:             }
                   1687:             my @esc_order = split(/\&/,$orderitems);
                   1688:             foreach my $item (@esc_order) {
                   1689:                 push(@order,&unescape($item));
                   1690:             }
                   1691:         } else {
                   1692:             &logthis("get_dom failed - no primary domain server for $udom");
1.837     raeburn  1693:         }
                   1694:     }
                   1695:     return (\%returnhash,\@order);
                   1696: }
                   1697: 
1.868     raeburn  1698: sub is_domainimage {
                   1699:     my ($url) = @_;
                   1700:     if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
                   1701:         if (&domain($1) ne '') {
                   1702:             return '1';
                   1703:         }
                   1704:     }
                   1705:     return;
                   1706: }
                   1707: 
1.899     raeburn  1708: sub inst_directory_query {
                   1709:     my ($srch) = @_;
                   1710:     my $udom = $srch->{'srchdomain'};
                   1711:     my %results;
                   1712:     my $homeserver = &domain($udom,'primary');
1.909     raeburn  1713:     my $outcome;
1.899     raeburn  1714:     if ($homeserver ne '') {
1.904     albertel 1715: 	my $queryid=&reply("querysend:instdirsearch:".
                   1716: 			   &escape($srch->{'srchby'}).':'.
                   1717: 			   &escape($srch->{'srchterm'}).':'.
                   1718: 			   &escape($srch->{'srchtype'}),$homeserver);
                   1719: 	my $host=&hostname($homeserver);
                   1720: 	if ($queryid !~/^\Q$host\E\_/) {
                   1721: 	    &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1722: 	    return;
                   1723: 	}
                   1724: 	my $response = &get_query_reply($queryid);
                   1725: 	my $maxtries = 5;
                   1726: 	my $tries = 1;
                   1727: 	while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1728: 	    $response = &get_query_reply($queryid);
                   1729: 	    $tries ++;
                   1730: 	}
                   1731: 
                   1732:         if (!&error($response) && $response ne 'refused') {
1.909     raeburn  1733:             if ($response eq 'unavailable') {
                   1734:                 $outcome = $response;
                   1735:             } else {
                   1736:                 $outcome = 'ok';
                   1737:                 my @matches = split(/\n/,$response);
                   1738:                 foreach my $match (@matches) {
                   1739:                     my ($key,$value) = split(/=/,$match);
                   1740:                     $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
                   1741:                 }
1.899     raeburn  1742:             }
                   1743:         }
                   1744:     }
1.909     raeburn  1745:     return ($outcome,%results);
1.899     raeburn  1746: }
                   1747: 
                   1748: sub usersearch {
                   1749:     my ($srch) = @_;
                   1750:     my $dom = $srch->{'srchdomain'};
                   1751:     my %results;
                   1752:     my %libserv = &all_library();
                   1753:     my $query = 'usersearch';
                   1754:     foreach my $tryserver (keys(%libserv)) {
                   1755:         if (&host_domain($tryserver) eq $dom) {
                   1756:             my $host=&hostname($tryserver);
                   1757:             my $queryid=
1.911     raeburn  1758:                 &reply("querysend:".&escape($query).':'.
                   1759:                        &escape($srch->{'srchby'}).':'.
1.899     raeburn  1760:                        &escape($srch->{'srchtype'}).':'.
                   1761:                        &escape($srch->{'srchterm'}),$tryserver);
                   1762:             if ($queryid !~/^\Q$host\E\_/) {
                   1763:                 &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902     raeburn  1764:                 next;
1.899     raeburn  1765:             }
                   1766:             my $reply = &get_query_reply($queryid);
                   1767:             my $maxtries = 1;
                   1768:             my $tries = 1;
                   1769:             while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   1770:                 $reply = &get_query_reply($queryid);
                   1771:                 $tries ++;
                   1772:             }
                   1773:             if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   1774:                 &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') -  maxtries: '.$maxtries.' tries: '.$tries);
                   1775:             } else {
1.911     raeburn  1776:                 my @matches;
                   1777:                 if ($reply =~ /\n/) {
                   1778:                     @matches = split(/\n/,$reply);
                   1779:                 } else {
                   1780:                     @matches = split(/\&/,$reply);
                   1781:                 }
1.899     raeburn  1782:                 foreach my $match (@matches) {
                   1783:                     my ($uname,$udom,%userhash);
1.911     raeburn  1784:                     foreach my $entry (split(/:/,$match)) {
                   1785:                         my ($key,$value) =
                   1786:                             map {&unescape($_);} split(/=/,$entry);
1.899     raeburn  1787:                         $userhash{$key} = $value;
                   1788:                         if ($key eq 'username') {
                   1789:                             $uname = $value;
                   1790:                         } elsif ($key eq 'domain') {
                   1791:                             $udom = $value;
1.911     raeburn  1792:                         }
1.899     raeburn  1793:                     }
                   1794:                     $results{$uname.':'.$udom} = \%userhash;
                   1795:                 }
                   1796:             }
                   1797:         }
                   1798:     }
                   1799:     return %results;
                   1800: }
                   1801: 
1.912     raeburn  1802: sub get_instuser {
                   1803:     my ($udom,$uname,$id) = @_;
                   1804:     my $homeserver = &domain($udom,'primary');
                   1805:     my ($outcome,%results);
                   1806:     if ($homeserver ne '') {
                   1807:         my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
                   1808:                            &escape($id).':'.&escape($udom),$homeserver);
                   1809:         my $host=&hostname($homeserver);
                   1810:         if ($queryid !~/^\Q$host\E\_/) {
                   1811:             &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
                   1812:             return;
                   1813:         }
                   1814:         my $response = &get_query_reply($queryid);
                   1815:         my $maxtries = 5;
                   1816:         my $tries = 1;
                   1817:         while (($response=~/^timeout/) && ($tries < $maxtries)) {
                   1818:             $response = &get_query_reply($queryid);
                   1819:             $tries ++;
                   1820:         }
                   1821:         if (!&error($response) && $response ne 'refused') {
                   1822:             if ($response eq 'unavailable') {
                   1823:                 $outcome = $response;
                   1824:             } else {
                   1825:                 $outcome = 'ok';
                   1826:                 my @matches = split(/\n/,$response);
                   1827:                 foreach my $match (@matches) {
                   1828:                     my ($key,$value) = split(/=/,$match);
                   1829:                     $results{&unescape($key)} = &thaw_unescape($value);
                   1830:                 }
                   1831:             }
                   1832:         }
                   1833:     }
                   1834:     my %userinfo;
                   1835:     if (ref($results{$uname}) eq 'HASH') {
                   1836:         %userinfo = %{$results{$uname}};
                   1837:     } 
                   1838:     return ($outcome,%userinfo);
                   1839: }
                   1840: 
                   1841: sub inst_rulecheck {
1.923     raeburn  1842:     my ($udom,$uname,$id,$item,$rules) = @_;
1.912     raeburn  1843:     my %returnhash;
                   1844:     if ($udom ne '') {
                   1845:         if (ref($rules) eq 'ARRAY') {
                   1846:             @{$rules} = map {&escape($_);} (@{$rules});
                   1847:             my $rulestr = join(':',@{$rules});
                   1848:             my $homeserver=&domain($udom,'primary');
                   1849:             if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1850:                 my $response;
                   1851:                 if ($item eq 'username') {                
                   1852:                     $response=&unescape(&reply('instrulecheck:'.&escape($udom).
                   1853:                                               ':'.&escape($uname).':'.$rulestr,
1.912     raeburn  1854:                                               $homeserver));
1.923     raeburn  1855:                 } elsif ($item eq 'id') {
                   1856:                     $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
                   1857:                                               ':'.&escape($id).':'.$rulestr,
                   1858:                                               $homeserver));
1.945     raeburn  1859:                 } elsif ($item eq 'selfcreate') {
                   1860:                     $response=&unescape(&reply('instselfcreatecheck:'.
1.943     raeburn  1861:                                                &escape($udom).':'.&escape($uname).
                   1862:                                               ':'.$rulestr,$homeserver));
1.923     raeburn  1863:                 }
1.912     raeburn  1864:                 if ($response ne 'refused') {
                   1865:                     my @pairs=split(/\&/,$response);
                   1866:                     foreach my $item (@pairs) {
                   1867:                         my ($key,$value)=split(/=/,$item,2);
                   1868:                         $key = &unescape($key);
                   1869:                         next if ($key =~ /^error: 2 /);
                   1870:                         $returnhash{$key}=&thaw_unescape($value);
                   1871:                     }
                   1872:                 }
                   1873:             }
                   1874:         }
                   1875:     }
                   1876:     return %returnhash;
                   1877: }
                   1878: 
                   1879: sub inst_userrules {
1.923     raeburn  1880:     my ($udom,$check) = @_;
1.912     raeburn  1881:     my (%ruleshash,@ruleorder);
                   1882:     if ($udom ne '') {
                   1883:         my $homeserver=&domain($udom,'primary');
                   1884:         if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923     raeburn  1885:             my $response;
                   1886:             if ($check eq 'id') {
                   1887:                 $response=&reply('instidrules:'.&escape($udom),
1.912     raeburn  1888:                                  $homeserver);
1.943     raeburn  1889:             } elsif ($check eq 'email') {
                   1890:                 $response=&reply('instemailrules:'.&escape($udom),
                   1891:                                  $homeserver);
1.923     raeburn  1892:             } else {
                   1893:                 $response=&reply('instuserrules:'.&escape($udom),
                   1894:                                  $homeserver);
                   1895:             }
1.912     raeburn  1896:             if (($response ne 'refused') && ($response ne 'error') && 
1.923     raeburn  1897:                 ($response ne 'unknown_cmd') && 
1.912     raeburn  1898:                 ($response ne 'no_such_host')) {
                   1899:                 my ($hashitems,$orderitems) = split(/:/,$response);
                   1900:                 my @pairs=split(/\&/,$hashitems);
                   1901:                 foreach my $item (@pairs) {
                   1902:                     my ($key,$value)=split(/=/,$item,2);
                   1903:                     $key = &unescape($key);
                   1904:                     next if ($key =~ /^error: 2 /);
                   1905:                     $ruleshash{$key}=&thaw_unescape($value);
                   1906:                 }
                   1907:                 my @esc_order = split(/\&/,$orderitems);
                   1908:                 foreach my $item (@esc_order) {
                   1909:                     push(@ruleorder,&unescape($item));
                   1910:                 }
                   1911:             }
                   1912:         }
                   1913:     }
                   1914:     return (\%ruleshash,\@ruleorder);
                   1915: }
                   1916: 
1.976     raeburn  1917: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943     raeburn  1918: 
                   1919: sub get_domain_defaults {
                   1920:     my ($domain) = @_;
                   1921:     my $cachetime = 60*60*24;
                   1922:     my ($result,$cached)=&is_cached_new('domdefaults',$domain);
                   1923:     if (defined($cached)) {
                   1924:         if (ref($result) eq 'HASH') {
                   1925:             return %{$result};
                   1926:         }
                   1927:     }
                   1928:     my %domdefaults;
                   1929:     my %domconfig =
1.989     raeburn  1930:          &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047    raeburn  1931:                                   'requestcourses','inststatus',
1.1073    raeburn  1932:                                   'coursedefaults','usersessions'],$domain);
1.943     raeburn  1933:     if (ref($domconfig{'defaults'}) eq 'HASH') {
                   1934:         $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'}; 
                   1935:         $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
                   1936:         $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982     raeburn  1937:         $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985     raeburn  1938:         $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147    raeburn  1939:         $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943     raeburn  1940:     } else {
                   1941:         $domdefaults{'lang_def'} = &domain($domain,'lang_def');
                   1942:         $domdefaults{'auth_def'} = &domain($domain,'auth_def');
                   1943:         $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
                   1944:     }
1.976     raeburn  1945:     if (ref($domconfig{'quotas'}) eq 'HASH') {
                   1946:         if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
                   1947:             $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
                   1948:         } else {
                   1949:             $domdefaults{'defaultquota'} = $domconfig{'quotas'};
                   1950:         } 
                   1951:         my @usertools = ('aboutme','blog','portfolio');
                   1952:         foreach my $item (@usertools) {
                   1953:             if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
                   1954:                 $domdefaults{$item} = $domconfig{'quotas'}{$item};
                   1955:             }
                   1956:         }
                   1957:     }
1.985     raeburn  1958:     if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006    raeburn  1959:         foreach my $item ('official','unofficial','community') {
1.985     raeburn  1960:             $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
                   1961:         }
                   1962:     }
1.989     raeburn  1963:     if (ref($domconfig{'inststatus'}) eq 'HASH') {
                   1964:         foreach my $item ('inststatustypes','inststatusorder') {
                   1965:             $domdefaults{$item} = $domconfig{'inststatus'}{$item};
                   1966:         }
                   1967:     }
1.1047    raeburn  1968:     if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
                   1969:         foreach my $item ('canuse_pdfforms') {
                   1970:             $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
                   1971:         }
                   1972:     }
1.1073    raeburn  1973:     if (ref($domconfig{'usersessions'}) eq 'HASH') {
                   1974:         if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
                   1975:             $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
                   1976:         }
                   1977:         if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
                   1978:             $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
                   1979:         }
                   1980:     }
1.943     raeburn  1981:     &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
                   1982:                                   $cachetime);
                   1983:     return %domdefaults;
                   1984: }
                   1985: 
1.344     www      1986: # --------------------------------------------------- Assign a key to a student
                   1987: 
                   1988: sub assign_access_key {
1.364     www      1989: #
                   1990: # a valid key looks like uname:udom#comments
                   1991: # comments are being appended
                   1992: #
1.498     www      1993:     my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
                   1994:     $kdom=
1.620     albertel 1995:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498     www      1996:     $knum=
1.620     albertel 1997:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344     www      1998:     $cdom=
1.620     albertel 1999:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2000:     $cnum=
1.620     albertel 2001:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2002:     $udom=$env{'user.name'} unless (defined($udom));
                   2003:     $uname=$env{'user.domain'} unless (defined($uname));
1.498     www      2004:     my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364     www      2005:     if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479     albertel 2006:         ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) { 
1.364     www      2007:                                                   # assigned to this person
                   2008:                                                   # - this should not happen,
1.345     www      2009:                                                   # unless something went wrong
                   2010:                                                   # the first time around
                   2011: # ready to assign
1.364     www      2012:         $logentry=$1.'; '.$logentry;
1.496     www      2013:         if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498     www      2014:                                                  $kdom,$knum) eq 'ok') {
1.345     www      2015: # key now belongs to user
1.346     www      2016: 	    my $envkey='key.'.$cdom.'_'.$cnum;
1.345     www      2017:             if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949     raeburn  2018:                 &appenv({'environment.'.$envkey => $ckey});
1.345     www      2019:                 return 'ok';
                   2020:             } else {
                   2021:                 return 
                   2022:   'error: Count not permanently assign key, will need to be re-entered later.';
                   2023: 	    }
                   2024:         } else {
                   2025:             return 'error: Could not assign key, try again later.';
                   2026:         }
1.364     www      2027:     } elsif (!$existing{$ckey}) {
1.345     www      2028: # the key does not exist
                   2029: 	return 'error: The key does not exist';
                   2030:     } else {
                   2031: # the key is somebody else's
                   2032: 	return 'error: The key is already in use';
                   2033:     }
1.344     www      2034: }
                   2035: 
1.364     www      2036: # ------------------------------------------ put an additional comment on a key
                   2037: 
                   2038: sub comment_access_key {
                   2039: #
                   2040: # a valid key looks like uname:udom#comments
                   2041: # comments are being appended
                   2042: #
                   2043:     my ($ckey,$cdom,$cnum,$logentry)=@_;
                   2044:     $cdom=
1.620     albertel 2045:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364     www      2046:     $cnum=
1.620     albertel 2047:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364     www      2048:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
                   2049:     if ($existing{$ckey}) {
                   2050:         $existing{$ckey}.='; '.$logentry;
                   2051: # ready to assign
1.367     www      2052:         if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364     www      2053:                                                  $cdom,$cnum) eq 'ok') {
                   2054: 	    return 'ok';
                   2055:         } else {
                   2056: 	    return 'error: Count not store comment.';
                   2057:         }
                   2058:     } else {
                   2059: # the key does not exist
                   2060: 	return 'error: The key does not exist';
                   2061:     }
                   2062: }
                   2063: 
1.344     www      2064: # ------------------------------------------------------ Generate a set of keys
                   2065: 
                   2066: sub generate_access_keys {
1.364     www      2067:     my ($number,$cdom,$cnum,$logentry)=@_;
1.344     www      2068:     $cdom=
1.620     albertel 2069:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2070:     $cnum=
1.620     albertel 2071:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361     www      2072:     unless (&allowed('mky',$cdom)) { return 0; }
1.344     www      2073:     unless (($cdom) && ($cnum)) { return 0; }
                   2074:     if ($number>10000) { return 0; }
                   2075:     sleep(2); # make sure don't get same seed twice
                   2076:     srand(time()^($$+($$<<15))); # from "Programming Perl"
                   2077:     my $total=0;
                   2078:     for (my $i=1;$i<=$number;$i++) {
                   2079:        my $newkey=sprintf("%lx",int(100000*rand)).'-'.
                   2080:                   sprintf("%lx",int(100000*rand)).'-'.
                   2081:                   sprintf("%lx",int(100000*rand));
                   2082:        $newkey=~s/1/g/g; # folks mix up 1 and l
                   2083:        $newkey=~s/0/h/g; # and also 0 and O
                   2084:        my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
                   2085:        if ($existing{$newkey}) {
                   2086:            $i--;
                   2087:        } else {
1.364     www      2088: 	  if (&put('accesskeys',
                   2089:               { $newkey => '# generated '.localtime().
1.620     albertel 2090:                            ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364     www      2091:                            '; '.$logentry },
                   2092: 		   $cdom,$cnum) eq 'ok') {
1.344     www      2093:               $total++;
                   2094: 	  }
                   2095:        }
                   2096:     }
1.620     albertel 2097:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344     www      2098:          'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
                   2099:     return $total;
                   2100: }
                   2101: 
                   2102: # ------------------------------------------------------- Validate an accesskey
                   2103: 
                   2104: sub validate_access_key {
                   2105:     my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
                   2106:     $cdom=
1.620     albertel 2107:    $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344     www      2108:     $cnum=
1.620     albertel 2109:    $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
                   2110:     $udom=$env{'user.domain'} unless (defined($udom));
                   2111:     $uname=$env{'user.name'} unless (defined($uname));
1.345     www      2112:     my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479     albertel 2113:     return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70      www      2114: }
                   2115: 
                   2116: # ------------------------------------- Find the section of student in a course
1.652     albertel 2117: sub devalidate_getsection_cache {
                   2118:     my ($udom,$unam,$courseid)=@_;
                   2119:     my $hashid="$udom:$unam:$courseid";
                   2120:     &devalidate_cache_new('getsection',$hashid);
                   2121: }
1.298     matthew  2122: 
1.815     albertel 2123: sub courseid_to_courseurl {
                   2124:     my ($courseid) = @_;
                   2125:     #already url style courseid
                   2126:     return $courseid if ($courseid =~ m{^/});
                   2127: 
                   2128:     if (exists($env{'course.'.$courseid.'.num'})) {
                   2129: 	my $cnum = $env{'course.'.$courseid.'.num'};
                   2130: 	my $cdom = $env{'course.'.$courseid.'.domain'};
                   2131: 	return "/$cdom/$cnum";
                   2132:     }
                   2133: 
                   2134:     my %courseinfo=&Apache::lonnet::coursedescription($courseid);
                   2135:     if (exists($courseinfo{'num'})) {
                   2136: 	return "/$courseinfo{'domain'}/$courseinfo{'num'}";
                   2137:     }
                   2138: 
                   2139:     return undef;
                   2140: }
                   2141: 
1.298     matthew  2142: sub getsection {
                   2143:     my ($udom,$unam,$courseid)=@_;
1.599     albertel 2144:     my $cachetime=1800;
1.551     albertel 2145: 
                   2146:     my $hashid="$udom:$unam:$courseid";
1.599     albertel 2147:     my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551     albertel 2148:     if (defined($cached)) { return $result; }
                   2149: 
1.298     matthew  2150:     my %Pending; 
                   2151:     my %Expired;
                   2152:     #
                   2153:     # Each role can either have not started yet (pending), be active, 
                   2154:     #    or have expired.
                   2155:     #
                   2156:     # If there is an active role, we are done.
                   2157:     #
                   2158:     # If there is more than one role which has not started yet, 
                   2159:     #     choose the one which will start sooner
                   2160:     # If there is one role which has not started yet, return it.
                   2161:     #
                   2162:     # If there is more than one expired role, choose the one which ended last.
                   2163:     # If there is a role which has expired, return it.
                   2164:     #
1.815     albertel 2165:     $courseid = &courseid_to_courseurl($courseid);
1.1166    raeburn  2166:     my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817     raeburn  2167:     foreach my $key (keys(%roleshash)) {
1.479     albertel 2168:         next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298     matthew  2169:         my $section=$1;
                   2170:         if ($key eq $courseid.'_st') { $section=''; }
1.817     raeburn  2171:         my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298     matthew  2172:         my $now=time;
1.548     albertel 2173:         if (defined($end) && $end && ($now > $end)) {
1.298     matthew  2174:             $Expired{$end}=$section;
                   2175:             next;
                   2176:         }
1.548     albertel 2177:         if (defined($start) && $start && ($now < $start)) {
1.298     matthew  2178:             $Pending{$start}=$section;
                   2179:             next;
                   2180:         }
1.599     albertel 2181:         return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298     matthew  2182:     }
                   2183:     #
                   2184:     # Presumedly there will be few matching roles from the above
                   2185:     # loop and the sorting time will be negligible.
                   2186:     if (scalar(keys(%Pending))) {
                   2187:         my ($time) = sort {$a <=> $b} keys(%Pending);
1.599     albertel 2188:         return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298     matthew  2189:     } 
                   2190:     if (scalar(keys(%Expired))) {
                   2191:         my @sorted = sort {$a <=> $b} keys(%Expired);
                   2192:         my $time = pop(@sorted);
1.599     albertel 2193:         return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298     matthew  2194:     }
1.599     albertel 2195:     return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298     matthew  2196: }
1.70      www      2197: 
1.599     albertel 2198: sub save_cache {
                   2199:     &purge_remembered();
1.722     albertel 2200:     #&Apache::loncommon::validate_page();
1.620     albertel 2201:     undef(%env);
1.780     albertel 2202:     undef($env_loaded);
1.599     albertel 2203: }
1.452     albertel 2204: 
1.599     albertel 2205: my $to_remember=-1;
                   2206: my %remembered;
                   2207: my %accessed;
                   2208: my $kicks=0;
                   2209: my $hits=0;
1.849     albertel 2210: sub make_key {
                   2211:     my ($name,$id) = @_;
1.872     albertel 2212:     if (length($id) > 65 
                   2213: 	&& length(&escape($id)) > 200) {
                   2214: 	$id=length($id).':'.&Digest::MD5::md5_hex($id);
                   2215:     }
1.849     albertel 2216:     return &escape($name.':'.$id);
                   2217: }
                   2218: 
1.599     albertel 2219: sub devalidate_cache_new {
                   2220:     my ($name,$id,$debug) = @_;
                   2221:     if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849     albertel 2222:     $id=&make_key($name,$id);
1.599     albertel 2223:     $memcache->delete($id);
                   2224:     delete($remembered{$id});
                   2225:     delete($accessed{$id});
                   2226: }
                   2227: 
                   2228: sub is_cached_new {
                   2229:     my ($name,$id,$debug) = @_;
1.849     albertel 2230:     $id=&make_key($name,$id);
1.599     albertel 2231:     if (exists($remembered{$id})) {
1.1133    foxr     2232: 	if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599     albertel 2233: 	$accessed{$id}=[&gettimeofday()];
                   2234: 	$hits++;
                   2235: 	return ($remembered{$id},1);
                   2236:     }
                   2237:     my $value = $memcache->get($id);
                   2238:     if (!(defined($value))) {
                   2239: 	if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417     albertel 2240: 	return (undef,undef);
1.416     albertel 2241:     }
1.599     albertel 2242:     if ($value eq '__undef__') {
                   2243: 	if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
                   2244: 	$value=undef;
                   2245:     }
                   2246:     &make_room($id,$value,$debug);
                   2247:     if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
                   2248:     return ($value,1);
                   2249: }
                   2250: 
                   2251: sub do_cache_new {
                   2252:     my ($name,$id,$value,$time,$debug) = @_;
1.849     albertel 2253:     $id=&make_key($name,$id);
1.599     albertel 2254:     my $setvalue=$value;
                   2255:     if (!defined($setvalue)) {
                   2256: 	$setvalue='__undef__';
                   2257:     }
1.623     albertel 2258:     if (!defined($time) ) {
                   2259: 	$time=600;
                   2260:     }
1.599     albertel 2261:     if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910     albertel 2262:     my $result = $memcache->set($id,$setvalue,$time);
                   2263:     if (! $result) {
1.872     albertel 2264: 	&logthis("caching of id -> $id  failed");
1.910     albertel 2265: 	$memcache->disconnect_all();
1.872     albertel 2266:     }
1.600     albertel 2267:     # need to make a copy of $value
1.919     albertel 2268:     &make_room($id,$value,$debug);
1.599     albertel 2269:     return $value;
                   2270: }
                   2271: 
                   2272: sub make_room {
                   2273:     my ($id,$value,$debug)=@_;
1.919     albertel 2274: 
                   2275:     $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
                   2276:                                     : $value;
1.599     albertel 2277:     if ($to_remember<0) { return; }
                   2278:     $accessed{$id}=[&gettimeofday()];
                   2279:     if (scalar(keys(%remembered)) <= $to_remember) { return; }
                   2280:     my $to_kick;
                   2281:     my $max_time=0;
                   2282:     foreach my $other (keys(%accessed)) {
                   2283: 	if (&tv_interval($accessed{$other}) > $max_time) {
                   2284: 	    $to_kick=$other;
                   2285: 	    $max_time=&tv_interval($accessed{$other});
                   2286: 	}
                   2287:     }
                   2288:     delete($remembered{$to_kick});
                   2289:     delete($accessed{$to_kick});
                   2290:     $kicks++;
                   2291:     if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541     albertel 2292:     return;
                   2293: }
                   2294: 
1.599     albertel 2295: sub purge_remembered {
1.604     albertel 2296:     #&logthis("Tossing ".scalar(keys(%remembered)));
                   2297:     #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599     albertel 2298:     undef(%remembered);
                   2299:     undef(%accessed);
1.428     albertel 2300: }
1.70      www      2301: # ------------------------------------- Read an entry from a user's environment
                   2302: 
                   2303: sub userenvironment {
                   2304:     my ($udom,$unam,@what)=@_;
1.976     raeburn  2305:     my $items;
                   2306:     foreach my $item (@what) {
                   2307:         $items.=&escape($item).'&';
                   2308:     }
                   2309:     $items=~s/\&$//;
1.70      www      2310:     my %returnhash=();
1.1009    raeburn  2311:     my $uhome = &homeserver($unam,$udom);
                   2312:     unless ($uhome eq 'no_host') {
                   2313:         my @answer=split(/\&/, 
                   2314:             &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048    raeburn  2315:         if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
                   2316:             return %returnhash;
                   2317:         }
1.1009    raeburn  2318:         my $i;
                   2319:         for ($i=0;$i<=$#what;$i++) {
                   2320: 	    $returnhash{$what[$i]}=&unescape($answer[$i]);
                   2321:         }
1.70      www      2322:     }
                   2323:     return %returnhash;
1.1       albertel 2324: }
                   2325: 
1.617     albertel 2326: # ---------------------------------------------------------- Get a studentphoto
                   2327: sub studentphoto {
                   2328:     my ($udom,$unam,$ext) = @_;
                   2329:     my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706     raeburn  2330:     if (defined($env{'request.course.id'})) {
1.708     raeburn  2331:         if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706     raeburn  2332:             if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
                   2333:                 return(&retrievestudentphoto($udom,$unam,$ext)); 
                   2334:             } else {
                   2335:                 my ($result,$perm_reqd)=
1.707     albertel 2336: 		    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2337:                 if ($result eq 'ok') {
                   2338:                     if (!($perm_reqd eq 'yes')) {
                   2339:                         return(&retrievestudentphoto($udom,$unam,$ext));
                   2340:                     }
                   2341:                 }
                   2342:             }
                   2343:         }
                   2344:     } else {
                   2345:         my ($result,$perm_reqd) = 
1.707     albertel 2346: 	    &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706     raeburn  2347:         if ($result eq 'ok') {
                   2348:             if (!($perm_reqd eq 'yes')) {
                   2349:                 return(&retrievestudentphoto($udom,$unam,$ext));
                   2350:             }
                   2351:         }
                   2352:     }
                   2353:     return '/adm/lonKaputt/lonlogo_broken.gif';
                   2354: }
                   2355: 
                   2356: sub retrievestudentphoto {
                   2357:     my ($udom,$unam,$ext,$type) = @_;
                   2358:     my $home=&Apache::lonnet::homeserver($unam,$udom);
                   2359:     my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
                   2360:     if ($ret eq 'ok') {
                   2361:         my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
                   2362:         if ($type eq 'thumbnail') {
                   2363:             $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext"; 
                   2364:         }
                   2365:         my $tokenurl=&Apache::lonnet::tokenwrapper($url);
                   2366:         return $tokenurl;
                   2367:     } else {
                   2368:         if ($type eq 'thumbnail') {
                   2369:             return '/adm/lonKaputt/genericstudent_tn.gif';
                   2370:         } else { 
                   2371:             return '/adm/lonKaputt/lonlogo_broken.gif';
                   2372:         }
1.617     albertel 2373:     }
                   2374: }
                   2375: 
1.263     www      2376: # -------------------------------------------------------------------- New chat
                   2377: 
                   2378: sub chatsend {
1.724     raeburn  2379:     my ($newentry,$anon,$group)=@_;
1.620     albertel 2380:     my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2381:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2382:     my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263     www      2383:     &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620     albertel 2384: 	   &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724     raeburn  2385: 		   &escape($newentry)).':'.$group,$chome);
1.292     www      2386: }
                   2387: 
                   2388: # ------------------------------------------ Find current version of a resource
                   2389: 
                   2390: sub getversion {
                   2391:     my $fname=&clutter(shift);
                   2392:     unless ($fname=~/^\/res\//) { return -1; }
                   2393:     return &currentversion(&filelocation('',$fname));
                   2394: }
                   2395: 
                   2396: sub currentversion {
                   2397:     my $fname=shift;
                   2398:     my $author=$fname;
                   2399:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2400:     my ($udom,$uname)=split(/\//,$author);
1.1112    www      2401:     my $home=&homeserver($uname,$udom);
1.292     www      2402:     if ($home eq 'no_host') { 
                   2403:         return -1; 
                   2404:     }
1.1112    www      2405:     my $answer=&reply("currentversion:$fname",$home);
1.292     www      2406:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2407: 	return -1;
                   2408:     }
1.1112    www      2409:     return $answer;
1.263     www      2410: }
                   2411: 
1.1111    www      2412: #
                   2413: # Return special version number of resource if set by override, empty otherwise
                   2414: #
                   2415: sub usedversion {
                   2416:     my $fname=shift;
                   2417:     unless ($fname) { $fname=$env{'request.uri'}; }
                   2418:     my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
                   2419:     if ($urlversion) { return $urlversion; }
                   2420:     return '';
                   2421: }
                   2422: 
1.1       albertel 2423: # ----------------------------- Subscribe to a resource, return URL if possible
1.11      www      2424: 
1.1       albertel 2425: sub subscribe {
                   2426:     my $fname=shift;
1.761     raeburn  2427:     if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532     albertel 2428:     $fname=~s/[\n\r]//g;
1.1       albertel 2429:     my $author=$fname;
                   2430:     $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2431:     my ($udom,$uname)=split(/\//,$author);
                   2432:     my $home=homeserver($uname,$udom);
1.335     albertel 2433:     if ($home eq 'no_host') {
                   2434:         return 'not_found';
1.1       albertel 2435:     }
                   2436:     my $answer=reply("sub:$fname",$home);
1.64      www      2437:     if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
                   2438: 	$answer.=' by '.$home;
                   2439:     }
1.1       albertel 2440:     return $answer;
                   2441: }
                   2442:     
1.8       www      2443: # -------------------------------------------------------------- Replicate file
                   2444: 
                   2445: sub repcopy {
                   2446:     my $filename=shift;
1.23      www      2447:     $filename=~s/\/+/\//g;
1.1142    raeburn  2448:     my $londocroot = $perlvar{'lonDocRoot'};
                   2449:     if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164    raeburn  2450:     if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142    raeburn  2451:     if ($filename=~m{^\Q$londocroot/userfiles/\E} or
                   2452: 	$filename=~m{^/*(uploaded|editupload)/}) {
1.538     albertel 2453: 	return &repcopy_userfile($filename);
                   2454:     }
1.532     albertel 2455:     $filename=~s/[\n\r]//g;
1.8       www      2456:     my $transname="$filename.in.transfer";
1.828     www      2457: # FIXME: this should flock
1.607     raeburn  2458:     if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8       www      2459:     my $remoteurl=subscribe($filename);
1.64      www      2460:     if ($remoteurl =~ /^con_lost by/) {
                   2461: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2462:            return 'unavailable';
1.8       www      2463:     } elsif ($remoteurl eq 'not_found') {
1.441     albertel 2464: 	   #&logthis("Subscribe returned not_found: $filename");
1.607     raeburn  2465: 	   return 'not_found';
1.64      www      2466:     } elsif ($remoteurl =~ /^rejected by/) {
                   2467: 	   &logthis("Subscribe returned $remoteurl: $filename");
1.607     raeburn  2468:            return 'forbidden';
1.20      www      2469:     } elsif ($remoteurl eq 'directory') {
1.607     raeburn  2470:            return 'ok';
1.8       www      2471:     } else {
1.290     www      2472:         my $author=$filename;
                   2473:         $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
                   2474:         my ($udom,$uname)=split(/\//,$author);
                   2475:         my $home=homeserver($uname,$udom);
                   2476:         unless ($home eq $perlvar{'lonHostID'}) {
1.8       www      2477:            my @parts=split(/\//,$filename);
                   2478:            my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142    raeburn  2479:            if ($path ne "$londocroot/res") {
1.8       www      2480:                &logthis("Malconfiguration for replication: $filename");
1.607     raeburn  2481: 	       return 'bad_request';
1.8       www      2482:            }
                   2483:            my $count;
                   2484:            for ($count=5;$count<$#parts;$count++) {
                   2485:                $path.="/$parts[$count]";
                   2486:                if ((-e $path)!=1) {
                   2487: 		   mkdir($path,0777);
                   2488:                }
                   2489:            }
                   2490:            my $ua=new LWP::UserAgent;
                   2491:            my $request=new HTTP::Request('GET',"$remoteurl");
                   2492:            my $response=$ua->request($request,$transname);
                   2493:            if ($response->is_error()) {
                   2494: 	       unlink($transname);
                   2495:                my $message=$response->status_line;
1.672     albertel 2496:                &logthis("<font color=\"blue\">WARNING:"
1.12      www      2497:                        ." LWP get: $message: $filename</font>");
1.607     raeburn  2498:                return 'unavailable';
1.8       www      2499:            } else {
1.16      www      2500: 	       if ($remoteurl!~/\.meta$/) {
                   2501:                   my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
                   2502:                   my $mresponse=$ua->request($mrequest,$filename.'.meta');
                   2503:                   if ($mresponse->is_error()) {
                   2504: 		      unlink($filename.'.meta');
                   2505:                       &logthis(
1.672     albertel 2506:                      "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16      www      2507:                   }
                   2508: 	       }
1.8       www      2509:                rename($transname,$filename);
1.607     raeburn  2510:                return 'ok';
1.8       www      2511:            }
1.290     www      2512:        }
1.8       www      2513:     }
1.330     www      2514: }
                   2515: 
                   2516: # ------------------------------------------------ Get server side include body
                   2517: sub ssi_body {
1.381     albertel 2518:     my ($filelink,%form)=@_;
1.606     matthew  2519:     if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
                   2520:         $form{'LONCAPA_INTERNAL_no_discussion'}='true';
                   2521:     }
1.953     www      2522:     my $output='';
                   2523:     my $response;
1.980     raeburn  2524:     if ($filelink=~/^https?\:/) {
1.954     raeburn  2525:        ($output,$response)=&externalssi($filelink);
1.953     www      2526:     } else {
1.1004    droeschl 2527:        $filelink .= $filelink=~/\?/ ? '&' : '?';
                   2528:        $filelink .= 'inhibitmenu=yes';
1.953     www      2529:        ($output,$response)=&ssi($filelink,%form);
                   2530:     }
1.778     albertel 2531:     $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451     albertel 2532:     $output=~s/^.*?\<body[^\>]*\>//si;
1.930     albertel 2533:     $output=~s/\<\/body\s*\>.*?$//si;
1.953     www      2534:     if (wantarray) {
                   2535:         return ($output, $response);
                   2536:     } else {
                   2537:         return $output;
                   2538:     }
1.8       www      2539: }
                   2540: 
1.15      www      2541: # --------------------------------------------------------- Server Side Include
                   2542: 
1.782     albertel 2543: sub absolute_url {
                   2544:     my ($host_name) = @_;
                   2545:     my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
                   2546:     if ($host_name eq '') {
                   2547: 	$host_name = $ENV{'SERVER_NAME'};
                   2548:     }
                   2549:     return $protocol.$host_name;
                   2550: }
                   2551: 
1.942     foxr     2552: #
                   2553: #   Server side include.
                   2554: # Parameters:
                   2555: #  fn     Possibly encrypted resource name/id.
                   2556: #  form   Hash that describes how the rendering should be done
                   2557: #         and other things.
1.944     foxr     2558: # Returns:
1.950     raeburn  2559: #   Scalar context: The content of the response.
                   2560: #   Array context:  2 element list of the content and the full response object.
1.942     foxr     2561: #     
1.15      www      2562: sub ssi {
                   2563: 
1.944     foxr     2564:     my ($fn,%form)=@_;
1.15      www      2565:     my $ua=new LWP::UserAgent;
1.23      www      2566:     my $request;
1.711     albertel 2567: 
                   2568:     $form{'no_update_last_known'}=1;
1.895     albertel 2569:     &Apache::lonenc::check_encrypt(\$fn);
1.23      www      2570:     if (%form) {
1.782     albertel 2571:       $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000    raeburn  2572:       $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23      www      2573:     } else {
1.782     albertel 2574:       $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23      www      2575:     }
                   2576: 
1.15      www      2577:     $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173    foxr     2578:     my $response= $ua->request($request);
                   2579:     my $content = Encode::decode_utf8($response->content);
1.944     foxr     2580:     if (wantarray) {
1.1173    foxr     2581: 	return ($content, $response);
1.944     foxr     2582:     } else {
1.1173    foxr     2583: 	return $content;
1.942     foxr     2584:     }
1.324     www      2585: }
                   2586: 
                   2587: sub externalssi {
                   2588:     my ($url)=@_;
                   2589:     my $ua=new LWP::UserAgent;
                   2590:     my $request=new HTTP::Request('GET',$url);
                   2591:     my $response=$ua->request($request);
1.954     raeburn  2592:     if (wantarray) {
                   2593:         return ($response->content, $response);
                   2594:     } else {
                   2595:         return $response->content;
                   2596:     }
1.15      www      2597: }
1.254     www      2598: 
1.492     albertel 2599: # -------------------------------- Allow a /uploaded/ URI to be vouched for
                   2600: 
                   2601: sub allowuploaded {
                   2602:     my ($srcurl,$url)=@_;
                   2603:     $url=&clutter(&declutter($url));
                   2604:     my $dir=$url;
                   2605:     $dir=~s/\/[^\/]+$//;
                   2606:     my %httpref=();
                   2607:     my $httpurl=&hreflocation('',$url);
                   2608:     $httpref{'httpref.'.$httpurl}=$srcurl;
1.949     raeburn  2609:     &Apache::lonnet::appenv(\%httpref);
1.254     www      2610: }
1.477     raeburn  2611: 
1.478     albertel 2612: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638     albertel 2613: # input: action, courseID, current domain, intended
1.637     raeburn  2614: #        path to file, source of file, instruction to parse file for objects,
                   2615: #        ref to hash for embedded objects,
                   2616: #        ref to hash for codebase of java objects.
1.1095    raeburn  2617: #        reference to scalar to accommodate mime type determined
                   2618: #          from File::MMagic if $parser = parse.
1.637     raeburn  2619: #
1.485     raeburn  2620: # output: url to file (if action was uploaddoc), 
                   2621: #         ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477     raeburn  2622: #
1.478     albertel 2623: # Allows directory structure to be used within lonUsers/../userfiles/ for a 
                   2624: # course.
1.477     raeburn  2625: #
1.478     albertel 2626: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2627: #          will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
                   2628: #          course's home server.
1.477     raeburn  2629: #
1.478     albertel 2630: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
                   2631: #          be copied from $source (current location) to 
                   2632: #          /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2633: #         and will then be copied to
                   2634: #          /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
                   2635: #         course's home server.
1.485     raeburn  2636: #
1.481     raeburn  2637: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620     albertel 2638: #         will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481     raeburn  2639: #         /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
                   2640: #         and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
                   2641: #         in course's home server.
1.637     raeburn  2642: #
1.477     raeburn  2643: 
                   2644: sub process_coursefile {
1.1095    raeburn  2645:     my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
                   2646:         $mimetype)=@_;
1.477     raeburn  2647:     my $fetchresult;
1.638     albertel 2648:     my $home=&homeserver($docuname,$docudom);
1.477     raeburn  2649:     if ($action eq 'propagate') {
1.638     albertel 2650:         $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
                   2651: 			     $home);
1.481     raeburn  2652:     } else {
1.477     raeburn  2653:         my $fpath = '';
                   2654:         my $fname = $file;
1.478     albertel 2655:         ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477     raeburn  2656:         $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637     raeburn  2657:         my $filepath = &build_filepath($fpath);
1.481     raeburn  2658:         if ($action eq 'copy') {
                   2659:             if ($source eq '') {
                   2660:                 $fetchresult = 'no source file';
                   2661:                 return $fetchresult;
                   2662:             } else {
                   2663:                 my $destination = $filepath.'/'.$fname;
                   2664:                 rename($source,$destination);
                   2665:                 $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2666:                                  $home);
1.481     raeburn  2667:             }
                   2668:         } elsif ($action eq 'uploaddoc') {
                   2669:             open(my $fh,'>'.$filepath.'/'.$fname);
1.620     albertel 2670:             print $fh $env{'form.'.$source};
1.481     raeburn  2671:             close($fh);
1.637     raeburn  2672:             if ($parser eq 'parse') {
1.1024    raeburn  2673:                 my $mm = new File::MMagic;
1.1095    raeburn  2674:                 my $type = $mm->checktype_filename($filepath.'/'.$fname);
                   2675:                 if ($type eq 'text/html') {
1.1024    raeburn  2676:                     my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
                   2677:                     unless ($parse_result eq 'ok') {
                   2678:                         &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
                   2679:                     }
1.637     raeburn  2680:                 }
1.1095    raeburn  2681:                 if (ref($mimetype)) {
                   2682:                     $$mimetype = $type;
                   2683:                 } 
1.637     raeburn  2684:             }
1.477     raeburn  2685:             $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2686:                                  $home);
1.481     raeburn  2687:             if ($fetchresult eq 'ok') {
                   2688:                 return '/uploaded/'.$fpath.'/'.$fname;
                   2689:             } else {
                   2690:                 &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2691:                         ' to host '.$home.': '.$fetchresult);
1.481     raeburn  2692:                 return '/adm/notfound.html';
                   2693:             }
1.477     raeburn  2694:         }
                   2695:     }
1.485     raeburn  2696:     unless ( $fetchresult eq 'ok') {
1.477     raeburn  2697:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638     albertel 2698:              ' to host '.$home.': '.$fetchresult);
1.477     raeburn  2699:     }
                   2700:     return $fetchresult;
                   2701: }
                   2702: 
1.637     raeburn  2703: sub build_filepath {
                   2704:     my ($fpath) = @_;
                   2705:     my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
                   2706:     unless ($fpath eq '') {
                   2707:         my @parts=split('/',$fpath);
                   2708:         foreach my $part (@parts) {
                   2709:             $filepath.= '/'.$part;
                   2710:             if ((-e $filepath)!=1) {
                   2711:                 mkdir($filepath,0777);
                   2712:             }
                   2713:         }
                   2714:     }
                   2715:     return $filepath;
                   2716: }
                   2717: 
                   2718: sub store_edited_file {
1.638     albertel 2719:     my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637     raeburn  2720:     my $file = $primary_url;
                   2721:     $file =~ s#^/uploaded/$docudom/$docuname/##;
                   2722:     my $fpath = '';
                   2723:     my $fname = $file;
                   2724:     ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
                   2725:     $fpath=$docudom.'/'.$docuname.'/'.$fpath;
                   2726:     my $filepath = &build_filepath($fpath);
                   2727:     open(my $fh,'>'.$filepath.'/'.$fname);
                   2728:     print $fh $content;
                   2729:     close($fh);
1.638     albertel 2730:     my $home=&homeserver($docuname,$docudom);
1.637     raeburn  2731:     $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638     albertel 2732: 			  $home);
1.637     raeburn  2733:     if ($$fetchresult eq 'ok') {
                   2734:         return '/uploaded/'.$fpath.'/'.$fname;
                   2735:     } else {
1.638     albertel 2736:         &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
                   2737: 		 ' to host '.$home.': '.$$fetchresult);
1.637     raeburn  2738:         return '/adm/notfound.html';
                   2739:     }
                   2740: }
                   2741: 
1.531     albertel 2742: sub clean_filename {
1.831     albertel 2743:     my ($fname,$args)=@_;
1.315     www      2744: # Replace Windows backslashes by forward slashes
1.257     www      2745:     $fname=~s/\\/\//g;
1.831     albertel 2746:     if (!$args->{'keep_path'}) {
                   2747:         # Get rid of everything but the actual filename
                   2748: 	$fname=~s/^.*\/([^\/]+)$/$1/;
                   2749:     }
1.315     www      2750: # Replace spaces by underscores
                   2751:     $fname=~s/\s+/\_/g;
                   2752: # Replace all other weird characters by nothing
1.831     albertel 2753:     $fname=~s{[^/\w\.\-]}{}g;
1.540     albertel 2754: # Replace all .\d. sequences with _\d. so they no longer look like version
                   2755: # numbers
                   2756:     $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531     albertel 2757:     return $fname;
                   2758: }
1.1051    raeburn  2759: # This Function checks if an Image's dimensions exceed either $resizewidth (width) 
                   2760: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an 
                   2761: # image with the same aspect ratio as the original, but with dimensions which do 
                   2762: # not exceed $resizewidth and $resizeheight.
                   2763:  
1.984     neumanie 2764: sub resizeImage {
1.1051    raeburn  2765:     my ($img_path,$resizewidth,$resizeheight) = @_;
                   2766:     my $ima = Image::Magick->new;
                   2767:     my $resized;
                   2768:     if (-e $img_path) {
                   2769:         $ima->Read($img_path);
                   2770:         if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
                   2771:             my $width = $ima->Get('width');
                   2772:             my $height = $ima->Get('height');
                   2773:             if ($width > $resizewidth) {
                   2774: 	        my $factor = $width/$resizewidth;
                   2775:                 my $newheight = $height/$factor;
                   2776:                 $ima->Scale(width=>$resizewidth,height=>$newheight);
                   2777:                 $resized = 1;
                   2778:             }
                   2779:         }
                   2780:         if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
                   2781:             my $width = $ima->Get('width');
                   2782:             my $height = $ima->Get('height');
                   2783:             if ($height > $resizeheight) {
                   2784:                 my $factor = $height/$resizeheight;
                   2785:                 my $newwidth = $width/$factor;
                   2786:                 $ima->Scale(width=>$newwidth,height=>$resizeheight);
                   2787:                 $resized = 1;
                   2788:             }
                   2789:         }
                   2790:         if ($resized) {
                   2791:             $ima->Write($img_path);
                   2792:         }
                   2793:     }
                   2794:     return;
1.977     amueller 2795: }
                   2796: 
1.608     albertel 2797: # --------------- Take an uploaded file and put it into the userfiles directory
1.686     albertel 2798: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093    raeburn  2799: #                    the desired filename is in $env{"form.$formname.filename"}
1.1090    raeburn  2800: #        $context - possible values: coursedoc, existingfile, overwrite, 
                   2801: #                                    canceloverwrite, or ''. 
                   2802: #                   if 'coursedoc': upload to the current course
                   2803: #                   if 'existingfile': write file to tmp/overwrites directory 
                   2804: #                   if 'canceloverwrite': delete file written to tmp/overwrites directory
                   2805: #                   $context is passed as argument to &finishuserfileupload
1.686     albertel 2806: #        $subdir - directory in userfile to store the file into
1.858     raeburn  2807: #        $parser - instruction to parse file for objects ($parser = parse)    
                   2808: #        $allfiles - reference to hash for embedded objects
                   2809: #        $codebase - reference to hash for codebase of java objects
                   2810: #        $desuname - username for permanent storage of uploaded file
                   2811: #        $dsetudom - domain for permanaent storage of uploaded file
1.860     raeburn  2812: #        $thumbwidth - width (pixels) of thumbnail to make for uploaded image 
                   2813: #        $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051    raeburn  2814: #        $resizewidth - width (pixels) to which to resize uploaded image
                   2815: #        $resizeheight - height (pixels) to which to resize uploaded image
1.1095    raeburn  2816: #        $mimetype - reference to scalar to accommodate mime type determined
1.1152    raeburn  2817: #                    from File::MMagic.
1.858     raeburn  2818: # 
1.686     albertel 2819: # output: url of file in userspace, or error: <message> 
                   2820: #             or /adm/notfound.html if failure to upload occurse
1.608     albertel 2821: 
1.531     albertel 2822: sub userfileupload {
1.1090    raeburn  2823:     my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095    raeburn  2824:         $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531     albertel 2825:     if (!defined($subdir)) { $subdir='unknown'; }
1.620     albertel 2826:     my $fname=$env{'form.'.$formname.'.filename'};
1.531     albertel 2827:     $fname=&clean_filename($fname);
1.1090    raeburn  2828:     # See if there is anything left
1.257     www      2829:     unless ($fname) { return 'error: no uploaded file'; }
1.1090    raeburn  2830:     # Files uploaded to help request form, or uploaded to "create course" page are handled differently
                   2831:     if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
                   2832:         (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
                   2833:          ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523     raeburn  2834:         my $now = time;
1.1090    raeburn  2835:         my $filepath;
1.1095    raeburn  2836:         if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090    raeburn  2837:              $filepath = 'tmp/helprequests/'.$now;
                   2838:         } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
                   2839:              $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
                   2840:                          '_'.$env{'user.domain'}.'/pending';
                   2841:         } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
                   2842:             my ($docuname,$docudom);
                   2843:             if ($destudom) {
                   2844:                 $docudom = $destudom;
                   2845:             } else {
                   2846:                 $docudom = $env{'user.domain'};
                   2847:             }
                   2848:             if ($destuname) {
                   2849:                 $docuname = $destuname;
                   2850:             } else {
                   2851:                 $docuname = $env{'user.name'};
                   2852:             }
                   2853:             if (exists($env{'form.group'})) {
                   2854:                 $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2855:                 $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2856:             }
                   2857:             $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
                   2858:             if ($context eq 'canceloverwrite') {
                   2859:                 my $tempfile =  $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
                   2860:                 if (-e  $tempfile) {
                   2861:                     my @info = stat($tempfile);
                   2862:                     if ($info[9] eq $env{'form.timestamp'}) {
                   2863:                         unlink($tempfile);
                   2864:                     }
                   2865:                 }
                   2866:                 return;
1.523     raeburn  2867:             }
                   2868:         }
1.1090    raeburn  2869:         # Create the directory if not present
1.741     raeburn  2870:         my @parts=split(/\//,$filepath);
                   2871:         my $fullpath = $perlvar{'lonDaemons'};
                   2872:         for (my $i=0;$i<@parts;$i++) {
                   2873:             $fullpath .= '/'.$parts[$i];
                   2874:             if ((-e $fullpath)!=1) {
                   2875:                 mkdir($fullpath,0777);
                   2876:             }
                   2877:         }
                   2878:         open(my $fh,'>'.$fullpath.'/'.$fname);
                   2879:         print $fh $env{'form.'.$formname};
                   2880:         close($fh);
1.1090    raeburn  2881:         if ($context eq 'existingfile') {
                   2882:             my @info = stat($fullpath.'/'.$fname);
                   2883:             return ($fullpath.'/'.$fname,$info[9]);
                   2884:         } else {
                   2885:             return $fullpath.'/'.$fname;
                   2886:         }
1.523     raeburn  2887:     }
1.995     raeburn  2888:     if ($subdir eq 'scantron') {
                   2889:         $fname = 'scantron_orig_'.$fname;
1.1093    raeburn  2890:     } else {
1.995     raeburn  2891:         $fname="$subdir/$fname";
                   2892:     }
1.1090    raeburn  2893:     if ($context eq 'coursedoc') {
1.638     albertel 2894: 	my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2895: 	my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646     raeburn  2896:         if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638     albertel 2897:             return &finishuserfileupload($docuname,$docudom,
                   2898: 					 $formname,$fname,$parser,$allfiles,
1.1051    raeburn  2899: 					 $codebase,$thumbwidth,$thumbheight,
1.1095    raeburn  2900:                                          $resizewidth,$resizeheight,$context,$mimetype);
1.481     raeburn  2901:         } else {
1.620     albertel 2902:             $fname=$env{'form.folder'}.'/'.$fname;
1.638     albertel 2903:             return &process_coursefile('uploaddoc',$docuname,$docudom,
                   2904: 				       $fname,$formname,$parser,
1.1095    raeburn  2905: 				       $allfiles,$codebase,$mimetype);
1.481     raeburn  2906:         }
1.719     banghart 2907:     } elsif (defined($destuname)) {
                   2908:         my $docuname=$destuname;
                   2909:         my $docudom=$destudom;
1.860     raeburn  2910: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2911: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2912:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2913:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2914:     } else {
1.638     albertel 2915:         my $docuname=$env{'user.name'};
                   2916:         my $docudom=$env{'user.domain'};
1.714     raeburn  2917:         if (exists($env{'form.group'})) {
                   2918:             $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   2919:             $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
                   2920:         }
1.860     raeburn  2921: 	return &finishuserfileupload($docuname,$docudom,$formname,$fname,
                   2922: 				     $parser,$allfiles,$codebase,
1.1051    raeburn  2923:                                      $thumbwidth,$thumbheight,
1.1095    raeburn  2924:                                      $resizewidth,$resizeheight,$context,$mimetype);
1.259     www      2925:     }
1.271     www      2926: }
                   2927: 
                   2928: sub finishuserfileupload {
1.860     raeburn  2929:     my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095    raeburn  2930:         $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477     raeburn  2931:     my $path=$docudom.'/'.$docuname.'/';
1.258     www      2932:     my $filepath=$perlvar{'lonDocRoot'};
1.984     neumanie 2933:   
1.860     raeburn  2934:     my ($fnamepath,$file,$fetchthumb);
1.494     albertel 2935:     $file=$fname;
                   2936:     if ($fname=~m|/|) {
                   2937:         ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
                   2938: 	$path.=$fnamepath.'/';
                   2939:     }
1.259     www      2940:     my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258     www      2941:     my $count;
                   2942:     for ($count=4;$count<=$#parts;$count++) {
                   2943:         $filepath.="/$parts[$count]";
                   2944:         if ((-e $filepath)!=1) {
                   2945: 	    mkdir($filepath,0777);
                   2946:         }
                   2947:     }
1.984     neumanie 2948: 
1.258     www      2949: # Save the file
                   2950:     {
1.701     albertel 2951: 	if (!open(FH,'>'.$filepath.'/'.$file)) {
                   2952: 	    &logthis('Failed to create '.$filepath.'/'.$file);
                   2953: 	    print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
                   2954: 	    return '/adm/notfound.html';
                   2955: 	}
1.1090    raeburn  2956:         if ($context eq 'overwrite') {
1.1117    foxr     2957:             my $source =  LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090    raeburn  2958:             my $target = $filepath.'/'.$file;
                   2959:             if (-e $source) {
                   2960:                 my @info = stat($source);
                   2961:                 if ($info[9] eq $env{'form.timestamp'}) {   
                   2962:                     unless (&File::Copy::move($source,$target)) {
                   2963:                         &logthis('Failed to overwrite '.$filepath.'/'.$file);
                   2964:                         return "Moving from $source failed";
                   2965:                     }
                   2966:                 } else {
                   2967:                     return "Temporary file: $source had unexpected date/time for last modification";
                   2968:                 }
                   2969:             } else {
                   2970:                 return "Temporary file: $source missing";
                   2971:             }
                   2972:         } elsif (!print FH ($env{'form.'.$formname})) {
1.701     albertel 2973: 	    &logthis('Failed to write to '.$filepath.'/'.$file);
                   2974: 	    print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
                   2975: 	    return '/adm/notfound.html';
                   2976: 	}
1.570     albertel 2977: 	close(FH);
1.1051    raeburn  2978:         if ($resizewidth && $resizeheight) {
                   2979:             my $mm = new File::MMagic;
                   2980:             my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
                   2981:             if ($mime_type =~ m{^image/}) {
                   2982: 	        &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
                   2983:             }  
1.977     amueller 2984: 	}
1.258     www      2985:     }
1.1152    raeburn  2986:     if (($context eq 'coursedoc') || ($parser eq 'parse')) {
                   2987:         if (ref($mimetype)) {
                   2988:             if ($$mimetype eq '') {
                   2989:                 my $mm = new File::MMagic;
                   2990:                 my $type = $mm->checktype_filename($filepath.'/'.$file);
                   2991:                 $$mimetype = $type;
                   2992:             }
                   2993:         }
                   2994:     }
1.637     raeburn  2995:     if ($parser eq 'parse') {
1.1152    raeburn  2996:         if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024    raeburn  2997:             my $parse_result = &extract_embedded_items($filepath.'/'.$file,
                   2998:                                                        $allfiles,$codebase);
                   2999:             unless ($parse_result eq 'ok') {
                   3000:                 &logthis('Failed to parse '.$filepath.$file.
                   3001: 	   	         ' for embedded media: '.$parse_result); 
                   3002:             }
1.637     raeburn  3003:         }
                   3004:     }
1.860     raeburn  3005:     if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
                   3006:         my $input = $filepath.'/'.$file;
                   3007:         my $output = $filepath.'/'.'tn-'.$file;
                   3008:         my $thumbsize = $thumbwidth.'x'.$thumbheight;
                   3009:         system("convert -sample $thumbsize $input $output");
                   3010:         if (-e $filepath.'/'.'tn-'.$file) {
                   3011:             $fetchthumb  = 1; 
                   3012:         }
                   3013:     }
1.858     raeburn  3014:  
1.259     www      3015: # Notify homeserver to grep it
                   3016: #
1.984     neumanie 3017:     my $docuhome=&homeserver($docuname,$docudom);	
1.494     albertel 3018:     my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295     www      3019:     if ($fetchresult eq 'ok') {
1.860     raeburn  3020:         if ($fetchthumb) {
                   3021:             my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
                   3022:             if ($thumbresult ne 'ok') {
                   3023:                 &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
                   3024:                          $docuhome.': '.$thumbresult);
                   3025:             }
                   3026:         }
1.259     www      3027: #
1.258     www      3028: # Return the URL to it
1.494     albertel 3029:         return '/uploaded/'.$path.$file;
1.263     www      3030:     } else {
1.494     albertel 3031:         &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
                   3032: 		 ': '.$fetchresult);
1.263     www      3033:         return '/adm/notfound.html';
1.858     raeburn  3034:     }
1.493     albertel 3035: }
                   3036: 
1.637     raeburn  3037: sub extract_embedded_items {
1.961     raeburn  3038:     my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637     raeburn  3039:     my @state = ();
1.1164    raeburn  3040:     my (%lastids,%related,%shockwave,%flashvars);
1.637     raeburn  3041:     my %javafiles = (
                   3042:                       codebase => '',
                   3043:                       code => '',
                   3044:                       archive => ''
                   3045:                     );
                   3046:     my %mediafiles = (
                   3047:                       src => '',
                   3048:                       movie => '',
                   3049:                      );
1.648     raeburn  3050:     my $p;
                   3051:     if ($content) {
                   3052:         $p = HTML::LCParser->new($content);
                   3053:     } else {
1.961     raeburn  3054:         $p = HTML::LCParser->new($fullpath);
1.648     raeburn  3055:     }
1.641     albertel 3056:     while (my $t=$p->get_token()) {
1.640     albertel 3057: 	if ($t->[0] eq 'S') {
                   3058: 	    my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886     albertel 3059: 	    push(@state, $tagname);
1.648     raeburn  3060:             if (lc($tagname) eq 'allow') {
                   3061:                 &add_filetype($allfiles,$attr->{'src'},'src');
                   3062:             }
1.640     albertel 3063: 	    if (lc($tagname) eq 'img') {
                   3064: 		&add_filetype($allfiles,$attr->{'src'},'src');
                   3065: 	    }
1.886     albertel 3066: 	    if (lc($tagname) eq 'a') {
                   3067: 		&add_filetype($allfiles,$attr->{'href'},'href');
                   3068: 	    }
1.645     raeburn  3069:             if (lc($tagname) eq 'script') {
1.1164    raeburn  3070:                 my $src;
1.645     raeburn  3071:                 if ($attr->{'archive'} =~ /\.jar$/i) {
                   3072:                     &add_filetype($allfiles,$attr->{'archive'},'archive');
                   3073:                 } else {
1.1164    raeburn  3074:                     if ($attr->{'src'} ne '') {
                   3075:                         $src = $attr->{'src'};
                   3076:                         &add_filetype($allfiles,$src,'src');
                   3077:                     }
                   3078:                 }
                   3079:                 my $text = $p->get_trimmed_text();
                   3080:                 if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
                   3081:                     my @swfargs = split(/,/,$1);
                   3082:                     foreach my $item (@swfargs) {
                   3083:                         $item =~ s/["']//g;
                   3084:                         $item =~ s/^\s+//;
                   3085:                         $item =~ s/\s+$//;
                   3086:                     }
                   3087:                     if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
                   3088:                         if (ref($related{$swfargs[0]}) eq 'ARRAY') {
                   3089:                             push(@{$related{$swfargs[0]}},$swfargs[2]);
                   3090:                         } else {
                   3091:                             $related{$swfargs[0]} = [$swfargs[2]];
                   3092:                         }
                   3093:                     }
1.645     raeburn  3094:                 }
                   3095:             }
                   3096:             if (lc($tagname) eq 'link') {
                   3097:                 if (lc($attr->{'rel'}) eq 'stylesheet') { 
                   3098:                     &add_filetype($allfiles,$attr->{'href'},'href');
                   3099:                 }
                   3100:             }
1.640     albertel 3101: 	    if (lc($tagname) eq 'object' ||
                   3102: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
                   3103: 		foreach my $item (keys(%javafiles)) {
                   3104: 		    $javafiles{$item} = '';
                   3105: 		}
1.1164    raeburn  3106:                 if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
                   3107:                     $lastids{lc($tagname)} = $attr->{'id'};
                   3108:                 }
1.640     albertel 3109: 	    }
                   3110: 	    if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
                   3111: 		my $name = lc($attr->{'name'});
                   3112: 		foreach my $item (keys(%javafiles)) {
                   3113: 		    if ($name eq $item) {
                   3114: 			$javafiles{$item} = $attr->{'value'};
                   3115: 			last;
                   3116: 		    }
                   3117: 		}
1.1164    raeburn  3118:                 my $pathfrom;
1.640     albertel 3119: 		foreach my $item (keys(%mediafiles)) {
                   3120: 		    if ($name eq $item) {
1.1164    raeburn  3121:                         $pathfrom = $attr->{'value'};
                   3122:                         $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
                   3123: 			&add_filetype($allfiles,$pathfrom,$name);
1.640     albertel 3124: 			last;
                   3125: 		    }
                   3126: 		}
1.1164    raeburn  3127:                 if ($name eq 'flashvars') {
                   3128:                     $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
                   3129:                 }
                   3130:                 if ($pathfrom ne '') {
                   3131:                     &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
                   3132:                                          $pathfrom);
                   3133:                 }
1.640     albertel 3134: 	    }
                   3135: 	    if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
                   3136: 		foreach my $item (keys(%javafiles)) {
                   3137: 		    if ($attr->{$item}) {
                   3138: 			$javafiles{$item} = $attr->{$item};
                   3139: 			last;
                   3140: 		    }
                   3141: 		}
                   3142: 		foreach my $item (keys(%mediafiles)) {
                   3143: 		    if ($attr->{$item}) {
                   3144: 			&add_filetype($allfiles,$attr->{$item},$item);
                   3145: 			last;
                   3146: 		    }
                   3147: 		}
1.1164    raeburn  3148:                 if (lc($tagname) eq 'embed') {
                   3149:                     if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
                   3150:                         &embedded_dependency($allfiles,\%related,$attr->{'name'},
                   3151:                                              $attr->{'src'});
                   3152:                     }
                   3153:                 }
1.640     albertel 3154: 	    }
1.1164    raeburn  3155:             if ($t->[4] =~ m{/>$}) {
                   3156:                 pop(@state);  
                   3157:             }
1.640     albertel 3158: 	} elsif ($t->[0] eq 'E') {
                   3159: 	    my ($tagname) = ($t->[1]);
                   3160: 	    if ($javafiles{'codebase'} ne '') {
                   3161: 		$javafiles{'codebase'} .= '/';
                   3162: 	    }  
                   3163: 	    if (lc($tagname) eq 'applet' ||
                   3164: 		lc($tagname) eq 'object' ||
                   3165: 		(lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
                   3166: 		) {
                   3167: 		foreach my $item (keys(%javafiles)) {
                   3168: 		    if ($item ne 'codebase' && $javafiles{$item} ne '') {
                   3169: 			my $file=$javafiles{'codebase'}.$javafiles{$item};
                   3170: 			&add_filetype($allfiles,$file,$item);
                   3171: 		    }
                   3172: 		}
                   3173: 	    } 
                   3174: 	    pop @state;
                   3175: 	}
                   3176:     }
1.1164    raeburn  3177:     foreach my $id (sort(keys(%flashvars))) {
                   3178:         if ($shockwave{$id} ne '') {
                   3179:             my @pairs = split(/\&/,$flashvars{$id});
                   3180:             foreach my $pair (@pairs) {
                   3181:                 my ($key,$value) = split(/\=/,$pair);
                   3182:                 if ($key eq 'thumb') {
                   3183:                     &add_filetype($allfiles,$value,$key);
                   3184:                 } elsif ($key eq 'content') {
                   3185:                     my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
                   3186:                     my ($ext) = ($value =~ /\.([^.]+)$/);
                   3187:                     if ($ext ne '') {
                   3188:                         &add_filetype($allfiles,$path.$value,$ext);
                   3189:                     }
                   3190:                 }
                   3191:             }
                   3192:         }
                   3193:     }
1.637     raeburn  3194:     return 'ok';
                   3195: }
                   3196: 
1.639     albertel 3197: sub add_filetype {
                   3198:     my ($allfiles,$file,$type)=@_;
                   3199:     if (exists($allfiles->{$file})) {
                   3200: 	unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
                   3201: 	    push(@{$allfiles->{$file}}, &escape($type));
                   3202: 	}
                   3203:     } else {
                   3204: 	@{$allfiles->{$file}} = (&escape($type));
1.637     raeburn  3205:     }
                   3206: }
                   3207: 
1.1164    raeburn  3208: sub embedded_dependency {
                   3209:     my ($allfiles,$related,$identifier,$pathfrom) = @_;
                   3210:     if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
                   3211:         if (($identifier ne '') &&
                   3212:             (ref($related->{$identifier}) eq 'ARRAY') &&
                   3213:             ($pathfrom ne '')) {
                   3214:             my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
                   3215:             foreach my $dep (@{$related->{$identifier}}) {
                   3216:                 &add_filetype($allfiles,$path.$dep,'object');
                   3217:             }
                   3218:         }
                   3219:     }
                   3220:     return;
                   3221: }
                   3222: 
1.493     albertel 3223: sub removeuploadedurl {
1.984     neumanie 3224:     my ($url)=@_;	
                   3225:     my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);    
1.613     albertel 3226:     return &removeuserfile($uname,$udom,$fname);
1.490     albertel 3227: }
                   3228: 
                   3229: sub removeuserfile {
                   3230:     my ($docuname,$docudom,$fname)=@_;
1.984     neumanie 3231:     my $home=&homeserver($docuname,$docudom);    
1.798     raeburn  3232:     my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984     neumanie 3233:     if ($result eq 'ok') {	
1.798     raeburn  3234:         if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
                   3235:             my $metafile = $fname.'.meta';
                   3236:             my $metaresult = &removeuserfile($docuname,$docudom,$metafile); 
1.823     albertel 3237: 	    my $url = "/uploaded/$docudom/$docuname/$fname";
1.984     neumanie 3238:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];	   
1.821     raeburn  3239:             my $sqlresult = 
1.823     albertel 3240:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3241:                                         'portfolio_metadata',$group,
                   3242:                                         'delete');
1.798     raeburn  3243:         }
                   3244:     }
                   3245:     return $result;
1.257     www      3246: }
1.15      www      3247: 
1.530     albertel 3248: sub mkdiruserfile {
                   3249:     my ($docuname,$docudom,$dir)=@_;
                   3250:     my $home=&homeserver($docuname,$docudom);
                   3251:     return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
                   3252: }
                   3253: 
1.531     albertel 3254: sub renameuserfile {
                   3255:     my ($docuname,$docudom,$old,$new)=@_;
                   3256:     my $home=&homeserver($docuname,$docudom);
1.798     raeburn  3257:     my $result = &reply("renameuserfile:$docudom:$docuname:".
                   3258:                         &escape("$old").':'.&escape("$new"),$home);
                   3259:     if ($result eq 'ok') {
                   3260:         if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
                   3261:             my $oldmeta = $old.'.meta';
                   3262:             my $newmeta = $new.'.meta';
                   3263:             my $metaresult = 
                   3264:                 &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823     albertel 3265: 	    my $url = "/uploaded/$docudom/$docuname/$old";
                   3266:             my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821     raeburn  3267:             my $sqlresult = 
1.823     albertel 3268:                 &update_portfolio_table($docuname,$docudom,$file,
1.821     raeburn  3269:                                         'portfolio_metadata',$group,
                   3270:                                         'delete');
1.798     raeburn  3271:         }
                   3272:     }
                   3273:     return $result;
1.531     albertel 3274: }
                   3275: 
1.14      www      3276: # ------------------------------------------------------------------------- Log
                   3277: 
                   3278: sub log {
                   3279:     my ($dom,$nam,$hom,$what)=@_;
1.47      www      3280:     return critical("log:$dom:$nam:$what",$hom);
1.157     www      3281: }
                   3282: 
                   3283: # ------------------------------------------------------------------ Course Log
1.352     www      3284: #
                   3285: # This routine flushes several buffers of non-mission-critical nature
                   3286: #
1.157     www      3287: 
                   3288: sub flushcourselogs {
1.352     www      3289:     &logthis('Flushing log buffers');
                   3290: #
                   3291: # course logs
                   3292: # This is a log of all transactions in a course, which can be used
                   3293: # for data mining purposes
                   3294: #
                   3295: # It also collects the courseid database, which lists last transaction
                   3296: # times and course titles for all courseids
                   3297: #
                   3298:     my %courseidbuffer=();
1.921     raeburn  3299:     foreach my $crsid (keys(%courselogs)) {
1.352     www      3300:         if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188     www      3301: 		          &escape($courselogs{$crsid}),
                   3302: 		          $coursehombuf{$crsid}) eq 'ok') {
1.157     www      3303: 	    delete $courselogs{$crsid};
                   3304:         } else {
                   3305:             &logthis('Failed to flush log buffer for '.$crsid);
                   3306:             if (length($courselogs{$crsid})>40000) {
1.672     albertel 3307:                &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157     www      3308:                         " exceeded maximum size, deleting.</font>");
                   3309:                delete $courselogs{$crsid};
                   3310:             }
1.352     www      3311:         }
1.920     raeburn  3312:         $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936     raeburn  3313:             'description' => $coursedescrbuf{$crsid},
                   3314:             'inst_code'    => $courseinstcodebuf{$crsid},
                   3315:             'type'        => $coursetypebuf{$crsid},
                   3316:             'owner'       => $courseownerbuf{$crsid},
1.920     raeburn  3317:         };
1.191     harris41 3318:     }
1.352     www      3319: #
                   3320: # Write course id database (reverse lookup) to homeserver of courses 
                   3321: # Is used in pickcourse
                   3322: #
1.840     albertel 3323:     foreach my $crs_home (keys(%courseidbuffer)) {
1.918     raeburn  3324:         my $response = &courseidput(&host_domain($crs_home),
1.921     raeburn  3325:                                     $courseidbuffer{$crs_home},
                   3326:                                     $crs_home,'timeonly');
1.352     www      3327:     }
                   3328: #
                   3329: # File accesses
                   3330: # Writes to the dynamic metadata of resources to get hit counts, etc.
                   3331: #
1.449     matthew  3332:     foreach my $entry (keys(%accesshash)) {
1.458     matthew  3333:         if ($entry =~ /___count$/) {
                   3334:             my ($dom,$name);
1.807     albertel 3335:             ($dom,$name,undef)=
1.811     albertel 3336: 		($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458     matthew  3337:             if (! defined($dom) || $dom eq '' || 
                   3338:                 ! defined($name) || $name eq '') {
1.620     albertel 3339:                 my $cid = $env{'request.course.id'};
                   3340:                 $dom  = $env{'request.'.$cid.'.domain'};
                   3341:                 $name = $env{'request.'.$cid.'.num'};
1.458     matthew  3342:             }
1.450     matthew  3343:             my $value = $accesshash{$entry};
                   3344:             my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
                   3345:             my %temphash=($url => $value);
1.449     matthew  3346:             my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
                   3347:             if ($result eq 'ok') {
                   3348:                 delete $accesshash{$entry};
                   3349:             }
                   3350:         } else {
1.811     albertel 3351:             my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159    www      3352:             if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450     matthew  3353:             my %temphash=($entry => $accesshash{$entry});
1.449     matthew  3354:             if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
                   3355:                 delete $accesshash{$entry};
                   3356:             }
1.185     www      3357:         }
1.191     harris41 3358:     }
1.352     www      3359: #
                   3360: # Roles
                   3361: # Reverse lookup of user roles for course faculty/staff and co-authorship
                   3362: #
1.800     albertel 3363:     foreach my $entry (keys(%userrolehash)) {
1.351     www      3364:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349     www      3365: 	    split(/\:/,$entry);
                   3366:         if (&Apache::lonnet::put('nohist_userroles',
1.351     www      3367:              { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349     www      3368:                 $rudom,$runame) eq 'ok') {
                   3369: 	    delete $userrolehash{$entry};
                   3370:         }
                   3371:     }
1.662     raeburn  3372: #
                   3373: # Reverse lookup of domain roles (dc, ad, li, sc, au)
                   3374: #
                   3375:     my %domrolebuffer = ();
1.1000    raeburn  3376:     foreach my $entry (keys(%domainrolehash)) {
1.901     albertel 3377:         my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662     raeburn  3378:         if ($domrolebuffer{$rudom}) {
                   3379:             $domrolebuffer{$rudom}.='&'.&escape($entry).
                   3380:                       '='.&escape($domainrolehash{$entry});
                   3381:         } else {
                   3382:             $domrolebuffer{$rudom}.=&escape($entry).
                   3383:                       '='.&escape($domainrolehash{$entry});
                   3384:         }
                   3385:         delete $domainrolehash{$entry};
                   3386:     }
                   3387:     foreach my $dom (keys(%domrolebuffer)) {
1.841     albertel 3388: 	my %servers = &get_servers($dom,'library');
                   3389: 	foreach my $tryserver (keys(%servers)) {
                   3390: 	    unless (&reply('domroleput:'.$dom.':'.
                   3391: 			   $domrolebuffer{$dom},$tryserver) eq 'ok') {
                   3392: 		&logthis('Put of domain roles failed for '.$dom.' and  '.$tryserver);
                   3393: 	    }
1.662     raeburn  3394:         }
                   3395:     }
1.186     www      3396:     $dumpcount++;
1.157     www      3397: }
                   3398: 
                   3399: sub courselog {
                   3400:     my $what=shift;
1.158     www      3401:     $what=time.':'.$what;
1.620     albertel 3402:     unless ($env{'request.course.id'}) { return ''; }
                   3403:     $coursedombuf{$env{'request.course.id'}}=
                   3404:        $env{'course.'.$env{'request.course.id'}.'.domain'};
                   3405:     $coursenumbuf{$env{'request.course.id'}}=
                   3406:        $env{'course.'.$env{'request.course.id'}.'.num'};
                   3407:     $coursehombuf{$env{'request.course.id'}}=
                   3408:        $env{'course.'.$env{'request.course.id'}.'.home'};
                   3409:     $coursedescrbuf{$env{'request.course.id'}}=
                   3410:        $env{'course.'.$env{'request.course.id'}.'.description'};
                   3411:     $courseinstcodebuf{$env{'request.course.id'}}=
                   3412:        $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
                   3413:     $courseownerbuf{$env{'request.course.id'}}=
                   3414:        $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741     raeburn  3415:     $coursetypebuf{$env{'request.course.id'}}=
                   3416:        $env{'course.'.$env{'request.course.id'}.'.type'};
1.620     albertel 3417:     if (defined $courselogs{$env{'request.course.id'}}) {
                   3418: 	$courselogs{$env{'request.course.id'}}.='&'.$what;
1.157     www      3419:     } else {
1.620     albertel 3420: 	$courselogs{$env{'request.course.id'}}.=$what;
1.157     www      3421:     }
1.620     albertel 3422:     if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157     www      3423: 	&flushcourselogs();
                   3424:     }
1.158     www      3425: }
                   3426: 
                   3427: sub courseacclog {
                   3428:     my $fnsymb=shift;
1.620     albertel 3429:     unless ($env{'request.course.id'}) { return ''; }
                   3430:     my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144    www      3431:     if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187     www      3432:         $what.=':POST';
1.583     matthew  3433:         # FIXME: Probably ought to escape things....
1.800     albertel 3434: 	foreach my $key (keys(%env)) {
                   3435:             if ($key=~/^form\.(.*)/) {
1.975     raeburn  3436:                 my $formitem = $1;
                   3437:                 if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
                   3438:                     $what.=':'.$formitem.'='.$env{$key};
                   3439:                 } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
                   3440:                     $what.=':'.$formitem.'='.$env{$key};
                   3441:                 }
1.158     www      3442:             }
1.191     harris41 3443:         }
1.583     matthew  3444:     } elsif ($fnsymb =~ m:^/adm/searchcat:) {
                   3445:         # FIXME: We should not be depending on a form parameter that someone
                   3446:         # editing lonsearchcat.pm might change in the future.
1.620     albertel 3447:         if ($env{'form.phase'} eq 'course_search') {
1.583     matthew  3448:             $what.= ':POST';
                   3449:             # FIXME: Probably ought to escape things....
                   3450:             foreach my $element ('courseexp','crsfulltext','crsrelated',
                   3451:                                  'crsdiscuss') {
1.620     albertel 3452:                 $what.=':'.$element.'='.$env{'form.'.$element};
1.583     matthew  3453:             }
                   3454:         }
1.158     www      3455:     }
                   3456:     &courselog($what);
1.149     www      3457: }
                   3458: 
1.185     www      3459: sub countacc {
                   3460:     my $url=&declutter(shift);
1.458     matthew  3461:     return if (! defined($url) || $url eq '');
1.620     albertel 3462:     unless ($env{'request.course.id'}) { return ''; }
1.1158    www      3463: #
                   3464: # Mark that this url was used in this course
                   3465: #
1.620     albertel 3466:     $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158    www      3467: #
                   3468: # Increase the access count for this resource in this child process
                   3469: #
1.281     www      3470:     my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450     matthew  3471:     $accesshash{$key}++;
1.185     www      3472: }
1.349     www      3473: 
1.361     www      3474: sub linklog {
                   3475:     my ($from,$to)=@_;
                   3476:     $from=&declutter($from);
                   3477:     $to=&declutter($to);
                   3478:     $accesshash{$from.'___'.$to.'___comefrom'}=1;
                   3479:     $accesshash{$to.'___'.$from.'___goto'}=1;
                   3480: }
1.1160    www      3481: 
                   3482: sub statslog {
                   3483:     my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
                   3484:     if ($users<2) { return; }
                   3485:     my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
                   3486:             'course'       => $env{'request.course.id'},
                   3487:             'sections'     => '"all"',
                   3488:             'num_students' => $users,
                   3489:             'part'         => $part,
                   3490:             'symb'         => $symb,
                   3491:             'mean_tries'   => $av_attempts,
                   3492:             'deg_of_diff'  => $degdiff});
                   3493:     foreach my $key (keys(%dynstore)) {
                   3494:         $accesshash{$key}=$dynstore{$key};
                   3495:     }
                   3496: }
1.361     www      3497:   
1.349     www      3498: sub userrolelog {
                   3499:     my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169    droeschl 3500:     if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350     www      3501:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3502:        $userrolehash
                   3503:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349     www      3504:                     =$tend.':'.$tstart;
1.662     raeburn  3505:     }
1.1169    droeschl 3506:     if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898     albertel 3507:        $userrolehash
                   3508:          {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
                   3509:                     =$tend.':'.$tstart;
                   3510:     }
1.1169    droeschl 3511:     if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662     raeburn  3512:        my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
                   3513:        $domainrolehash
                   3514:          {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
                   3515:                     = $tend.':'.$tstart;
                   3516:     }
1.351     www      3517: }
                   3518: 
1.957     raeburn  3519: sub courserolelog {
                   3520:     my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
                   3521:     if (($trole eq 'cc') || ($trole eq 'in') ||
                   3522:         ($trole eq 'ep') || ($trole eq 'ad') ||
                   3523:         ($trole eq 'ta') || ($trole eq 'st') ||
1.1044    raeburn  3524:         ($trole=~/^cr/) || ($trole eq 'gr') ||
                   3525:         ($trole eq 'co')) {
1.957     raeburn  3526:         if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
                   3527:             my $cdom = $1;
                   3528:             my $cnum = $2;
                   3529:             my $sec = $3;
                   3530:             my $namespace = 'rolelog';
                   3531:             my %storehash = (
                   3532:                                role    => $trole,
                   3533:                                start   => $tstart,
                   3534:                                end     => $tend,
                   3535:                                selfenroll => $selfenroll,
                   3536:                                context    => $context,
                   3537:                             );
                   3538:             if ($trole eq 'gr') {
                   3539:                 $namespace = 'groupslog';
                   3540:                 $storehash{'group'} = $sec;
                   3541:             } else {
                   3542:                 $storehash{'section'} = $sec;
                   3543:             }
                   3544:             &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996     raeburn  3545:             if (($trole ne 'st') || ($sec ne '')) {
                   3546:                 &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
                   3547:             }
1.957     raeburn  3548:         }
                   3549:     }
                   3550:     return;
                   3551: }
                   3552: 
1.351     www      3553: sub get_course_adv_roles {
1.948     raeburn  3554:     my ($cid,$codes) = @_;
1.620     albertel 3555:     $cid=$env{'request.course.id'} unless (defined($cid));
1.351     www      3556:     my %coursehash=&coursedescription($cid);
1.988     raeburn  3557:     my $crstype = &Apache::loncommon::course_type($cid);
1.470     www      3558:     my %nothide=();
1.800     albertel 3559:     foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937     raeburn  3560:         if ($user !~ /:/) {
                   3561: 	    $nothide{join(':',split(/[\@]/,$user))}=1;
                   3562:         } else {
                   3563:             $nothide{$user}=1;
                   3564:         }
1.470     www      3565:     }
1.351     www      3566:     my %returnhash=();
                   3567:     my %dumphash=
                   3568:             &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
                   3569:     my $now=time;
1.997     raeburn  3570:     my %privileged;
1.1000    raeburn  3571:     foreach my $entry (keys(%dumphash)) {
1.800     albertel 3572: 	my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351     www      3573:         if (($tstart) && ($tstart<0)) { next; }
                   3574:         if (($tend) && ($tend<$now)) { next; }
                   3575:         if (($tstart) && ($now<$tstart)) { next; }
1.800     albertel 3576:         my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576     albertel 3577: 	if ($username eq '' || $domain eq '') { next; }
1.997     raeburn  3578:         unless (ref($privileged{$domain}) eq 'HASH') {
                   3579:             my %dompersonnel =
1.998     raeburn  3580:                 &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997     raeburn  3581:             $privileged{$domain} = {};
                   3582:             foreach my $server (keys(%dompersonnel)) {
1.999     raeburn  3583:                 if (ref($dompersonnel{$server}) eq 'HASH') {
1.997     raeburn  3584:                     foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3585:                         my ($trole,$uname,$udom) = split(/:/,$user);
                   3586:                         $privileged{$udom}{$uname} = 1;
                   3587:                     }
                   3588:                 }
                   3589:             }
                   3590:         }
                   3591:         if ((exists($privileged{$domain}{$username})) && 
                   3592:             (!$nothide{$username.':'.$domain})) { next; }
1.656     albertel 3593: 	if ($role eq 'cr') { next; }
1.948     raeburn  3594:         if ($codes) {
                   3595:             if ($section) { $role .= ':'.$section; }
                   3596:             if ($returnhash{$role}) {
                   3597:                 $returnhash{$role}.=','.$username.':'.$domain;
                   3598:             } else {
                   3599:                 $returnhash{$role}=$username.':'.$domain;
                   3600:             }
1.351     www      3601:         } else {
1.988     raeburn  3602:             my $key=&plaintext($role,$crstype);
1.973     bisitz   3603:             if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948     raeburn  3604:             if ($returnhash{$key}) {
                   3605: 	        $returnhash{$key}.=','.$username.':'.$domain;
                   3606:             } else {
                   3607:                 $returnhash{$key}=$username.':'.$domain;
                   3608:             }
1.351     www      3609:         }
1.948     raeburn  3610:     }
1.400     www      3611:     return %returnhash;
                   3612: }
                   3613: 
                   3614: sub get_my_roles {
1.937     raeburn  3615:     my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620     albertel 3616:     unless (defined($uname)) { $uname=$env{'user.name'}; }
                   3617:     unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937     raeburn  3618:     my (%dumphash,%nothide);
1.1086    raeburn  3619:     if ($context eq 'userroles') {
1.1166    raeburn  3620:         %dumphash = &dump('roles',$udom,$uname);
1.858     raeburn  3621:     } else {
                   3622:         %dumphash=
1.400     www      3623:             &dump('nohist_userroles',$udom,$uname);
1.937     raeburn  3624:         if ($hidepriv) {
                   3625:             my %coursehash=&coursedescription($udom.'_'.$uname);
                   3626:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   3627:                 if ($user !~ /:/) {
                   3628:                     $nothide{join(':',split(/[\@]/,$user))} = 1;
                   3629:                 } else {
                   3630:                     $nothide{$user} = 1;
                   3631:                 }
                   3632:             }
                   3633:         }
1.858     raeburn  3634:     }
1.400     www      3635:     my %returnhash=();
                   3636:     my $now=time;
1.999     raeburn  3637:     my %privileged;
1.800     albertel 3638:     foreach my $entry (keys(%dumphash)) {
1.867     raeburn  3639:         my ($role,$tend,$tstart);
                   3640:         if ($context eq 'userroles') {
1.1149    raeburn  3641:             next if ($entry =~ /^rolesdef/);
1.867     raeburn  3642: 	    ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
                   3643:         } else {
                   3644:             ($tend,$tstart)=split(/\:/,$dumphash{$entry});
                   3645:         }
1.400     www      3646:         if (($tstart) && ($tstart<0)) { next; }
1.832     raeburn  3647:         my $status = 'active';
1.939     raeburn  3648:         if (($tend) && ($tend<=$now)) {
1.832     raeburn  3649:             $status = 'previous';
                   3650:         } 
                   3651:         if (($tstart) && ($now<$tstart)) {
                   3652:             $status = 'future';
                   3653:         }
                   3654:         if (ref($types) eq 'ARRAY') {
                   3655:             if (!grep(/^\Q$status\E$/,@{$types})) {
                   3656:                 next;
                   3657:             } 
                   3658:         } else {
                   3659:             if ($status ne 'active') {
                   3660:                 next;
                   3661:             }
                   3662:         }
1.867     raeburn  3663:         my ($rolecode,$username,$domain,$section,$area);
                   3664:         if ($context eq 'userroles') {
                   3665:             ($area,$rolecode) = split(/_/,$entry);
                   3666:             (undef,$domain,$username,$section) = split(/\//,$area);
                   3667:         } else {
                   3668:             ($role,$username,$domain,$section) = split(/\:/,$entry);
                   3669:         }
1.832     raeburn  3670:         if (ref($roledoms) eq 'ARRAY') {
                   3671:             if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
                   3672:                 next;
                   3673:             }
                   3674:         }
                   3675:         if (ref($roles) eq 'ARRAY') {
                   3676:             if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922     raeburn  3677:                 if ($role =~ /^cr\//) {
                   3678:                     if (!grep(/^cr$/,@{$roles})) {
                   3679:                         next;
                   3680:                     }
1.1104    raeburn  3681:                 } elsif ($role =~ /^gr\//) {
                   3682:                     if (!grep(/^gr$/,@{$roles})) {
                   3683:                         next;
                   3684:                     }
1.922     raeburn  3685:                 } else {
                   3686:                     next;
                   3687:                 }
1.832     raeburn  3688:             }
1.867     raeburn  3689:         }
1.937     raeburn  3690:         if ($hidepriv) {
1.999     raeburn  3691:             if ($context eq 'userroles') {
                   3692:                 if ((&privileged($username,$domain)) &&
                   3693:                     (!$nothide{$username.':'.$domain})) {
                   3694:                     next;
                   3695:                 }
                   3696:             } else {
                   3697:                 unless (ref($privileged{$domain}) eq 'HASH') {
                   3698:                     my %dompersonnel =
                   3699:                         &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
                   3700:                     $privileged{$domain} = {};
                   3701:                     if (keys(%dompersonnel)) {
                   3702:                         foreach my $server (keys(%dompersonnel)) {
                   3703:                             if (ref($dompersonnel{$server}) eq 'HASH') {
                   3704:                                 foreach my $user (keys(%{$dompersonnel{$server}})) {
                   3705:                                     my ($trole,$uname,$udom) = split(/:/,$user);
                   3706:                                     $privileged{$udom}{$uname} = $trole;
                   3707:                                 }
                   3708:                             }
                   3709:                         }
                   3710:                     }
                   3711:                 }
                   3712:                 if (exists($privileged{$domain}{$username})) {
                   3713:                     if (!$nothide{$username.':'.$domain}) {
                   3714:                         next;
                   3715:                     }
                   3716:                 }
1.937     raeburn  3717:             }
                   3718:         }
1.933     raeburn  3719:         if ($withsec) {
                   3720:             $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
                   3721:                 $tstart.':'.$tend;
                   3722:         } else {
                   3723:             $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
                   3724:         }
1.832     raeburn  3725:     }
1.373     www      3726:     return %returnhash;
1.399     www      3727: }
                   3728: 
                   3729: # ----------------------------------------------------- Frontpage Announcements
                   3730: #
                   3731: #
                   3732: 
                   3733: sub postannounce {
                   3734:     my ($server,$text)=@_;
1.844     albertel 3735:     unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399     www      3736:     unless ($text=~/\w/) { $text=''; }
                   3737:     return &reply('setannounce:'.&escape($text),$server);
                   3738: }
                   3739: 
                   3740: sub getannounce {
1.448     albertel 3741: 
                   3742:     if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399     www      3743: 	my $announcement='';
1.800     albertel 3744: 	while (my $line = <$fh>) { $announcement .= $line; }
1.448     albertel 3745: 	close($fh);
1.399     www      3746: 	if ($announcement=~/\w/) { 
                   3747: 	    return 
                   3748:    '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518     albertel 3749:    '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>'; 
1.399     www      3750: 	} else {
                   3751: 	    return '';
                   3752: 	}
                   3753:     } else {
                   3754: 	return '';
                   3755:     }
1.351     www      3756: }
1.353     www      3757: 
                   3758: # ---------------------------------------------------------- Course ID routines
                   3759: # Deal with domain's nohist_courseid.db files
                   3760: #
                   3761: 
                   3762: sub courseidput {
1.921     raeburn  3763:     my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054    raeburn  3764:     return unless (ref($storehash) eq 'HASH');
1.921     raeburn  3765:     my $outcome;
                   3766:     if ($caller eq 'timeonly') {
                   3767:         my $cids = '';
                   3768:         foreach my $item (keys(%$storehash)) {
                   3769:             $cids.=&escape($item).'&';
                   3770:         }
                   3771:         $cids=~s/\&$//;
                   3772:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
                   3773:                           $coursehome);       
                   3774:     } else {
                   3775:         my $items = '';
                   3776:         foreach my $item (keys(%$storehash)) {
                   3777:             $items.= &escape($item).'='.
                   3778:                      &freeze_escape($$storehash{$item}).'&';
                   3779:         }
                   3780:         $items=~s/\&$//;
                   3781:         $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
                   3782:                           $coursehome);
1.918     raeburn  3783:     }
                   3784:     if ($outcome eq 'unknown_cmd') {
                   3785:         my $what;
                   3786:         foreach my $cid (keys(%$storehash)) {
                   3787:             $what .= &escape($cid).'=';
1.921     raeburn  3788:             foreach my $item ('description','inst_code','owner','type') {
1.936     raeburn  3789:                 $what .= &escape($storehash->{$cid}{$item}).':';
1.918     raeburn  3790:             }
                   3791:             $what =~ s/\:$/&/;
                   3792:         }
                   3793:         $what =~ s/\&$//;  
                   3794:         return &reply('courseidput:'.$domain.':'.$what,$coursehome);
                   3795:     } else {
                   3796:         return $outcome;
                   3797:     }
1.353     www      3798: }
                   3799: 
                   3800: sub courseiddump {
1.921     raeburn  3801:     my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947     raeburn  3802:         $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029    raeburn  3803:         $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071    raeburn  3804:         $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918     raeburn  3805:     my $as_hash = 1;
                   3806:     my %returnhash;
                   3807:     if (!$domfilter) { $domfilter=''; }
1.845     albertel 3808:     my %libserv = &all_library();
                   3809:     foreach my $tryserver (keys(%libserv)) {
                   3810:         if ( (  $hostidflag == 1 
                   3811: 	        && grep(/^\Q$tryserver\E$/,@{$hostidref}) ) 
                   3812: 	     || (!defined($hostidflag)) ) {
                   3813: 
1.918     raeburn  3814: 	    if (($domfilter eq '') ||
                   3815: 		(&host_domain($tryserver) eq $domfilter)) {
                   3816:                 my $rep = 
                   3817:                   &reply('courseiddump:'.&host_domain($tryserver).':'.
                   3818:                          $sincefilter.':'.&escape($descfilter).':'.
                   3819:                          &escape($instcodefilter).':'.&escape($ownerfilter).
                   3820:                          ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947     raeburn  3821:                          ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962     raeburn  3822:                          &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008    raeburn  3823:                          $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029    raeburn  3824:                          &escape($cc_clone).':'.$cloneonly.':'.
                   3825:                          &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071    raeburn  3826:                          &escape($creationcontext).':'.$domcloner,
                   3827:                          $tryserver);
1.918     raeburn  3828:                 my @pairs=split(/\&/,$rep);
                   3829:                 foreach my $item (@pairs) {
                   3830:                     my ($key,$value)=split(/\=/,$item,2);
                   3831:                     $key = &unescape($key);
                   3832:                     next if ($key =~ /^error: 2 /);
                   3833:                     my $result = &thaw_unescape($value);
                   3834:                     if (ref($result) eq 'HASH') {
                   3835:                         $returnhash{$key}=$result;
                   3836:                     } else {
1.921     raeburn  3837:                         my @responses = split(/:/,$value);
                   3838:                         my @items = ('description','inst_code','owner','type');
1.918     raeburn  3839:                         for (my $i=0; $i<@responses; $i++) {
1.921     raeburn  3840:                             $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918     raeburn  3841:                         }
1.1008    raeburn  3842:                     }
1.353     www      3843:                 }
                   3844:             }
                   3845:         }
                   3846:     }
                   3847:     return %returnhash;
                   3848: }
                   3849: 
1.1055    raeburn  3850: sub courselastaccess {
                   3851:     my ($cdom,$cnum,$hostidref) = @_;
                   3852:     my %returnhash;
                   3853:     if ($cdom && $cnum) {
                   3854:         my $chome = &homeserver($cnum,$cdom);
                   3855:         if ($chome ne 'no_host') {
                   3856:             my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
                   3857:             &extract_lastaccess(\%returnhash,$rep);
                   3858:         }
                   3859:     } else {
                   3860:         if (!$cdom) { $cdom=''; }
                   3861:         my %libserv = &all_library();
                   3862:         foreach my $tryserver (keys(%libserv)) {
                   3863:             if (ref($hostidref) eq 'ARRAY') {
                   3864:                 next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
                   3865:             } 
                   3866:             if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
                   3867:                 my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
                   3868:                 &extract_lastaccess(\%returnhash,$rep);
                   3869:             }
                   3870:         }
                   3871:     }
                   3872:     return %returnhash;
                   3873: }
                   3874: 
                   3875: sub extract_lastaccess {
                   3876:     my ($returnhash,$rep) = @_;
                   3877:     if (ref($returnhash) eq 'HASH') {
                   3878:         unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' || 
                   3879:                 $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
                   3880:                  $rep eq '') {
                   3881:             my @pairs=split(/\&/,$rep);
                   3882:             foreach my $item (@pairs) {
                   3883:                 my ($key,$value)=split(/\=/,$item,2);
                   3884:                 $key = &unescape($key);
                   3885:                 next if ($key =~ /^error: 2 /);
                   3886:                 $returnhash->{$key} = &thaw_unescape($value);
                   3887:             }
                   3888:         }
                   3889:     }
                   3890:     return;
                   3891: }
                   3892: 
1.658     raeburn  3893: # ---------------------------------------------------------- DC e-mail
1.662     raeburn  3894: 
                   3895: sub dcmailput {
1.685     raeburn  3896:     my ($domain,$msgid,$message,$server)=@_;
1.662     raeburn  3897:     my $status = &Apache::lonnet::critical(
1.740     www      3898:        'dcmailput:'.$domain.':'.&escape($msgid).'='.
                   3899:        &escape($message),$server);
1.662     raeburn  3900:     return $status;
                   3901: }
                   3902: 
1.658     raeburn  3903: sub dcmaildump {
                   3904:     my ($dom,$startdate,$enddate,$senders) = @_;
1.685     raeburn  3905:     my %returnhash=();
1.846     albertel 3906: 
                   3907:     if (defined(&domain($dom,'primary'))) {
1.685     raeburn  3908:         my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
                   3909:                                                          &escape($enddate).':';
                   3910: 	my @esc_senders=map { &escape($_)} @$senders;
                   3911: 	$cmd.=&escape(join('&',@esc_senders));
1.846     albertel 3912: 	foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800     albertel 3913:             my ($key,$value) = split(/\=/,$line,2);
1.685     raeburn  3914:             if (($key) && ($value)) {
                   3915:                 $returnhash{&unescape($key)} = &unescape($value);
1.658     raeburn  3916:             }
                   3917:         }
                   3918:     }
                   3919:     return %returnhash;
                   3920: }
1.662     raeburn  3921: # ---------------------------------------------------------- Domain roles
                   3922: 
                   3923: sub get_domain_roles {
                   3924:     my ($dom,$roles,$startdate,$enddate)=@_;
1.1018    raeburn  3925:     if ((!defined($startdate)) || ($startdate eq '')) {
1.662     raeburn  3926:         $startdate = '.';
                   3927:     }
1.1018    raeburn  3928:     if ((!defined($enddate)) || ($enddate eq '')) {
1.662     raeburn  3929:         $enddate = '.';
                   3930:     }
1.922     raeburn  3931:     my $rolelist;
                   3932:     if (ref($roles) eq 'ARRAY') {
                   3933:         $rolelist = join(':',@{$roles});
                   3934:     }
1.662     raeburn  3935:     my %personnel = ();
1.841     albertel 3936: 
                   3937:     my %servers = &get_servers($dom,'library');
                   3938:     foreach my $tryserver (keys(%servers)) {
                   3939: 	%{$personnel{$tryserver}}=();
                   3940: 	foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
                   3941: 					    &escape($startdate).':'.
                   3942: 					    &escape($enddate).':'.
                   3943: 					    &escape($rolelist), $tryserver))) {
                   3944: 	    my ($key,$value) = split(/\=/,$line,2);
                   3945: 	    if (($key) && ($value)) {
                   3946: 		$personnel{$tryserver}{&unescape($key)} = &unescape($value);
                   3947: 	    }
                   3948: 	}
1.662     raeburn  3949:     }
                   3950:     return %personnel;
                   3951: }
1.658     raeburn  3952: 
1.1057    www      3953: # ----------------------------------------------------------- Interval timing 
1.149     www      3954: 
1.1153    www      3955: {
                   3956: # Caches needed for speedup of navmaps
                   3957: # We don't want to cache this for very long at all (5 seconds at most)
                   3958: # 
                   3959: # The user for whom we cache
                   3960: my $cachedkey='';
                   3961: # The cached times for this user
                   3962: my %cachedtimes=();
                   3963: # When this was last done
                   3964: my $cachedtime=();
                   3965: 
                   3966: sub load_all_first_access {
1.1154    raeburn  3967:     my ($uname,$udom)=@_;
1.1156    www      3968:     if (($cachedkey eq $uname.':'.$udom) &&
1.1174    raeburn  3969:         (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154    raeburn  3970:         return;
                   3971:     }
                   3972:     $cachedtime=time;
                   3973:     $cachedkey=$uname.':'.$udom;
                   3974:     %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153    www      3975: }
                   3976: 
1.504     albertel 3977: sub get_first_access {
1.1162    raeburn  3978:     my ($type,$argsymb,$argmap)=@_;
1.790     albertel 3979:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3980:     if ($argsymb) { $symb=$argsymb; }
                   3981:     my ($map,$id,$res)=&decode_symb($symb);
1.1162    raeburn  3982:     if ($argmap) { $map = $argmap; }
1.926     albertel 3983:     if ($type eq 'course') {
                   3984: 	$res='course';
                   3985:     } elsif ($type eq 'map') {
1.588     albertel 3986: 	$res=&symbread($map);
                   3987:     } else {
                   3988: 	$res=$symb;
                   3989:     }
1.1153    www      3990:     &load_all_first_access($uname,$udom);
                   3991:     return $cachedtimes{"$courseid\0$res"};
1.504     albertel 3992: }
                   3993: 
                   3994: sub set_first_access {
1.1162    raeburn  3995:     my ($type,$interval)=@_;
1.790     albertel 3996:     my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504     albertel 3997:     my ($map,$id,$res)=&decode_symb($symb);
1.928     albertel 3998:     if ($type eq 'course') {
                   3999: 	$res='course';
                   4000:     } elsif ($type eq 'map') {
1.588     albertel 4001: 	$res=&symbread($map);
                   4002:     } else {
                   4003: 	$res=$symb;
                   4004:     }
1.1153    www      4005:     $cachedkey='';
1.1162    raeburn  4006:     my $firstaccess=&get_first_access($type,$symb,$map);
1.505     albertel 4007:     if (!$firstaccess) {
1.1162    raeburn  4008:         my $start = time;
                   4009: 	my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
                   4010:                           $udom,$uname);
                   4011:         if ($putres eq 'ok') {
                   4012:             &put('timerinterval',{"$courseid\0$res"=>$interval},
                   4013:                  $udom,$uname); 
                   4014:             &appenv(
                   4015:                      {
                   4016:                         'course.'.$courseid.'.firstaccess.'.$res   => $start,
                   4017:                         'course.'.$courseid.'.timerinterval.'.$res => $interval,
                   4018:                      }
                   4019:                   );
                   4020:         }
                   4021:         return $putres;
1.505     albertel 4022:     }
                   4023:     return 'already_set';
1.504     albertel 4024: }
1.1153    www      4025: }
1.110     www      4026: # --------------------------------------------- Set Expire Date for Spreadsheet
                   4027: 
                   4028: sub expirespread {
                   4029:     my ($uname,$udom,$stype,$usymb)=@_;
1.620     albertel 4030:     my $cid=$env{'request.course.id'}; 
1.110     www      4031:     if ($cid) {
                   4032:        my $now=time;
                   4033:        my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620     albertel 4034:        return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
                   4035:                             $env{'course.'.$cid.'.num'}.
1.110     www      4036: 	        	    ':nohist_expirationdates:'.
                   4037:                             &escape($key).'='.$now,
1.620     albertel 4038:                             $env{'course.'.$cid.'.home'})
1.110     www      4039:     }
                   4040:     return 'ok';
1.14      www      4041: }
                   4042: 
1.109     www      4043: # ----------------------------------------------------- Devalidate Spreadsheets
                   4044: 
                   4045: sub devalidate {
1.325     www      4046:     my ($symb,$uname,$udom)=@_;
1.620     albertel 4047:     my $cid=$env{'request.course.id'}; 
1.109     www      4048:     if ($cid) {
1.391     matthew  4049:         # delete the stored spreadsheets for
                   4050:         # - the student level sheet of this user in course's homespace
                   4051:         # - the assessment level sheet for this resource 
                   4052:         #   for this user in user's homespace
1.553     albertel 4053: 	# - current conditional state info
1.325     www      4054: 	my $key=$uname.':'.$udom.':';
1.109     www      4055:         my $status=
1.299     matthew  4056: 	    &del('nohist_calculatedsheets',
1.391     matthew  4057: 		 [$key.'studentcalc:'],
1.620     albertel 4058: 		 $env{'course.'.$cid.'.domain'},
                   4059: 		 $env{'course.'.$cid.'.num'})
1.133     albertel 4060: 		.' '.
                   4061: 	    &del('nohist_calculatedsheets_'.$cid,
1.391     matthew  4062: 		 [$key.'assesscalc:'.$symb],$udom,$uname);
1.109     www      4063:         unless ($status eq 'ok ok') {
                   4064:            &logthis('Could not devalidate spreadsheet '.
1.325     www      4065:                     $uname.' at '.$udom.' for '.
1.109     www      4066: 		    $symb.': '.$status);
1.133     albertel 4067:         }
1.553     albertel 4068: 	&delenv('user.state.'.$cid);
1.109     www      4069:     }
                   4070: }
                   4071: 
1.265     albertel 4072: sub get_scalar {
                   4073:     my ($string,$end) = @_;
                   4074:     my $value;
                   4075:     if ($$string =~ s/^([^&]*?)($end)/$2/) {
                   4076: 	$value = $1;
                   4077:     } elsif ($$string =~ s/^([^&]*?)&//) {
                   4078: 	$value = $1;
                   4079:     }
                   4080:     return &unescape($value);
                   4081: }
                   4082: 
                   4083: sub array2str {
                   4084:   my (@array) = @_;
                   4085:   my $result=&arrayref2str(\@array);
                   4086:   $result=~s/^__ARRAY_REF__//;
                   4087:   $result=~s/__END_ARRAY_REF__$//;
                   4088:   return $result;
                   4089: }
                   4090: 
1.204     albertel 4091: sub arrayref2str {
                   4092:   my ($arrayref) = @_;
1.265     albertel 4093:   my $result='__ARRAY_REF__';
1.204     albertel 4094:   foreach my $elem (@$arrayref) {
1.265     albertel 4095:     if(ref($elem) eq 'ARRAY') {
                   4096:       $result.=&arrayref2str($elem).'&';
                   4097:     } elsif(ref($elem) eq 'HASH') {
                   4098:       $result.=&hashref2str($elem).'&';
                   4099:     } elsif(ref($elem)) {
                   4100:       #print("Got a ref of ".(ref($elem))." skipping.");
1.204     albertel 4101:     } else {
                   4102:       $result.=&escape($elem).'&';
                   4103:     }
                   4104:   }
                   4105:   $result=~s/\&$//;
1.265     albertel 4106:   $result .= '__END_ARRAY_REF__';
1.204     albertel 4107:   return $result;
                   4108: }
                   4109: 
1.168     albertel 4110: sub hash2str {
1.204     albertel 4111:   my (%hash) = @_;
                   4112:   my $result=&hashref2str(\%hash);
1.265     albertel 4113:   $result=~s/^__HASH_REF__//;
                   4114:   $result=~s/__END_HASH_REF__$//;
1.204     albertel 4115:   return $result;
                   4116: }
                   4117: 
                   4118: sub hashref2str {
                   4119:   my ($hashref)=@_;
1.265     albertel 4120:   my $result='__HASH_REF__';
1.800     albertel 4121:   foreach my $key (sort(keys(%$hashref))) {
                   4122:     if (ref($key) eq 'ARRAY') {
                   4123:       $result.=&arrayref2str($key).'=';
                   4124:     } elsif (ref($key) eq 'HASH') {
                   4125:       $result.=&hashref2str($key).'=';
                   4126:     } elsif (ref($key)) {
1.265     albertel 4127:       $result.='=';
1.800     albertel 4128:       #print("Got a ref of ".(ref($key))." skipping.");
1.204     albertel 4129:     } else {
1.1132    raeburn  4130: 	if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204     albertel 4131:     }
                   4132: 
1.800     albertel 4133:     if(ref($hashref->{$key}) eq 'ARRAY') {
                   4134:       $result.=&arrayref2str($hashref->{$key}).'&';
                   4135:     } elsif(ref($hashref->{$key}) eq 'HASH') {
                   4136:       $result.=&hashref2str($hashref->{$key}).'&';
                   4137:     } elsif(ref($hashref->{$key})) {
1.265     albertel 4138:        $result.='&';
1.800     albertel 4139:       #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204     albertel 4140:     } else {
1.800     albertel 4141:       $result.=&escape($hashref->{$key}).'&';
1.204     albertel 4142:     }
                   4143:   }
1.168     albertel 4144:   $result=~s/\&$//;
1.265     albertel 4145:   $result .= '__END_HASH_REF__';
1.168     albertel 4146:   return $result;
                   4147: }
                   4148: 
                   4149: sub str2hash {
1.265     albertel 4150:     my ($string)=@_;
                   4151:     my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
                   4152:     return %$hash;
                   4153: }
                   4154: 
                   4155: sub str2hashref {
1.168     albertel 4156:   my ($string) = @_;
1.265     albertel 4157: 
                   4158:   my %hash;
                   4159: 
                   4160:   if($string !~ /^__HASH_REF__/) {
                   4161:       if (! ($string eq '' || !defined($string))) {
                   4162: 	  $hash{'error'}='Not hash reference';
                   4163:       }
                   4164:       return (\%hash, $string);
                   4165:   }
                   4166: 
                   4167:   $string =~ s/^__HASH_REF__//;
                   4168: 
                   4169:   while($string !~ /^__END_HASH_REF__/) {
                   4170:       #key
                   4171:       my $key='';
                   4172:       if($string =~ /^__HASH_REF__/) {
                   4173:           ($key, $string)=&str2hashref($string);
                   4174:           if(defined($key->{'error'})) {
                   4175:               $hash{'error'}='Bad data';
                   4176:               return (\%hash, $string);
                   4177:           }
                   4178:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4179:           ($key, $string)=&str2arrayref($string);
                   4180:           if($key->[0] eq 'Array reference error') {
                   4181:               $hash{'error'}='Bad data';
                   4182:               return (\%hash, $string);
                   4183:           }
                   4184:       } else {
                   4185:           $string =~ s/^(.*?)=//;
1.267     albertel 4186: 	  $key=&unescape($1);
1.265     albertel 4187:       }
                   4188:       $string =~ s/^=//;
                   4189: 
                   4190:       #value
                   4191:       my $value='';
                   4192:       if($string =~ /^__HASH_REF__/) {
                   4193:           ($value, $string)=&str2hashref($string);
                   4194:           if(defined($value->{'error'})) {
                   4195:               $hash{'error'}='Bad data';
                   4196:               return (\%hash, $string);
                   4197:           }
                   4198:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4199:           ($value, $string)=&str2arrayref($string);
                   4200:           if($value->[0] eq 'Array reference error') {
                   4201:               $hash{'error'}='Bad data';
                   4202:               return (\%hash, $string);
                   4203:           }
                   4204:       } else {
                   4205: 	  $value=&get_scalar(\$string,'__END_HASH_REF__');
                   4206:       }
                   4207:       $string =~ s/^&//;
                   4208: 
                   4209:       $hash{$key}=$value;
1.204     albertel 4210:   }
1.265     albertel 4211: 
                   4212:   $string =~ s/^__END_HASH_REF__//;
                   4213: 
                   4214:   return (\%hash, $string);
1.204     albertel 4215: }
                   4216: 
                   4217: sub str2array {
1.265     albertel 4218:     my ($string)=@_;
                   4219:     my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
                   4220:     return @$array;
                   4221: }
                   4222: 
                   4223: sub str2arrayref {
1.204     albertel 4224:   my ($string) = @_;
1.265     albertel 4225:   my @array;
                   4226: 
                   4227:   if($string !~ /^__ARRAY_REF__/) {
                   4228:       if (! ($string eq '' || !defined($string))) {
                   4229: 	  $array[0]='Array reference error';
                   4230:       }
                   4231:       return (\@array, $string);
                   4232:   }
                   4233: 
                   4234:   $string =~ s/^__ARRAY_REF__//;
                   4235: 
                   4236:   while($string !~ /^__END_ARRAY_REF__/) {
                   4237:       my $value='';
                   4238:       if($string =~ /^__HASH_REF__/) {
                   4239:           ($value, $string)=&str2hashref($string);
                   4240:           if(defined($value->{'error'})) {
                   4241:               $array[0] ='Array reference error';
                   4242:               return (\@array, $string);
                   4243:           }
                   4244:       } elsif($string =~ /^__ARRAY_REF__/) {
                   4245:           ($value, $string)=&str2arrayref($string);
                   4246:           if($value->[0] eq 'Array reference error') {
                   4247:               $array[0] ='Array reference error';
                   4248:               return (\@array, $string);
                   4249:           }
                   4250:       } else {
                   4251: 	  $value=&get_scalar(\$string,'__END_ARRAY_REF__');
                   4252:       }
                   4253:       $string =~ s/^&//;
                   4254: 
                   4255:       push(@array, $value);
1.191     harris41 4256:   }
1.265     albertel 4257: 
                   4258:   $string =~ s/^__END_ARRAY_REF__//;
                   4259: 
                   4260:   return (\@array, $string);
1.168     albertel 4261: }
                   4262: 
1.167     albertel 4263: # -------------------------------------------------------------------Temp Store
                   4264: 
1.168     albertel 4265: sub tmpreset {
                   4266:   my ($symb,$namespace,$domain,$stuname) = @_;
                   4267:   if (!$symb) {
                   4268:     $symb=&symbread();
1.620     albertel 4269:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4270:   }
                   4271:   $symb=escape($symb);
                   4272: 
1.620     albertel 4273:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.168     albertel 4274:   $namespace=~s/\//\_/g;
                   4275:   $namespace=~s/\W//g;
                   4276: 
1.620     albertel 4277:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4278:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4279:   if ($domain eq 'public' && $stuname eq 'public') {
                   4280:       $stuname=$ENV{'REMOTE_ADDR'};
                   4281:   }
1.1117    foxr     4282:   my $path=LONCAPA::tempdir();
1.168     albertel 4283:   my %hash;
                   4284:   if (tie(%hash,'GDBM_File',
                   4285: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4286: 	  &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  4287:     foreach my $key (keys(%hash)) {
1.180     albertel 4288:       if ($key=~ /:$symb/) {
1.168     albertel 4289: 	delete($hash{$key});
                   4290:       }
                   4291:     }
                   4292:   }
                   4293: }
                   4294: 
1.167     albertel 4295: sub tmpstore {
1.168     albertel 4296:   my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4297: 
                   4298:   if (!$symb) {
                   4299:     $symb=&symbread();
1.620     albertel 4300:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4301:   }
                   4302:   $symb=escape($symb);
                   4303: 
                   4304:   if (!$namespace) {
                   4305:     # I don't think we would ever want to store this for a course.
                   4306:     # it seems this will only be used if we don't have a course.
1.620     albertel 4307:     #$namespace=$env{'request.course.id'};
1.168     albertel 4308:     #if (!$namespace) {
1.620     albertel 4309:       $namespace=$env{'request.state'};
1.168     albertel 4310:     #}
                   4311:   }
                   4312:   $namespace=~s/\//\_/g;
                   4313:   $namespace=~s/\W//g;
1.620     albertel 4314:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4315:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4316:   if ($domain eq 'public' && $stuname eq 'public') {
                   4317:       $stuname=$ENV{'REMOTE_ADDR'};
                   4318:   }
1.168     albertel 4319:   my $now=time;
                   4320:   my %hash;
1.1117    foxr     4321:   my $path=LONCAPA::tempdir();
1.168     albertel 4322:   if (tie(%hash,'GDBM_File',
                   4323: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4324: 	  &GDBM_WRCREAT(),0640)) {
1.168     albertel 4325:     $hash{"version:$symb"}++;
                   4326:     my $version=$hash{"version:$symb"};
                   4327:     my $allkeys=''; 
                   4328:     foreach my $key (keys(%$storehash)) {
                   4329:       $allkeys.=$key.':';
1.591     albertel 4330:       $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168     albertel 4331:     }
                   4332:     $hash{"$version:$symb:timestamp"}=$now;
                   4333:     $allkeys.='timestamp';
                   4334:     $hash{"$version:keys:$symb"}=$allkeys;
                   4335:     if (untie(%hash)) {
                   4336:       return 'ok';
                   4337:     } else {
                   4338:       return "error:$!";
                   4339:     }
                   4340:   } else {
                   4341:     return "error:$!";
                   4342:   }
                   4343: }
1.167     albertel 4344: 
1.168     albertel 4345: # -----------------------------------------------------------------Temp Restore
1.167     albertel 4346: 
1.168     albertel 4347: sub tmprestore {
                   4348:   my ($symb,$namespace,$domain,$stuname) = @_;
1.167     albertel 4349: 
1.168     albertel 4350:   if (!$symb) {
                   4351:     $symb=&symbread();
1.620     albertel 4352:     if (!$symb) { $symb= $env{'request.url'}; }
1.168     albertel 4353:   }
                   4354:   $symb=escape($symb);
                   4355: 
1.620     albertel 4356:   if (!$namespace) { $namespace=$env{'request.state'}; }
1.591     albertel 4357: 
1.620     albertel 4358:   if (!$domain) { $domain=$env{'user.domain'}; }
                   4359:   if (!$stuname) { $stuname=$env{'user.name'}; }
1.591     albertel 4360:   if ($domain eq 'public' && $stuname eq 'public') {
                   4361:       $stuname=$ENV{'REMOTE_ADDR'};
                   4362:   }
1.168     albertel 4363:   my %returnhash;
                   4364:   $namespace=~s/\//\_/g;
                   4365:   $namespace=~s/\W//g;
                   4366:   my %hash;
1.1117    foxr     4367:   my $path=LONCAPA::tempdir();
1.168     albertel 4368:   if (tie(%hash,'GDBM_File',
                   4369: 	  $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256     albertel 4370: 	  &GDBM_READER(),0640)) {
1.168     albertel 4371:     my $version=$hash{"version:$symb"};
                   4372:     $returnhash{'version'}=$version;
                   4373:     my $scope;
                   4374:     for ($scope=1;$scope<=$version;$scope++) {
                   4375:       my $vkeys=$hash{"$scope:keys:$symb"};
                   4376:       my @keys=split(/:/,$vkeys);
                   4377:       my $key;
                   4378:       $returnhash{"$scope:keys"}=$vkeys;
                   4379:       foreach $key (@keys) {
1.591     albertel 4380: 	$returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
                   4381: 	$returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167     albertel 4382:       }
                   4383:     }
1.168     albertel 4384:     if (!(untie(%hash))) {
                   4385:       return "error:$!";
                   4386:     }
                   4387:   } else {
                   4388:     return "error:$!";
                   4389:   }
                   4390:   return %returnhash;
1.167     albertel 4391: }
                   4392: 
1.9       www      4393: # ----------------------------------------------------------------------- Store
                   4394: 
                   4395: sub store {
1.124     www      4396:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4397:     my $home='';
                   4398: 
1.168     albertel 4399:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4400: 
1.213     www      4401:     $symb=&symbclean($symb);
1.122     albertel 4402:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4403: 
1.620     albertel 4404:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4405:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4406: 
                   4407:     &devalidate($symb,$stuname,$domain);
1.109     www      4408: 
                   4409:     $symb=escape($symb);
1.187     www      4410:     if (!$namespace) { 
1.620     albertel 4411:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4412:           return ''; 
                   4413:        } 
                   4414:     }
1.620     albertel 4415:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4416: 
                   4417:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4418:     $$storehash{'host'}=$perlvar{'lonHostID'};
                   4419: 
1.12      www      4420:     my $namevalue='';
1.800     albertel 4421:     foreach my $key (keys(%$storehash)) {
                   4422:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4423:     }
1.12      www      4424:     $namevalue=~s/\&$//;
1.187     www      4425:     &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124     www      4426:     return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9       www      4427: }
                   4428: 
1.47      www      4429: # -------------------------------------------------------------- Critical Store
                   4430: 
                   4431: sub cstore {
1.124     www      4432:     my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
                   4433:     my $home='';
                   4434: 
1.168     albertel 4435:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4436: 
1.213     www      4437:     $symb=&symbclean($symb);
1.122     albertel 4438:     if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109     www      4439: 
1.620     albertel 4440:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4441:     if (!$stuname) { $stuname=$env{'user.name'}; }
1.325     www      4442: 
                   4443:     &devalidate($symb,$stuname,$domain);
1.109     www      4444: 
                   4445:     $symb=escape($symb);
1.187     www      4446:     if (!$namespace) { 
1.620     albertel 4447:        unless ($namespace=$env{'request.course.id'}) { 
1.187     www      4448:           return ''; 
                   4449:        } 
                   4450:     }
1.620     albertel 4451:     if (!$home) { $home=$env{'user.home'}; }
1.447     www      4452: 
                   4453:     $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
                   4454:     $$storehash{'host'}=$perlvar{'lonHostID'};
1.122     albertel 4455: 
1.47      www      4456:     my $namevalue='';
1.800     albertel 4457:     foreach my $key (keys(%$storehash)) {
                   4458:         $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191     harris41 4459:     }
1.47      www      4460:     $namevalue=~s/\&$//;
1.187     www      4461:     &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188     www      4462:     return critical
                   4463:                 ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47      www      4464: }
                   4465: 
1.9       www      4466: # --------------------------------------------------------------------- Restore
                   4467: 
                   4468: sub restore {
1.124     www      4469:     my ($symb,$namespace,$domain,$stuname) = @_;
                   4470:     my $home='';
                   4471: 
1.168     albertel 4472:     if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124     www      4473: 
1.122     albertel 4474:     if (!$symb) {
                   4475:       unless ($symb=escape(&symbread())) { return ''; }
                   4476:     } else {
1.213     www      4477:       $symb=&escape(&symbclean($symb));
1.122     albertel 4478:     }
1.188     www      4479:     if (!$namespace) { 
1.620     albertel 4480:        unless ($namespace=$env{'request.course.id'}) { 
1.188     www      4481:           return ''; 
                   4482:        } 
                   4483:     }
1.620     albertel 4484:     if (!$domain) { $domain=$env{'user.domain'}; }
                   4485:     if (!$stuname) { $stuname=$env{'user.name'}; }
                   4486:     if (!$home) { $home=$env{'user.home'}; }
1.122     albertel 4487:     my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
                   4488: 
1.12      www      4489:     my %returnhash=();
1.800     albertel 4490:     foreach my $line (split(/\&/,$answer)) {
                   4491: 	my ($name,$value)=split(/\=/,$line);
1.591     albertel 4492:         $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191     harris41 4493:     }
1.75      www      4494:     my $version;
                   4495:     for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800     albertel 4496:        foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
                   4497:           $returnhash{$item}=$returnhash{$version.':'.$item};
1.191     harris41 4498:        }
1.75      www      4499:     }
1.13      www      4500:     return %returnhash;
1.34      www      4501: }
                   4502: 
                   4503: # ---------------------------------------------------------- Course Description
1.1118    foxr     4504: #
                   4505: #  
1.34      www      4506: 
                   4507: sub coursedescription {
1.731     albertel 4508:     my ($courseid,$args)=@_;
1.34      www      4509:     $courseid=~s/^\///;
1.49      www      4510:     $courseid=~s/\_/\//g;
1.34      www      4511:     my ($cdomain,$cnum)=split(/\//,$courseid);
1.129     albertel 4512:     my $chome=&homeserver($cnum,$cdomain);
1.302     albertel 4513:     my $normalid=$cdomain.'_'.$cnum;
                   4514:     # need to always cache even if we get errors otherwise we keep 
                   4515:     # trying and trying and trying to get the course description.
                   4516:     my %envhash=();
                   4517:     my %returnhash=();
1.731     albertel 4518:     
                   4519:     my $expiretime=600;
                   4520:     if ($env{'request.course.id'} eq $normalid) {
                   4521: 	$expiretime=120;
                   4522:     }
                   4523: 
                   4524:     my $prefix='course.'.$cdomain.'_'.$cnum.'.';
                   4525:     if (!$args->{'freshen_cache'}
                   4526: 	&& ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
                   4527: 	foreach my $key (keys(%env)) {
                   4528: 	    next if ($key !~ /^\Q$prefix\E(.*)/);
                   4529: 	    my ($setting) = $1;
                   4530: 	    $returnhash{$setting} = $env{$key};
                   4531: 	}
                   4532: 	return %returnhash;
                   4533:     }
                   4534: 
1.1118    foxr     4535:     # get the data again
                   4536: 
1.731     albertel 4537:     if (!$args->{'one_time'}) {
                   4538: 	$envhash{'course.'.$normalid.'.last_cache'}=time;
                   4539:     }
1.811     albertel 4540: 
1.34      www      4541:     if ($chome ne 'no_host') {
1.302     albertel 4542:        %returnhash=&dump('environment',$cdomain,$cnum);
1.129     albertel 4543:        if (!exists($returnhash{'con_lost'})) {
1.1118    foxr     4544: 	   my $username = $env{'user.name'}; # Defult username
                   4545: 	   if(defined $args->{'user'}) {
                   4546: 	       $username = $args->{'user'};
                   4547: 	   }
1.129     albertel 4548:            $returnhash{'home'}= $chome;
                   4549: 	   $returnhash{'domain'} = $cdomain;
                   4550: 	   $returnhash{'num'} = $cnum;
1.741     raeburn  4551:            if (!defined($returnhash{'type'})) {
                   4552:                $returnhash{'type'} = 'Course';
                   4553:            }
1.130     albertel 4554:            while (my ($name,$value) = each %returnhash) {
1.53      www      4555:                $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129     albertel 4556:            }
1.270     www      4557:            $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117    foxr     4558:            $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118    foxr     4559: 	       $username.'_'.$cdomain.'_'.$cnum;
1.60      www      4560:            $envhash{'course.'.$normalid.'.home'}=$chome;
                   4561:            $envhash{'course.'.$normalid.'.domain'}=$cdomain;
                   4562:            $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34      www      4563:        }
                   4564:     }
1.731     albertel 4565:     if (!$args->{'one_time'}) {
1.949     raeburn  4566: 	&appenv(\%envhash);
1.731     albertel 4567:     }
1.302     albertel 4568:     return %returnhash;
1.461     www      4569: }
                   4570: 
1.1080    raeburn  4571: sub update_released_required {
                   4572:     my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
                   4573:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   4574:         $cid = $env{'request.course.id'};
                   4575:         $cdom = $env{'course.'.$cid.'.domain'};
                   4576:         $cnum = $env{'course.'.$cid.'.num'};
                   4577:         $chome = $env{'course.'.$cid.'.home'};
                   4578:     }
                   4579:     if ($needsrelease) {
                   4580:         my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
                   4581:         my $needsupdate;
                   4582:         if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
                   4583:             $needsupdate = 1;
                   4584:         } else {
                   4585:             my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   4586:             my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
                   4587:             if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
                   4588:                 $needsupdate = 1;
                   4589:             }
                   4590:         }
                   4591:         if ($needsupdate) {
                   4592:             my %needshash = (
                   4593:                              'internal.releaserequired' => $needsrelease,
                   4594:                             );
                   4595:             my $putresult = &put('environment',\%needshash,$cdom,$cnum);
                   4596:             if ($putresult eq 'ok') {
                   4597:                 &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
                   4598:                 my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   4599:                 if (ref($crsinfo{$cid}) eq 'HASH') {
                   4600:                     $crsinfo{$cid}{'releaserequired'} = $needsrelease;
                   4601:                     &courseidput($cdom,\%crsinfo,$chome,'notime');
                   4602:                 }
                   4603:             }
                   4604:         }
                   4605:     }
                   4606:     return;
                   4607: }
                   4608: 
1.461     www      4609: # -------------------------------------------------See if a user is privileged
                   4610: 
                   4611: sub privileged {
                   4612:     my ($username,$domain)=@_;
1.1170    droeschl 4613: 
                   4614:     my %rolesdump = &dump("roles", $domain, $username) or return 0;
                   4615:     my $now = time;
                   4616: 
                   4617:     for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
                   4618:             my ($trole, $tend, $tstart) = split(/_/, $role);
                   4619:             if (($trole eq 'dc') || ($trole eq 'su')) {
                   4620:                 return 1 unless ($tend && $tend < $now) 
                   4621:                     or ($tstart && $tstart > $now);
                   4622:             }
1.461     www      4623: 	}
1.1170    droeschl 4624: 
1.461     www      4625:     return 0;
1.9       www      4626: }
1.1       albertel 4627: 
1.103     harris41 4628: # -------------------------------------------------------- Get user privileges
1.11      www      4629: 
                   4630: sub rolesinit {
1.1169    droeschl 4631:     my ($domain, $username) = @_;
                   4632:     my %userroles = ('user.login.time' => time);
                   4633:     my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
                   4634: 
                   4635:     # firstaccess and timerinterval are related to timed maps/resources. 
                   4636:     # also, blocking can be triggered by an activating timer
                   4637:     # it's saved in the user's %env.
                   4638:     my %firstaccess = &dump('firstaccesstimes', $domain, $username);
                   4639:     my %timerinterval = &dump('timerinterval', $domain, $username);
                   4640:     my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
                   4641:         %timerintchk, %timerintenv);
                   4642: 
1.1162    raeburn  4643:     foreach my $key (keys(%firstaccess)) {
1.1169    droeschl 4644:         my ($cid, $rest) = split(/\0/, $key);
1.1162    raeburn  4645:         $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
                   4646:     }
1.1169    droeschl 4647: 
1.1162    raeburn  4648:     foreach my $key (keys(%timerinterval)) {
                   4649:         my ($cid,$rest) = split(/\0/,$key);
                   4650:         $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
                   4651:     }
1.1169    droeschl 4652: 
1.11      www      4653:     my %allroles=();
1.1162    raeburn  4654:     my %allgroups=();
1.11      www      4655: 
1.1169    droeschl 4656:     for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
                   4657:         my $role = $rolesdump{$area};
                   4658:         $area =~ s/\_\w\w$//;
                   4659: 
                   4660:         my ($trole, $tend, $tstart, $group_privs);
                   4661: 
                   4662:         if ($role =~ /^cr/) {
                   4663:         # Custom role, defined by a user 
                   4664:         # e.g., user.role.cr/msu/smith/mynewrole
                   4665:             if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
                   4666:                 $trole = $1;
                   4667:                 ($tend, $tstart) = split('_', $2);
                   4668:             } else {
                   4669:                 $trole = $role;
                   4670:             }
                   4671:         } elsif ($role =~ m|^gr/|) {
                   4672:         # Role of member in a group, defined within a course/community
                   4673:         # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
                   4674:             ($trole, $tend, $tstart) = split(/_/, $role);
                   4675:             next if $tstart eq '-1';
                   4676:             ($trole, $group_privs) = split(/\//, $trole);
                   4677:             $group_privs = &unescape($group_privs);
                   4678:         } else {
                   4679:         # Just a normal role, defined in roles.tab
                   4680:             ($trole, $tend, $tstart) = split(/_/,$role);
                   4681:         }
                   4682: 
                   4683:         my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
                   4684:                  $username);
                   4685:         @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
                   4686: 
                   4687:         # role expired or not available yet?
                   4688:         $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or 
                   4689:             ($tstart != 0 && $tstart > $userroles{'user.login.time'});
                   4690: 
                   4691:         next if $area eq '' or $trole eq '';
                   4692: 
                   4693:         my $spec = "$trole.$area";
                   4694:         my ($tdummy, $tdomain, $trest) = split(/\//, $area);
                   4695: 
                   4696:         if ($trole =~ /^cr\//) {
                   4697:         # Custom role, defined by a user
                   4698:             &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   4699:         } elsif ($trole eq 'gr') {
                   4700:         # Role of a member in a group, defined within a course/community
                   4701:             &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
                   4702:             next;
                   4703:         } else {
                   4704:         # Normal role, defined in roles.tab
                   4705:             &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   4706:         }
                   4707: 
                   4708:         my $cid = $tdomain.'_'.$trest;
                   4709:         unless ($firstaccchk{$cid}) {
                   4710:             if (ref($coursetimerstarts{$cid}) eq 'HASH') {
                   4711:                 foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
                   4712:                     $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} = 
                   4713:                         $coursetimerstarts{$cid}{$item}; 
                   4714:                 }
                   4715:             }
                   4716:             $firstaccchk{$cid} = 1;
                   4717:         }
                   4718:         unless ($timerintchk{$cid}) {
                   4719:             if (ref($coursetimerintervals{$cid}) eq 'HASH') {
                   4720:                 foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
                   4721:                     $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
                   4722:                        $coursetimerintervals{$cid}{$item};
1.1162    raeburn  4723:                 }
1.12      www      4724:             }
1.1169    droeschl 4725:             $timerintchk{$cid} = 1;
1.191     harris41 4726:         }
1.11      www      4727:     }
1.1169    droeschl 4728: 
                   4729:     @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
                   4730:         \%allroles, \%allgroups);
                   4731:     $env{'user.adv'} = $userroles{'user.adv'};
                   4732: 
1.1162    raeburn  4733:     return (\%userroles,\%firstaccenv,\%timerintenv);
1.11      www      4734: }
                   4735: 
1.567     raeburn  4736: sub set_arearole {
                   4737:     my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
                   4738: # log the associated role with the area
                   4739:     &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743     albertel 4740:     return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567     raeburn  4741: }
                   4742: 
                   4743: sub custom_roleprivs {
                   4744:     my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
                   4745:     my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
                   4746:     my $homsvr=homeserver($rauthor,$rdomain);
1.838     albertel 4747:     if (&hostname($homsvr) ne '') {
1.567     raeburn  4748:         my ($rdummy,$roledef)=
                   4749:             &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
                   4750:         if (($rdummy ne 'con_lost') && ($roledef ne '')) {
                   4751:             my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
                   4752:             if (defined($syspriv)) {
1.1043    raeburn  4753:                 if ($trest =~ /^$match_community$/) {
                   4754:                     $syspriv =~ s/bre\&S//; 
                   4755:                 }
1.567     raeburn  4756:                 $$allroles{'cm./'}.=':'.$syspriv;
                   4757:                 $$allroles{$spec.'./'}.=':'.$syspriv;
                   4758:             }
                   4759:             if ($tdomain ne '') {
                   4760:                 if (defined($dompriv)) {
                   4761:                     $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
                   4762:                     $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
                   4763:                 }
                   4764:                 if (($trest ne '') && (defined($coursepriv))) {
                   4765:                     $$allroles{'cm.'.$area}.=':'.$coursepriv;
                   4766:                     $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
                   4767:                 }
                   4768:             }
                   4769:         }
                   4770:     }
                   4771: }
                   4772: 
1.678     raeburn  4773: sub group_roleprivs {
                   4774:     my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
                   4775:     my $access = 1;
                   4776:     my $now = time;
                   4777:     if (($tend!=0) && ($tend<$now)) { $access = 0; }
                   4778:     if (($tstart!=0) && ($tstart>$now)) { $access=0; }
                   4779:     if ($access) {
1.811     albertel 4780:         my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678     raeburn  4781:         $$allgroups{$course}{$group} .=':'.$group_privs;
                   4782:     }
                   4783: }
1.567     raeburn  4784: 
                   4785: sub standard_roleprivs {
                   4786:     my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
                   4787:     if (defined($pr{$trole.':s'})) {
                   4788:         $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
                   4789:         $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
                   4790:     }
                   4791:     if ($tdomain ne '') {
                   4792:         if (defined($pr{$trole.':d'})) {
                   4793:             $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4794:             $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
                   4795:         }
                   4796:         if (($trest ne '') && (defined($pr{$trole.':c'}))) {
                   4797:             $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
                   4798:             $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
                   4799:         }
                   4800:     }
                   4801: }
                   4802: 
                   4803: sub set_userprivs {
1.1064    raeburn  4804:     my ($userroles,$allroles,$allgroups,$groups_roles) = @_; 
1.567     raeburn  4805:     my $author=0;
                   4806:     my $adv=0;
1.678     raeburn  4807:     my %grouproles = ();
                   4808:     if (keys(%{$allgroups}) > 0) {
1.1064    raeburn  4809:         my @groupkeys; 
1.1000    raeburn  4810:         foreach my $role (keys(%{$allroles})) {
1.1064    raeburn  4811:             push(@groupkeys,$role);
                   4812:         }
                   4813:         if (ref($groups_roles) eq 'HASH') {
                   4814:             foreach my $key (keys(%{$groups_roles})) {
                   4815:                 unless (grep(/^\Q$key\E$/,@groupkeys)) {
                   4816:                     push(@groupkeys,$key);
                   4817:                 }
                   4818:             }
                   4819:         }
                   4820:         if (@groupkeys > 0) {
                   4821:             foreach my $role (@groupkeys) {
                   4822:                 my ($trole,$area,$sec,$extendedarea);
                   4823:                 if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
                   4824:                     $trole = $1;
                   4825:                     $area = $2;
                   4826:                     $sec = $3;
                   4827:                     $extendedarea = $area.$sec;
                   4828:                     if (exists($$allgroups{$area})) {
                   4829:                         foreach my $group (keys(%{$$allgroups{$area}})) {
                   4830:                             my $spec = $trole.'.'.$extendedarea;
                   4831:                             $grouproles{$spec.'.'.$area.'/'.$group} = 
1.681     raeburn  4832:                                                 $$allgroups{$area}{$group};
1.1064    raeburn  4833:                         }
1.678     raeburn  4834:                     }
                   4835:                 }
                   4836:             }
                   4837:         }
                   4838:     }
1.800     albertel 4839:     foreach my $group (keys(%grouproles)) {
                   4840:         $$allroles{$group} = $grouproles{$group};
1.678     raeburn  4841:     }
1.800     albertel 4842:     foreach my $role (keys(%{$allroles})) {
                   4843:         my %thesepriv;
1.941     raeburn  4844:         if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800     albertel 4845:         foreach my $item (split(/:/,$$allroles{$role})) {
                   4846:             if ($item ne '') {
                   4847:                 my ($privilege,$restrictions)=split(/&/,$item);
1.567     raeburn  4848:                 if ($restrictions eq '') {
                   4849:                     $thesepriv{$privilege}='F';
                   4850:                 } elsif ($thesepriv{$privilege} ne 'F') {
                   4851:                     $thesepriv{$privilege}.=$restrictions;
                   4852:                 }
                   4853:                 if ($thesepriv{'adv'} eq 'F') { $adv=1; }
                   4854:             }
                   4855:         }
                   4856:         my $thesestr='';
1.1104    raeburn  4857:         foreach my $priv (sort(keys(%thesepriv))) {
1.800     albertel 4858: 	    $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
                   4859: 	}
                   4860:         $userroles->{'user.priv.'.$role} = $thesestr;
1.567     raeburn  4861:     }
                   4862:     return ($author,$adv);
                   4863: }
                   4864: 
1.994     raeburn  4865: sub role_status {
1.1104    raeburn  4866:     my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994     raeburn  4867:     my @pwhere = ();
                   4868:     if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
                   4869:         (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
                   4870:         unless (!defined($$role) || $$role eq '') {
                   4871:             $$where=join('.',@pwhere);
                   4872:             $$trolecode=$$role.'.'.$$where;
                   4873:             ($$tstart,$$tend)=split(/\./,$env{$rolekey});
                   4874:             $$tstatus='is';
1.1104    raeburn  4875:             if ($$tstart && $$tstart>$update) {
1.994     raeburn  4876:                 $$tstatus='future';
1.1034    raeburn  4877:                 if ($$tstart<$now) {
                   4878:                     if ($$tstart && $$tstart>$refresh) {
1.1002    raeburn  4879:                         if (($$where ne '') && ($$role ne '')) {
1.1064    raeburn  4880:                             my (%allroles,%allgroups,$group_privs,
                   4881:                                 %groups_roles,@rolecodes);
1.1002    raeburn  4882:                             my %userroles = (
                   4883:                                 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
                   4884:                             );
1.1064    raeburn  4885:                             @rolecodes = ('cm'); 
1.1002    raeburn  4886:                             my $spec=$$role.'.'.$$where;
                   4887:                             my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
                   4888:                             if ($$role =~ /^cr\//) {
                   4889:                                 &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064    raeburn  4890:                                 push(@rolecodes,'cr');
1.1002    raeburn  4891:                             } elsif ($$role eq 'gr') {
1.1064    raeburn  4892:                                 push(@rolecodes,$$role);
1.1002    raeburn  4893:                                 my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
                   4894:                                                     $env{'user.name'});
1.1064    raeburn  4895:                                 my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002    raeburn  4896:                                 (undef,my $group_privs) = split(/\//,$trole);
                   4897:                                 $group_privs = &unescape($group_privs);
                   4898:                                 &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064    raeburn  4899:                                 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  4900:                                 &get_groups_roles($tdomain,$trest,
                   4901:                                                   \%course_roles,\@rolecodes,
                   4902:                                                   \%groups_roles);
1.1002    raeburn  4903:                             } else {
1.1064    raeburn  4904:                                 push(@rolecodes,$$role);
1.1002    raeburn  4905:                                 &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
                   4906:                             }
1.1064    raeburn  4907:                             my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
                   4908:                             &appenv(\%userroles,\@rolecodes);
1.1002    raeburn  4909:                             &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
                   4910:                         }
                   4911:                     }
1.1034    raeburn  4912:                     $$tstatus = 'is';
1.1002    raeburn  4913:                 }
1.994     raeburn  4914:             }
                   4915:             if ($$tend) {
1.1104    raeburn  4916:                 if ($$tend<$update) {
1.994     raeburn  4917:                     $$tstatus='expired';
                   4918:                 } elsif ($$tend<$now) {
                   4919:                     $$tstatus='will_not';
                   4920:                 }
                   4921:             }
                   4922:         }
                   4923:     }
                   4924: }
                   4925: 
1.1104    raeburn  4926: sub get_groups_roles {
                   4927:     my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
                   4928:     return unless((ref($cdom_courseroles) eq 'HASH') && 
                   4929:                   (ref($rolecodes) eq 'ARRAY') && 
                   4930:                   (ref($groups_roles) eq 'HASH')); 
                   4931:     if (keys(%{$cdom_courseroles}) > 0) {
                   4932:         my ($cnum) = ($rest =~ /^($match_courseid)/);
                   4933:         if ($cdom ne '' && $cnum ne '') {
                   4934:             foreach my $key (keys(%{$cdom_courseroles})) {
                   4935:                 if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
                   4936:                     my $crsrole = $1;
                   4937:                     my $crssec = $2;
                   4938:                     if ($crsrole =~ /^cr/) {
                   4939:                         unless (grep(/^cr$/,@{$rolecodes})) {
                   4940:                             push(@{$rolecodes},'cr');
                   4941:                         }
                   4942:                     } else {
                   4943:                         unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
                   4944:                             push(@{$rolecodes},$crsrole);
                   4945:                         }
                   4946:                     }
                   4947:                     my $rolekey = "$crsrole./$cdom/$cnum";
                   4948:                     if ($crssec ne '') {
                   4949:                         $rolekey .= "/$crssec";
                   4950:                     }
                   4951:                     $rolekey .= './';
                   4952:                     $groups_roles->{$rolekey} = $rolecodes;
                   4953:                 }
                   4954:             }
                   4955:         }
                   4956:     }
                   4957:     return;
                   4958: }
                   4959: 
                   4960: sub delete_env_groupprivs {
                   4961:     my ($where,$courseroles,$possroles) = @_;
                   4962:     return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
                   4963:     my ($dummy,$udom,$uname,$group) = split(/\//,$where);
                   4964:     unless (ref($courseroles->{$udom}) eq 'HASH') {
                   4965:         %{$courseroles->{$udom}} =
                   4966:             &get_my_roles('','','userroles',['active'],
                   4967:                           $possroles,[$udom],1);
                   4968:     }
                   4969:     if (ref($courseroles->{$udom}) eq 'HASH') {
                   4970:         foreach my $item (keys(%{$courseroles->{$udom}})) {
                   4971:             my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
                   4972:             my $area = '/'.$cdom.'/'.$cnum;
                   4973:             my $privkey = "user.priv.$crsrole.$area";
                   4974:             if ($crssec ne '') {
                   4975:                 $privkey .= '/'.$crssec;
                   4976:             }
                   4977:             $privkey .= ".$area/$group";
                   4978:             &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
                   4979:         }
                   4980:     }
                   4981:     return;
                   4982: }
                   4983: 
1.994     raeburn  4984: sub check_adhoc_privs {
1.1104    raeburn  4985:     my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994     raeburn  4986:     my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
                   4987:     if ($env{$cckey}) {
                   4988:         my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104    raeburn  4989:         &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994     raeburn  4990:         unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088    raeburn  4991:             &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4992:         }
                   4993:     } else {
1.1088    raeburn  4994:         &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994     raeburn  4995:     }
                   4996: }
                   4997: 
                   4998: sub set_adhoc_privileges {
                   4999: # role can be cc or ca
1.1088    raeburn  5000:     my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994     raeburn  5001:     my $area = '/'.$dcdom.'/'.$pickedcourse;
                   5002:     my $spec = $role.'.'.$area;
                   5003:     my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
                   5004:                                   $env{'user.name'});
                   5005:     my %ccrole = ();
                   5006:     &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
                   5007:     my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
                   5008:     &appenv(\%userroles,[$role,'cm']);
                   5009:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088    raeburn  5010:     unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
                   5011:         &appenv( {'request.role'        => $spec,
                   5012:                   'request.role.domain' => $dcdom,
                   5013:                   'request.course.sec'  => ''
                   5014:                  }
                   5015:                );
                   5016:         my $tadv=0;
                   5017:         if (&allowed('adv') eq 'F') { $tadv=1; }
                   5018:         &appenv({'request.role.adv'    => $tadv});
                   5019:     }
1.994     raeburn  5020: }
                   5021: 
1.12      www      5022: # --------------------------------------------------------------- get interface
                   5023: 
                   5024: sub get {
1.131     albertel 5025:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5026:    my $items='';
1.800     albertel 5027:    foreach my $item (@$storearr) {
                   5028:        $items.=&escape($item).'&';
1.191     harris41 5029:    }
1.12      www      5030:    $items=~s/\&$//;
1.620     albertel 5031:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5032:    if (!$uname) { $uname=$env{'user.name'}; }
1.131     albertel 5033:    my $uhome=&homeserver($uname,$udomain);
                   5034: 
1.133     albertel 5035:    my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5036:    my @pairs=split(/\&/,$rep);
1.273     albertel 5037:    if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
                   5038:      return @pairs;
                   5039:    }
1.15      www      5040:    my %returnhash=();
1.42      www      5041:    my $i=0;
1.800     albertel 5042:    foreach my $item (@$storearr) {
                   5043:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5044:       $i++;
1.191     harris41 5045:    }
1.15      www      5046:    return %returnhash;
1.27      www      5047: }
                   5048: 
                   5049: # --------------------------------------------------------------- del interface
                   5050: 
                   5051: sub del {
1.133     albertel 5052:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.27      www      5053:    my $items='';
1.800     albertel 5054:    foreach my $item (@$storearr) {
                   5055:        $items.=&escape($item).'&';
1.191     harris41 5056:    }
1.984     neumanie 5057: 
1.27      www      5058:    $items=~s/\&$//;
1.620     albertel 5059:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5060:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5061:    my $uhome=&homeserver($uname,$udomain);
                   5062:    return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15      www      5063: }
                   5064: 
                   5065: # -------------------------------------------------------------- dump interface
                   5066: 
                   5067: sub dump {
1.1166    raeburn  5068:     my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.755     albertel 5069:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5070:     if (!$uname) { $uname=$env{'user.name'}; }
                   5071:     my $uhome=&homeserver($uname,$udomain);
1.1167    droeschl 5072: 
1.755     albertel 5073:     if ($regexp) {
                   5074: 	$regexp=&escape($regexp);
                   5075:     } else {
                   5076: 	$regexp='.';
                   5077:     }
1.1166    raeburn  5078:     my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755     albertel 5079:     my @pairs=split(/\&/,$rep);
                   5080:     my %returnhash=();
1.1098    foxr     5081:     if (!($rep =~ /^error/ )) {
                   5082: 	foreach my $item (@pairs) {
                   5083: 	    my ($key,$value)=split(/=/,$item,2);
                   5084: 	    $key = &unescape($key);
                   5085: 	    next if ($key =~ /^error: 2 /);
                   5086: 	    $returnhash{$key}=&thaw_unescape($value);
                   5087: 	}
1.755     albertel 5088:     }
                   5089:     return %returnhash;
1.407     www      5090: }
                   5091: 
1.1098    foxr     5092: 
1.717     albertel 5093: # --------------------------------------------------------- dumpstore interface
                   5094: 
                   5095: sub dumpstore {
                   5096:    my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822     albertel 5097:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5098:    if (!$uname) { $uname=$env{'user.name'}; }
                   5099:    my $uhome=&homeserver($uname,$udomain);
                   5100:    if ($regexp) {
                   5101:        $regexp=&escape($regexp);
                   5102:    } else {
                   5103:        $regexp='.';
                   5104:    }
                   5105:    my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
                   5106:    my @pairs=split(/\&/,$rep);
                   5107:    my %returnhash=();
                   5108:    foreach my $item (@pairs) {
                   5109:        my ($key,$value)=split(/=/,$item,2);
                   5110:        next if ($key =~ /^error: 2 /);
                   5111:        $returnhash{$key}=&thaw_unescape($value);
                   5112:    }
                   5113:    return %returnhash;
1.717     albertel 5114: }
                   5115: 
1.407     www      5116: # -------------------------------------------------------------- keys interface
                   5117: 
                   5118: sub getkeys {
                   5119:    my ($namespace,$udomain,$uname)=@_;
1.620     albertel 5120:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5121:    if (!$uname) { $uname=$env{'user.name'}; }
1.407     www      5122:    my $uhome=&homeserver($uname,$udomain);
                   5123:    my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
                   5124:    my @keyarray=();
1.800     albertel 5125:    foreach my $key (split(/\&/,$rep)) {
1.812     raeburn  5126:       next if ($key =~ /^error: 2 /);
1.800     albertel 5127:       push(@keyarray,&unescape($key));
1.407     www      5128:    }
                   5129:    return @keyarray;
1.318     matthew  5130: }
                   5131: 
1.319     matthew  5132: # --------------------------------------------------------------- currentdump
                   5133: sub currentdump {
1.328     matthew  5134:    my ($courseid,$sdom,$sname)=@_;
1.620     albertel 5135:    $courseid = $env{'request.course.id'} if (! defined($courseid));
                   5136:    $sdom     = $env{'user.domain'}       if (! defined($sdom));
                   5137:    $sname    = $env{'user.name'}         if (! defined($sname));
1.326     matthew  5138:    my $uhome = &homeserver($sname,$sdom);
                   5139:    my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318     matthew  5140:    return if ($rep =~ /^(error:|no_such_host)/);
1.319     matthew  5141:    #
1.318     matthew  5142:    my %returnhash=();
1.319     matthew  5143:    #
                   5144:    if ($rep eq "unknown_cmd") { 
                   5145:        # an old lond will not know currentdump
                   5146:        # Do a dump and make it look like a currentdump
1.822     albertel 5147:        my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319     matthew  5148:        return if ($tmp[0] =~ /^(error:|no_such_host)/);
                   5149:        my %hash = @tmp;
                   5150:        @tmp=();
1.424     matthew  5151:        %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319     matthew  5152:    } else {
                   5153:        my @pairs=split(/\&/,$rep);
1.800     albertel 5154:        foreach my $pair (@pairs) {
                   5155:            my ($key,$value)=split(/=/,$pair,2);
1.319     matthew  5156:            my ($symb,$param) = split(/:/,$key);
                   5157:            $returnhash{&unescape($symb)}->{&unescape($param)} = 
1.557     albertel 5158:                                                         &thaw_unescape($value);
1.319     matthew  5159:        }
1.191     harris41 5160:    }
1.12      www      5161:    return %returnhash;
1.424     matthew  5162: }
                   5163: 
                   5164: sub convert_dump_to_currentdump{
                   5165:     my %hash = %{shift()};
                   5166:     my %returnhash;
                   5167:     # Code ripped from lond, essentially.  The only difference
                   5168:     # here is the unescaping done by lonnet::dump().  Conceivably
                   5169:     # we might run in to problems with parameter names =~ /^v\./
                   5170:     while (my ($key,$value) = each(%hash)) {
                   5171:         my ($v,$symb,$param) = split(/:/,$key);
1.822     albertel 5172: 	$symb  = &unescape($symb);
                   5173: 	$param = &unescape($param);
1.424     matthew  5174:         next if ($v eq 'version' || $symb eq 'keys');
                   5175:         next if (exists($returnhash{$symb}) &&
                   5176:                  exists($returnhash{$symb}->{$param}) &&
                   5177:                  $returnhash{$symb}->{'v.'.$param} > $v);
                   5178:         $returnhash{$symb}->{$param}=$value;
                   5179:         $returnhash{$symb}->{'v.'.$param}=$v;
                   5180:     }
                   5181:     #
                   5182:     # Remove all of the keys in the hashes which keep track of
                   5183:     # the version of the parameter.
                   5184:     while (my ($symb,$param_hash) = each(%returnhash)) {
                   5185:         # use a foreach because we are going to delete from the hash.
                   5186:         foreach my $key (keys(%$param_hash)) {
                   5187:             delete($param_hash->{$key}) if ($key =~ /^v\./);
                   5188:         }
                   5189:     }
                   5190:     return \%returnhash;
1.12      www      5191: }
                   5192: 
1.627     albertel 5193: # ------------------------------------------------------ critical inc interface
                   5194: 
                   5195: sub cinc {
                   5196:     return &inc(@_,'critical');
                   5197: }
                   5198: 
1.449     matthew  5199: # --------------------------------------------------------------- inc interface
                   5200: 
                   5201: sub inc {
1.627     albertel 5202:     my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620     albertel 5203:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5204:     if (!$uname) { $uname=$env{'user.name'}; }
1.449     matthew  5205:     my $uhome=&homeserver($uname,$udomain);
                   5206:     my $items='';
                   5207:     if (! ref($store)) {
                   5208:         # got a single value, so use that instead
                   5209:         $items = &escape($store).'=&';
                   5210:     } elsif (ref($store) eq 'SCALAR') {
                   5211:         $items = &escape($$store).'=&';        
                   5212:     } elsif (ref($store) eq 'ARRAY') {
                   5213:         $items = join('=&',map {&escape($_);} @{$store});
                   5214:     } elsif (ref($store) eq 'HASH') {
                   5215:         while (my($key,$value) = each(%{$store})) {
                   5216:             $items.= &escape($key).'='.&escape($value).'&';
                   5217:         }
                   5218:     }
                   5219:     $items=~s/\&$//;
1.627     albertel 5220:     if ($critical) {
                   5221: 	return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5222:     } else {
                   5223: 	return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
                   5224:     }
1.449     matthew  5225: }
                   5226: 
1.12      www      5227: # --------------------------------------------------------------- put interface
                   5228: 
                   5229: sub put {
1.134     albertel 5230:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5231:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5232:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5233:    my $uhome=&homeserver($uname,$udomain);
1.12      www      5234:    my $items='';
1.800     albertel 5235:    foreach my $item (keys(%$storehash)) {
                   5236:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5237:    }
1.12      www      5238:    $items=~s/\&$//;
1.134     albertel 5239:    return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47      www      5240: }
                   5241: 
1.631     albertel 5242: # ------------------------------------------------------------ newput interface
                   5243: 
                   5244: sub newput {
                   5245:    my ($namespace,$storehash,$udomain,$uname)=@_;
                   5246:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5247:    if (!$uname) { $uname=$env{'user.name'}; }
                   5248:    my $uhome=&homeserver($uname,$udomain);
                   5249:    my $items='';
                   5250:    foreach my $key (keys(%$storehash)) {
                   5251:        $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   5252:    }
                   5253:    $items=~s/\&$//;
                   5254:    return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
                   5255: }
                   5256: 
                   5257: # ---------------------------------------------------------  putstore interface
                   5258: 
1.524     raeburn  5259: sub putstore {
1.715     albertel 5260:    my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620     albertel 5261:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5262:    if (!$uname) { $uname=$env{'user.name'}; }
1.524     raeburn  5263:    my $uhome=&homeserver($uname,$udomain);
                   5264:    my $items='';
1.715     albertel 5265:    foreach my $key (keys(%$storehash)) {
                   5266:        $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524     raeburn  5267:    }
1.715     albertel 5268:    $items=~s/\&$//;
1.716     albertel 5269:    my $esc_symb=&escape($symb);
                   5270:    my $esc_v=&escape($version);
1.715     albertel 5271:    my $reply =
1.716     albertel 5272:        &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715     albertel 5273: 	      $uhome);
                   5274:    if ($reply eq 'unknown_cmd') {
1.716     albertel 5275:        # gfall back to way things use to be done
1.715     albertel 5276:        return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
                   5277: 			    $uname);
1.524     raeburn  5278:    }
1.715     albertel 5279:    return $reply;
                   5280: }
                   5281: 
                   5282: sub old_putstore {
1.716     albertel 5283:     my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
                   5284:     if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5285:     if (!$uname) { $uname=$env{'user.name'}; }
                   5286:     my $uhome=&homeserver($uname,$udomain);
                   5287:     my %newstorehash;
1.800     albertel 5288:     foreach my $item (keys(%$storehash)) {
                   5289: 	my $key = $version.':'.&escape($symb).':'.$item;
                   5290: 	$newstorehash{$key} = $storehash->{$item};
1.716     albertel 5291:     }
                   5292:     my $items='';
                   5293:     my %allitems = ();
1.800     albertel 5294:     foreach my $item (keys(%newstorehash)) {
                   5295: 	if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716     albertel 5296: 	    my $key = $1.':keys:'.$2;
                   5297: 	    $allitems{$key} .= $3.':';
                   5298: 	}
1.800     albertel 5299: 	$items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716     albertel 5300:     }
1.800     albertel 5301:     foreach my $item (keys(%allitems)) {
                   5302: 	$allitems{$item} =~ s/\:$//;
                   5303: 	$items.= $item.'='.$allitems{$item}.'&';
1.716     albertel 5304:     }
                   5305:     $items=~s/\&$//;
                   5306:     return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524     raeburn  5307: }
                   5308: 
1.47      www      5309: # ------------------------------------------------------ critical put interface
                   5310: 
                   5311: sub cput {
1.134     albertel 5312:    my ($namespace,$storehash,$udomain,$uname)=@_;
1.620     albertel 5313:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5314:    if (!$uname) { $uname=$env{'user.name'}; }
1.134     albertel 5315:    my $uhome=&homeserver($uname,$udomain);
1.47      www      5316:    my $items='';
1.800     albertel 5317:    foreach my $item (keys(%$storehash)) {
                   5318:        $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191     harris41 5319:    }
1.47      www      5320:    $items=~s/\&$//;
1.134     albertel 5321:    return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5322: }
                   5323: 
                   5324: # -------------------------------------------------------------- eget interface
                   5325: 
                   5326: sub eget {
1.133     albertel 5327:    my ($namespace,$storearr,$udomain,$uname)=@_;
1.12      www      5328:    my $items='';
1.800     albertel 5329:    foreach my $item (@$storearr) {
                   5330:        $items.=&escape($item).'&';
1.191     harris41 5331:    }
1.12      www      5332:    $items=~s/\&$//;
1.620     albertel 5333:    if (!$udomain) { $udomain=$env{'user.domain'}; }
                   5334:    if (!$uname) { $uname=$env{'user.name'}; }
1.133     albertel 5335:    my $uhome=&homeserver($uname,$udomain);
                   5336:    my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12      www      5337:    my @pairs=split(/\&/,$rep);
                   5338:    my %returnhash=();
1.42      www      5339:    my $i=0;
1.800     albertel 5340:    foreach my $item (@$storearr) {
                   5341:       $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42      www      5342:       $i++;
1.191     harris41 5343:    }
1.12      www      5344:    return %returnhash;
                   5345: }
                   5346: 
1.667     albertel 5347: # ------------------------------------------------------------ tmpput interface
                   5348: sub tmpput {
1.802     raeburn  5349:     my ($storehash,$server,$context)=@_;
1.667     albertel 5350:     my $items='';
1.800     albertel 5351:     foreach my $item (keys(%$storehash)) {
                   5352: 	$items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667     albertel 5353:     }
                   5354:     $items=~s/\&$//;
1.802     raeburn  5355:     if (defined($context)) {
                   5356:         $items .= ':'.&escape($context);
                   5357:     }
1.667     albertel 5358:     return &reply("tmpput:$items",$server);
                   5359: }
                   5360: 
                   5361: # ------------------------------------------------------------ tmpget interface
                   5362: sub tmpget {
1.688     albertel 5363:     my ($token,$server)=@_;
                   5364:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5365:     my $rep=&reply("tmpget:$token",$server);
1.667     albertel 5366:     my %returnhash;
                   5367:     foreach my $item (split(/\&/,$rep)) {
                   5368: 	my ($key,$value)=split(/=/,$item);
1.951     raeburn  5369:         next if ($key =~ /^error: 2 /);
1.667     albertel 5370: 	$returnhash{&unescape($key)}=&thaw_unescape($value);
                   5371:     }
                   5372:     return %returnhash;
                   5373: }
                   5374: 
1.1113    raeburn  5375: # ------------------------------------------------------------ tmpdel interface
1.688     albertel 5376: sub tmpdel {
                   5377:     my ($token,$server)=@_;
                   5378:     if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
                   5379:     return &reply("tmpdel:$token",$server);
                   5380: }
                   5381: 
1.765     albertel 5382: # -------------------------------------------------- portfolio access checking
                   5383: 
                   5384: sub portfolio_access {
1.766     albertel 5385:     my ($requrl) = @_;
1.765     albertel 5386:     my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
                   5387:     my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814     raeburn  5388:     if ($result) {
                   5389:         my %setters;
                   5390:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5391:             my ($startblock,$endblock) =
                   5392:                 &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
                   5393:             if ($startblock && $endblock) {
                   5394:                 return 'B';
                   5395:             }
                   5396:         } else {
                   5397:             my ($startblock,$endblock) =
                   5398:                 &Apache::loncommon::blockcheck(\%setters,'port');
                   5399:             if ($startblock && $endblock) {
                   5400:                 return 'B';
                   5401:             }
                   5402:         }
                   5403:     }
1.765     albertel 5404:     if ($result eq 'ok') {
1.766     albertel 5405:        return 'F';
1.765     albertel 5406:     } elsif ($result =~ /^[^:]+:guest_/) {
1.766     albertel 5407:        return 'A';
1.765     albertel 5408:     }
1.766     albertel 5409:     return '';
1.765     albertel 5410: }
                   5411: 
                   5412: sub get_portfolio_access {
1.767     albertel 5413:     my ($udom,$unum,$file_name,$group,$access_hash) = @_;
                   5414: 
                   5415:     if (!ref($access_hash)) {
                   5416: 	my $current_perms = &get_portfile_permissions($udom,$unum);
                   5417: 	my %access_controls = &get_access_controls($current_perms,$group,
                   5418: 						   $file_name);
                   5419: 	$access_hash = $access_controls{$file_name};
                   5420:     }
                   5421: 
1.765     albertel 5422:     my ($public,$guest,@domains,@users,@courses,@groups);
                   5423:     my $now = time;
                   5424:     if (ref($access_hash) eq 'HASH') {
                   5425:         foreach my $key (keys(%{$access_hash})) {
                   5426:             my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   5427:             if ($start > $now) {
                   5428:                 next;
                   5429:             }
                   5430:             if ($end && $end<$now) {
                   5431:                 next;
                   5432:             }
                   5433:             if ($scope eq 'public') {
                   5434:                 $public = $key;
                   5435:                 last;
                   5436:             } elsif ($scope eq 'guest') {
                   5437:                 $guest = $key;
                   5438:             } elsif ($scope eq 'domains') {
                   5439:                 push(@domains,$key);
                   5440:             } elsif ($scope eq 'users') {
                   5441:                 push(@users,$key);
                   5442:             } elsif ($scope eq 'course') {
                   5443:                 push(@courses,$key);
                   5444:             } elsif ($scope eq 'group') {
                   5445:                 push(@groups,$key);
                   5446:             }
                   5447:         }
                   5448:         if ($public) {
                   5449:             return 'ok';
                   5450:         }
                   5451:         if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
                   5452:             if ($guest) {
                   5453:                 return $guest;
                   5454:             }
                   5455:         } else {
                   5456:             if (@domains > 0) {
                   5457:                 foreach my $domkey (@domains) {
                   5458:                     if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
                   5459:                         if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
                   5460:                             return 'ok';
                   5461:                         }
                   5462:                     }
                   5463:                 }
                   5464:             }
                   5465:             if (@users > 0) {
                   5466:                 foreach my $userkey (@users) {
1.865     raeburn  5467:                     if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
                   5468:                         foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
                   5469:                             if (ref($item) eq 'HASH') {
                   5470:                                 if (($item->{'uname'} eq $env{'user.name'}) &&
                   5471:                                     ($item->{'udom'} eq $env{'user.domain'})) {
                   5472:                                     return 'ok';
                   5473:                                 }
                   5474:                             }
                   5475:                         }
                   5476:                     } 
1.765     albertel 5477:                 }
                   5478:             }
                   5479:             my %roleshash;
                   5480:             my @courses_and_groups = @courses;
                   5481:             push(@courses_and_groups,@groups); 
                   5482:             if (@courses_and_groups > 0) {
                   5483:                 my (%allgroups,%allroles); 
                   5484:                 my ($start,$end,$role,$sec,$group);
                   5485:                 foreach my $envkey (%env) {
1.1060    raeburn  5486:                     if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5487:                         my $cid = $2.'_'.$3; 
                   5488:                         if ($1 eq 'gr') {
                   5489:                             $group = $4;
                   5490:                             $allgroups{$cid}{$group} = $env{$envkey};
                   5491:                         } else {
                   5492:                             if ($4 eq '') {
                   5493:                                 $sec = 'none';
                   5494:                             } else {
                   5495:                                 $sec = $4;
                   5496:                             }
                   5497:                             $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5498:                         }
1.811     albertel 5499:                     } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765     albertel 5500:                         my $cid = $2.'_'.$3;
                   5501:                         if ($4 eq '') {
                   5502:                             $sec = 'none';
                   5503:                         } else {
                   5504:                             $sec = $4;
                   5505:                         }
                   5506:                         $allroles{$cid}{$1}{$sec} = $env{$envkey};
                   5507:                     }
                   5508:                 }
                   5509:                 if (keys(%allroles) == 0) {
                   5510:                     return;
                   5511:                 }
                   5512:                 foreach my $key (@courses_and_groups) {
                   5513:                     my %content = %{$$access_hash{$key}};
                   5514:                     my $cnum = $content{'number'};
                   5515:                     my $cdom = $content{'domain'};
                   5516:                     my $cid = $cdom.'_'.$cnum;
                   5517:                     if (!exists($allroles{$cid})) {
                   5518:                         next;
                   5519:                     }    
                   5520:                     foreach my $role_id (keys(%{$content{'roles'}})) {
                   5521:                         my @sections = @{$content{'roles'}{$role_id}{'section'}};
                   5522:                         my @groups = @{$content{'roles'}{$role_id}{'group'}};
                   5523:                         my @status = @{$content{'roles'}{$role_id}{'access'}};
                   5524:                         my @roles = @{$content{'roles'}{$role_id}{'role'}};
                   5525:                         foreach my $role (keys(%{$allroles{$cid}})) {
                   5526:                             if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
                   5527:                                 foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
                   5528:                                     if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
                   5529:                                         if (grep/^all$/,@sections) {
                   5530:                                             return 'ok';
                   5531:                                         } else {
                   5532:                                             if (grep/^$sec$/,@sections) {
                   5533:                                                 return 'ok';
                   5534:                                             }
                   5535:                                         }
                   5536:                                     }
                   5537:                                 }
                   5538:                                 if (keys(%{$allgroups{$cid}}) == 0) {
                   5539:                                     if (grep/^none$/,@groups) {
                   5540:                                         return 'ok';
                   5541:                                     }
                   5542:                                 } else {
                   5543:                                     if (grep/^all$/,@groups) {
                   5544:                                         return 'ok';
                   5545:                                     } 
                   5546:                                     foreach my $group (keys(%{$allgroups{$cid}})) {
                   5547:                                         if (grep/^$group$/,@groups) {
                   5548:                                             return 'ok';
                   5549:                                         }
                   5550:                                     }
                   5551:                                 } 
                   5552:                             }
                   5553:                         }
                   5554:                     }
                   5555:                 }
                   5556:             }
                   5557:             if ($guest) {
                   5558:                 return $guest;
                   5559:             }
                   5560:         }
                   5561:     }
                   5562:     return;
                   5563: }
                   5564: 
                   5565: sub course_group_datechecker {
                   5566:     my ($dates,$now,$status) = @_;
                   5567:     my ($start,$end) = split(/\./,$dates);
                   5568:     if (!$start && !$end) {
                   5569:         return 'ok';
                   5570:     }
                   5571:     if (grep/^active$/,@{$status}) {
                   5572:         if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
                   5573:             return 'ok';
                   5574:         }
                   5575:     }
                   5576:     if (grep/^previous$/,@{$status}) {
                   5577:         if ($end > $now ) {
                   5578:             return 'ok';
                   5579:         }
                   5580:     }
                   5581:     if (grep/^future$/,@{$status}) {
                   5582:         if ($start > $now) {
                   5583:             return 'ok';
                   5584:         }
                   5585:     }
                   5586:     return; 
                   5587: }
                   5588: 
                   5589: sub parse_portfolio_url {
                   5590:     my ($url) = @_;
                   5591: 
                   5592:     my ($type,$udom,$unum,$group,$file_name);
                   5593:     
1.823     albertel 5594:     if ($url =~  m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765     albertel 5595: 	$type = 1;
                   5596:         $udom = $1;
                   5597:         $unum = $2;
                   5598:         $file_name = $3;
1.823     albertel 5599:     } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765     albertel 5600: 	$type = 2;
                   5601:         $udom = $1;
                   5602:         $unum = $2;
                   5603:         $group = $3;
                   5604:         $file_name = $3.'/'.$4;
                   5605:     }
                   5606:     if (wantarray) {
                   5607: 	return ($type,$udom,$unum,$file_name,$group);
                   5608:     }
                   5609:     return $type;
                   5610: }
                   5611: 
                   5612: sub is_portfolio_url {
                   5613:     my ($url) = @_;
                   5614:     return scalar(&parse_portfolio_url($url));
                   5615: }
                   5616: 
1.798     raeburn  5617: sub is_portfolio_file {
                   5618:     my ($file) = @_;
1.820     raeburn  5619:     if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798     raeburn  5620:         return 1;
                   5621:     }
                   5622:     return;
                   5623: }
                   5624: 
1.976     raeburn  5625: sub usertools_access {
1.1084    raeburn  5626:     my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985     raeburn  5627:     my ($access,%tools);
                   5628:     if ($context eq '') {
                   5629:         $context = 'tools';
                   5630:     }
                   5631:     if ($context eq 'requestcourses') {
                   5632:         %tools = (
                   5633:                       official   => 1,
                   5634:                       unofficial => 1,
1.1006    raeburn  5635:                       community  => 1,
1.985     raeburn  5636:                  );
                   5637:     } else {
                   5638:         %tools = (
                   5639:                       aboutme   => 1,
                   5640:                       blog      => 1,
                   5641:                       portfolio => 1,
                   5642:                  );
                   5643:     }
1.976     raeburn  5644:     return if (!defined($tools{$tool}));
                   5645: 
                   5646:     if ((!defined($udom)) || (!defined($uname))) {
                   5647:         $udom = $env{'user.domain'};
                   5648:         $uname = $env{'user.name'};
                   5649:     }
                   5650: 
1.978     raeburn  5651:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
                   5652:         if ($action ne 'reload') {
1.985     raeburn  5653:             if ($context eq 'requestcourses') {
                   5654:                 return $env{'environment.canrequest.'.$tool};
                   5655:             } else {
                   5656:                 return $env{'environment.availabletools.'.$tool};
                   5657:             }
                   5658:         }
1.976     raeburn  5659:     }
                   5660: 
                   5661:     my ($toolstatus,$inststatus);
                   5662: 
1.985     raeburn  5663:     if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
                   5664:          ($action ne 'reload')) {
                   5665:         $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976     raeburn  5666:         $inststatus = $env{'environment.inststatus'};
                   5667:     } else {
1.1084    raeburn  5668:         if (ref($userenvref) eq 'HASH') {
                   5669:             $toolstatus = $userenvref->{$context.'.'.$tool};
                   5670:             $inststatus = $userenvref->{'inststatus'};
                   5671:         } else {
                   5672:             my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
                   5673:             $toolstatus = $userenv{$context.'.'.$tool};
                   5674:             $inststatus = $userenv{'inststatus'};
                   5675:         }
1.976     raeburn  5676:     }
                   5677: 
                   5678:     if ($toolstatus ne '') {
                   5679:         if ($toolstatus) {
                   5680:             $access = 1;
                   5681:         } else {
                   5682:             $access = 0;
                   5683:         }
                   5684:         return $access;
                   5685:     }
                   5686: 
1.1084    raeburn  5687:     my ($is_adv,%domdef);
                   5688:     if (ref($is_advref) eq 'HASH') {
                   5689:         $is_adv = $is_advref->{'is_adv'};
                   5690:     } else {
                   5691:         $is_adv = &is_advanced_user($udom,$uname);
                   5692:     }
                   5693:     if (ref($domdefref) eq 'HASH') {
                   5694:         %domdef = %{$domdefref};
                   5695:     } else {
                   5696:         %domdef = &get_domain_defaults($udom);
                   5697:     }
1.976     raeburn  5698:     if (ref($domdef{$tool}) eq 'HASH') {
                   5699:         if ($is_adv) {
                   5700:             if ($domdef{$tool}{'_LC_adv'} ne '') {
                   5701:                 if ($domdef{$tool}{'_LC_adv'}) { 
                   5702:                     $access = 1;
                   5703:                 } else {
                   5704:                     $access = 0;
                   5705:                 }
                   5706:                 return $access;
                   5707:             }
                   5708:         }
                   5709:         if ($inststatus ne '') {
                   5710:             my ($hasaccess,$hasnoaccess);
                   5711:             foreach my $affiliation (split(/:/,$inststatus)) {
                   5712:                 if ($domdef{$tool}{$affiliation} ne '') { 
                   5713:                     if ($domdef{$tool}{$affiliation}) {
                   5714:                         $hasaccess = 1;
                   5715:                     } else {
                   5716:                         $hasnoaccess = 1;
                   5717:                     }
                   5718:                 }
                   5719:             }
                   5720:             if ($hasaccess || $hasnoaccess) {
                   5721:                 if ($hasaccess) {
                   5722:                     $access = 1;
                   5723:                 } elsif ($hasnoaccess) {
                   5724:                     $access = 0; 
                   5725:                 }
                   5726:                 return $access;
                   5727:             }
                   5728:         } else {
                   5729:             if ($domdef{$tool}{'default'} ne '') {
                   5730:                 if ($domdef{$tool}{'default'}) {
                   5731:                     $access = 1;
                   5732:                 } elsif ($domdef{$tool}{'default'} == 0) {
                   5733:                     $access = 0;
                   5734:                 }
                   5735:                 return $access;
                   5736:             }
                   5737:         }
                   5738:     } else {
1.985     raeburn  5739:         if ($context eq 'tools') {
                   5740:             $access = 1;
                   5741:         } else {
                   5742:             $access = 0;
                   5743:         }
1.976     raeburn  5744:         return $access;
                   5745:     }
                   5746: }
                   5747: 
1.1050    raeburn  5748: sub is_course_owner {
                   5749:     my ($cdom,$cnum,$udom,$uname) = @_;
                   5750:     if (($udom eq '') || ($uname eq '')) {
                   5751:         $udom = $env{'user.domain'};
                   5752:         $uname = $env{'user.name'};
                   5753:     }
                   5754:     unless (($udom eq '') || ($uname eq '')) {
                   5755:         if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
                   5756:             if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
                   5757:                 return 1;
                   5758:             } else {
                   5759:                 my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
                   5760:                 if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
                   5761:                     return 1;
                   5762:                 }
                   5763:             }
                   5764:         }
                   5765:     }
                   5766:     return;
                   5767: }
                   5768: 
1.976     raeburn  5769: sub is_advanced_user {
                   5770:     my ($udom,$uname) = @_;
1.1085    raeburn  5771:     if ($udom ne '' && $uname ne '') {
                   5772:         if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128    raeburn  5773:             if (wantarray) {
                   5774:                 return ($env{'user.adv'},$env{'user.author'});
                   5775:             } else {
                   5776:                 return $env{'user.adv'};
                   5777:             }
1.1085    raeburn  5778:         }
                   5779:     }
1.976     raeburn  5780:     my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
                   5781:     my %allroles;
1.1128    raeburn  5782:     my ($is_adv,$is_author);
1.976     raeburn  5783:     foreach my $role (keys(%roleshash)) {
                   5784:         my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
                   5785:         my $area = '/'.$tdomain.'/'.$trest;
                   5786:         if ($sec ne '') {
                   5787:             $area .= '/'.$sec;
                   5788:         }
                   5789:         if (($area ne '') && ($trole ne '')) {
                   5790:             my $spec=$trole.'.'.$area;
                   5791:             if ($trole =~ /^cr\//) {
                   5792:                 &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
                   5793:             } elsif ($trole ne 'gr') {
                   5794:                 &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
                   5795:             }
1.1128    raeburn  5796:             if ($trole eq 'au') {
                   5797:                 $is_author = 1;
                   5798:             }
1.976     raeburn  5799:         }
                   5800:     }
                   5801:     foreach my $role (keys(%allroles)) {
                   5802:         last if ($is_adv);
                   5803:         foreach my $item (split(/:/,$allroles{$role})) {
                   5804:             if ($item ne '') {
                   5805:                 my ($privilege,$restrictions)=split(/&/,$item);
                   5806:                 if ($privilege eq 'adv') {
                   5807:                     $is_adv = 1;
                   5808:                     last;
                   5809:                 }
                   5810:             }
                   5811:         }
                   5812:     }
1.1128    raeburn  5813:     if (wantarray) {
                   5814:         return ($is_adv,$is_author);
                   5815:     }
1.976     raeburn  5816:     return $is_adv;
                   5817: }
1.798     raeburn  5818: 
1.1035    raeburn  5819: sub check_can_request {
1.1036    raeburn  5820:     my ($dom,$can_request,$request_domains) = @_;
1.1035    raeburn  5821:     my $canreq = 0;
                   5822:     my ($types,$typename) = &Apache::loncommon::course_types();
                   5823:     my @options = ('approval','validate','autolimit');
                   5824:     my $optregex = join('|',@options);
                   5825:     if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
                   5826:         foreach my $type (@{$types}) {
                   5827:             if (&usertools_access($env{'user.name'},
                   5828:                                   $env{'user.domain'},
                   5829:                                   $type,undef,'requestcourses')) {
                   5830:                 $canreq ++;
1.1036    raeburn  5831:                 if (ref($request_domains) eq 'HASH') {
                   5832:                     push(@{$request_domains->{$type}},$env{'user.domain'});
                   5833:                 }
1.1035    raeburn  5834:                 if ($dom eq $env{'user.domain'}) {
                   5835:                     $can_request->{$type} = 1;
                   5836:                 }
                   5837:             }
                   5838:             if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
                   5839:                 my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
                   5840:                 if (@curr > 0) {
1.1036    raeburn  5841:                     foreach my $item (@curr) {
                   5842:                         if (ref($request_domains) eq 'HASH') {
                   5843:                             my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
                   5844:                             if ($otherdom ne '') {
                   5845:                                 if (ref($request_domains->{$type}) eq 'ARRAY') {
                   5846:                                     unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
                   5847:                                         push(@{$request_domains->{$type}},$otherdom);
                   5848:                                     }
                   5849:                                 } else {
                   5850:                                     push(@{$request_domains->{$type}},$otherdom);
                   5851:                                 }
                   5852:                             }
                   5853:                         }
                   5854:                     }
                   5855:                     unless($dom eq $env{'user.domain'}) {
                   5856:                         $canreq ++;
1.1035    raeburn  5857:                         if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
                   5858:                             $can_request->{$type} = 1;
                   5859:                         }
                   5860:                     }
                   5861:                 }
                   5862:             }
                   5863:         }
                   5864:     }
                   5865:     return $canreq;
                   5866: }
                   5867: 
1.341     www      5868: # ---------------------------------------------- Custom access rule evaluation
                   5869: 
                   5870: sub customaccess {
                   5871:     my ($priv,$uri)=@_;
1.807     albertel 5872:     my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819     www      5873:     my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807     albertel 5874:     $udom = &LONCAPA::clean_domain($udom);
                   5875:     $ucrs = &LONCAPA::clean_username($ucrs);
1.341     www      5876:     my $access=0;
1.800     albertel 5877:     foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893     albertel 5878: 	my ($effect,$realm,$role,$type)=split(/\:/,$right);
                   5879: 	if ($type eq 'user') {
                   5880: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896     albertel 5881: 		my ($tdom,$tuname)=split(m{/},$scope);
1.893     albertel 5882: 		if ($tdom) {
                   5883: 		    if ($tdom ne $env{'user.domain'}) { next; }
                   5884: 		}
1.896     albertel 5885: 		if ($tuname) {
                   5886: 		    if ($tuname ne $env{'user.name'}) { next; }
1.893     albertel 5887: 		}
                   5888: 		$access=($effect eq 'allow');
                   5889: 		last;
                   5890: 	    }
                   5891: 	} else {
                   5892: 	    if ($role) {
                   5893: 		if ($role ne $urole) { next; }
                   5894: 	    }
                   5895: 	    foreach my $scope (split(/\s*\,\s*/,$realm)) {
                   5896: 		my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
                   5897: 		if ($tdom) {
                   5898: 		    if ($tdom ne $udom) { next; }
                   5899: 		}
                   5900: 		if ($tcrs) {
                   5901: 		    if ($tcrs ne $ucrs) { next; }
                   5902: 		}
                   5903: 		if ($tsec) {
                   5904: 		    if ($tsec ne $usec) { next; }
                   5905: 		}
                   5906: 		$access=($effect eq 'allow');
                   5907: 		last;
                   5908: 	    }
                   5909: 	    if ($realm eq '' && $role eq '') {
                   5910: 		$access=($effect eq 'allow');
                   5911: 	    }
1.402     bowersj2 5912: 	}
1.341     www      5913:     }
                   5914:     return $access;
                   5915: }
                   5916: 
1.103     harris41 5917: # ------------------------------------------------- Check for a user privilege
1.12      www      5918: 
                   5919: sub allowed {
1.810     raeburn  5920:     my ($priv,$uri,$symb,$role)=@_;
1.705     albertel 5921:     my $ver_orguri=$uri;
1.439     www      5922:     $uri=&deversion($uri);
1.152     www      5923:     my $orguri=$uri;
1.52      www      5924:     $uri=&declutter($uri);
1.809     raeburn  5925: 
1.810     raeburn  5926:     if ($priv eq 'evb') {
                   5927: # Evade communication block restrictions for specified role in a course
                   5928:         if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
                   5929:             return $1;
                   5930:         } else {
                   5931:             return;
                   5932:         }
                   5933:     }
                   5934: 
1.620     albertel 5935:     if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54      www      5936: # Free bre access to adm and meta resources
1.775     albertel 5937:     if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$})) 
1.769     albertel 5938: 	 || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) )) 
                   5939: 	&& ($priv eq 'bre')) {
1.14      www      5940: 	return 'F';
1.159     www      5941:     }
                   5942: 
1.545     banghart 5943: # Free bre access to user's own portfolio contents
1.714     raeburn  5944:     my ($space,$domain,$name,@dir)=split('/',$uri);
1.647     raeburn  5945:     if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) && 
1.714     raeburn  5946: 	($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814     raeburn  5947:         my %setters;
                   5948:         my ($startblock,$endblock) = 
                   5949:             &Apache::loncommon::blockcheck(\%setters,'port');
                   5950:         if ($startblock && $endblock) {
                   5951:             return 'B';
                   5952:         } else {
                   5953:             return 'F';
                   5954:         }
1.545     banghart 5955:     }
                   5956: 
1.762     raeburn  5957: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714     raeburn  5958:     if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups') 
                   5959:          && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
                   5960:         if (exists($env{'request.course.id'})) {
                   5961:             my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   5962:             my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   5963:             if (($domain eq $cdom) && ($name eq $cnum)) {
                   5964:                 my $courseprivid=$env{'request.course.id'};
                   5965:                 $courseprivid=~s/\_/\//;
                   5966:                 if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
                   5967:                     .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
                   5968:                     return $1; 
1.762     raeburn  5969:                 } else {
                   5970:                     if ($env{'request.course.sec'}) {
                   5971:                         $courseprivid.='/'.$env{'request.course.sec'};
                   5972:                     }
                   5973:                     if ($env{'user.priv.'.$env{'request.role'}.'./'.
                   5974:                         $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
                   5975:                         return $2;
                   5976:                     }
1.714     raeburn  5977:                 }
                   5978:             }
                   5979:         }
                   5980:     }
                   5981: 
1.159     www      5982: # Free bre to public access
                   5983: 
                   5984:     if ($priv eq 'bre') {
1.238     www      5985:         my $copyright=&metadata($uri,'copyright');
1.620     albertel 5986: 	if (($copyright eq 'public') && (!$env{'request.course.id'})) { 
1.301     www      5987:            return 'F'; 
                   5988:         }
1.238     www      5989:         if ($copyright eq 'priv') {
                   5990:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5991: 	    unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238     www      5992: 		return '';
                   5993:             }
                   5994:         }
                   5995:         if ($copyright eq 'domain') {
                   5996:             $uri=~/([^\/]+)\/([^\/]+)\//;
1.620     albertel 5997: 	    unless (($env{'user.domain'} eq $1) ||
                   5998:                  ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238     www      5999: 		return '';
                   6000:             }
1.262     matthew  6001:         }
1.620     albertel 6002:         if ($env{'request.role'}=~ /li\.\//) {
1.262     matthew  6003:             # Library role, so allow browsing of resources in this domain.
                   6004:             return 'F';
1.238     www      6005:         }
1.341     www      6006:         if ($copyright eq 'custom') {
                   6007: 	    unless (&customaccess($priv,$uri)) { return ''; }
                   6008:         }
1.14      www      6009:     }
1.264     matthew  6010:     # Domain coordinator is trying to create a course
1.620     albertel 6011:     if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264     matthew  6012:         # uri is the requested domain in this case.
                   6013:         # comparison to 'request.role.domain' shows if the user has selected
1.678     raeburn  6014:         # a role of dc for the domain in question.
1.620     albertel 6015:         return 'F' if ($uri eq $env{'request.role.domain'});
1.264     matthew  6016:     }
1.29      www      6017: 
1.52      www      6018:     my $thisallowed='';
                   6019:     my $statecond=0;
                   6020:     my $courseprivid='';
                   6021: 
1.1039    raeburn  6022:     my $ownaccess;
1.1043    raeburn  6023:     # Community Coordinator or Assistant Co-author browsing resource space.
1.1039    raeburn  6024:     if (($priv eq 'bro') && ($env{'user.author'})) {
                   6025:         if ($uri eq '') {
                   6026:             $ownaccess = 1;
                   6027:         } else {
                   6028:             if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
                   6029:                 my $udom = $env{'user.domain'};
                   6030:                 my $uname = $env{'user.name'};
                   6031:                 if ($uri =~ m{^\Q$udom\E/?$}) {
                   6032:                     $ownaccess = 1;
1.1040    raeburn  6033:                 } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039    raeburn  6034:                     unless ($uri =~ m{\.\./}) {
                   6035:                         $ownaccess = 1;
                   6036:                     }
                   6037:                 } elsif (($udom ne 'public') && ($uname ne 'public')) {
                   6038:                     my $now = time;
                   6039:                     if ($uri =~ m{^([^/]+)/?$}) {
                   6040:                         my $adom = $1;
                   6041:                         foreach my $key (keys(%env)) {
1.1042    raeburn  6042:                             if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039    raeburn  6043:                                 my ($start,$end) = split('.',$env{$key});
                   6044:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6045:                                     $ownaccess = 1;
                   6046:                                     last;
                   6047:                                 }
                   6048:                             }
                   6049:                         }
                   6050:                     } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
                   6051:                         my $adom = $1;
                   6052:                         my $aname = $2;
1.1042    raeburn  6053:                         foreach my $role ('ca','aa') { 
                   6054:                             if ($env{"user.role.$role./$adom/$aname"}) {
                   6055:                                 my ($start,$end) =
                   6056:                                     split('.',$env{"user.role.$role./$adom/$aname"});
                   6057:                                 if (($now >= $start) && (!$end || $end < $now)) {
                   6058:                                     $ownaccess = 1;
                   6059:                                     last;
                   6060:                                 }
1.1039    raeburn  6061:                             }
                   6062:                         }
                   6063:                     }
                   6064:                 }
                   6065:             }
                   6066:         }
                   6067:     }
                   6068: 
1.52      www      6069: # Course
                   6070: 
1.620     albertel 6071:     if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6072:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6073:             $thisallowed.=$1;
                   6074:         }
1.52      www      6075:     }
1.29      www      6076: 
1.52      www      6077: # Domain
                   6078: 
1.620     albertel 6079:     if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479     albertel 6080:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6081:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6082:             $thisallowed.=$1;
                   6083:         }
1.12      www      6084:     }
1.52      www      6085: 
1.1141    raeburn  6086: # User who is not author or co-author might still be able to edit
                   6087: # resource of an author in the domain (e.g., if Domain Coordinator).
                   6088:     if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
                   6089:         (&allowed('mdc',$env{'request.course.id'}))) {
                   6090:         if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
                   6091:             $thisallowed.=$1;
                   6092:         }
                   6093:     }
                   6094: 
1.52      www      6095: # Course: uri itself is a course
1.66      www      6096:     my $courseuri=$uri;
                   6097:     $courseuri=~s/\_(\d)/\/$1/;
1.83      www      6098:     $courseuri=~s/^([^\/])/\/$1/;
1.81      www      6099: 
1.620     albertel 6100:     if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479     albertel 6101:        =~/\Q$priv\E\&([^\:]*)/) {
1.1043    raeburn  6102:         unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039    raeburn  6103:             $thisallowed.=$1;
                   6104:         }
1.12      www      6105:     }
1.29      www      6106: 
1.665     albertel 6107: # URI is an uploaded document for this course, default permissions don't matter
1.611     albertel 6108: # not allowing 'edit' access (editupload) to uploaded course docs
1.492     albertel 6109:     if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665     albertel 6110: 	$thisallowed='';
1.671     raeburn  6111:         my ($match)=&is_on_map($uri);
                   6112:         if ($match) {
                   6113:             if ($env{'user.priv.'.$env{'request.role'}.'./'}
                   6114:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6115:                 my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6116:                 if (@blockers > 0) {
                   6117:                     $thisallowed = 'B';
                   6118:                 } else {
                   6119:                     $thisallowed.=$1;
                   6120:                 }
1.671     raeburn  6121:             }
                   6122:         } else {
1.705     albertel 6123:             my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671     raeburn  6124:             if ($refuri) {
                   6125:                 if ($refuri =~ m|^/adm/|) {
1.669     raeburn  6126:                     $thisallowed='F';
1.671     raeburn  6127:                 } else {
                   6128:                     $refuri=&declutter($refuri);
                   6129:                     my ($match) = &is_on_map($refuri);
                   6130:                     if ($match) {
1.1162    raeburn  6131:                         my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6132:                         if (@blockers > 0) {
                   6133:                             $thisallowed = 'B';
                   6134:                         } else {
                   6135:                             $thisallowed='F';
                   6136:                         }
1.671     raeburn  6137:                     }
1.669     raeburn  6138:                 }
1.671     raeburn  6139:             }
                   6140:         }
1.314     www      6141:     }
1.492     albertel 6142: 
1.766     albertel 6143:     if ($priv eq 'bre'
                   6144: 	&& $thisallowed ne 'F' 
                   6145: 	&& $thisallowed ne '2'
                   6146: 	&& &is_portfolio_url($uri)) {
                   6147: 	$thisallowed = &portfolio_access($uri);
                   6148:     }
                   6149:     
1.52      www      6150: # Full access at system, domain or course-wide level? Exit.
1.29      www      6151:     if ($thisallowed=~/F/) {
                   6152: 	return 'F';
                   6153:     }
                   6154: 
1.52      www      6155: # If this is generating or modifying users, exit with special codes
1.29      www      6156: 
1.643     www      6157:     if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
                   6158: 	if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642     albertel 6159: 	    my ($audom,$auname)=split('/',$uri);
1.643     www      6160: # no author name given, so this just checks on the general right to make a co-author in this domain
                   6161: 	    unless ($auname) { return $thisallowed; }
                   6162: # an author name is given, so we are about to actually make a co-author for a certain account
1.642     albertel 6163: 	    if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
                   6164: 		(($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
                   6165: 		 ($audom ne $env{'request.role.domain'}))) { return ''; }
                   6166: 	}
1.52      www      6167: 	return $thisallowed;
                   6168:     }
                   6169: #
1.103     harris41 6170: # Gathered so far: system, domain and course wide privileges
1.52      www      6171: #
                   6172: # Course: See if uri or referer is an individual resource that is part of 
                   6173: # the course
                   6174: 
1.620     albertel 6175:     if ($env{'request.course.id'}) {
1.232     www      6176: 
1.620     albertel 6177:        $courseprivid=$env{'request.course.id'};
                   6178:        if ($env{'request.course.sec'}) {
                   6179:           $courseprivid.='/'.$env{'request.course.sec'};
1.52      www      6180:        }
                   6181:        $courseprivid=~s/\_/\//;
                   6182:        my $checkreferer=1;
1.232     www      6183:        my ($match,$cond)=&is_on_map($uri);
                   6184:        if ($match) {
                   6185:            $statecond=$cond;
1.620     albertel 6186:            if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6187:                =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6188:                my $value = $1;
                   6189:                if ($priv eq 'bre') {
                   6190:                    my @blockers = &has_comm_blocking($priv,$symb,$uri);
                   6191:                    if (@blockers > 0) {
                   6192:                        $thisallowed = 'B';
                   6193:                    } else {
                   6194:                        $thisallowed.=$value;
                   6195:                    }
                   6196:                } else {
                   6197:                    $thisallowed.=$value;
                   6198:                }
1.52      www      6199:                $checkreferer=0;
                   6200:            }
1.29      www      6201:        }
1.83      www      6202:        
1.148     www      6203:        if ($checkreferer) {
1.620     albertel 6204: 	  my $refuri=$env{'httpref.'.$orguri};
1.148     www      6205:             unless ($refuri) {
1.800     albertel 6206:                 foreach my $key (keys(%env)) {
                   6207: 		    if ($key=~/^httpref\..*\*/) {
                   6208: 			my $pattern=$key;
1.156     www      6209:                         $pattern=~s/^httpref\.\/res\///;
1.148     www      6210:                         $pattern=~s/\*/\[\^\/\]\+/g;
                   6211:                         $pattern=~s/\//\\\//g;
1.152     www      6212:                         if ($orguri=~/$pattern/) {
1.800     albertel 6213: 			    $refuri=$env{$key};
1.148     www      6214:                         }
                   6215:                     }
1.191     harris41 6216:                 }
1.148     www      6217:             }
1.232     www      6218: 
1.148     www      6219:          if ($refuri) { 
1.152     www      6220: 	  $refuri=&declutter($refuri);
1.232     www      6221:           my ($match,$cond)=&is_on_map($refuri);
                   6222:             if ($match) {
                   6223:               my $refstatecond=$cond;
1.620     albertel 6224:               if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479     albertel 6225:                   =~/\Q$priv\E\&([^\:]*)/) {
1.1162    raeburn  6226:                   my $value = $1;
                   6227:                   if ($priv eq 'bre') {
                   6228:                       my @blockers = &has_comm_blocking($priv,$symb,$refuri);
                   6229:                       if (@blockers > 0) {
                   6230:                           $thisallowed = 'B';
                   6231:                       } else {
                   6232:                           $thisallowed.=$value;
                   6233:                       }
                   6234:                   } else {
                   6235:                       $thisallowed.=$value;
                   6236:                   }
1.53      www      6237:                   $uri=$refuri;
                   6238:                   $statecond=$refstatecond;
1.52      www      6239:               }
                   6240:           }
1.148     www      6241:         }
1.29      www      6242:        }
1.52      www      6243:    }
1.29      www      6244: 
1.52      www      6245: #
1.103     harris41 6246: # Gathered now: all privileges that could apply, and condition number
1.52      www      6247: # 
                   6248: #
                   6249: # Full or no access?
                   6250: #
1.29      www      6251: 
1.52      www      6252:     if ($thisallowed=~/F/) {
                   6253: 	return 'F';
                   6254:     }
1.29      www      6255: 
1.52      www      6256:     unless ($thisallowed) {
                   6257:         return '';
                   6258:     }
1.29      www      6259: 
1.52      www      6260: # Restrictions exist, deal with them
                   6261: #
                   6262: #   C:according to course preferences
                   6263: #   R:according to resource settings
                   6264: #   L:unless locked
                   6265: #   X:according to user session state
                   6266: #
                   6267: 
                   6268: # Possibly locked functionality, check all courses
1.54      www      6269: # Locks might take effect only after 10 minutes cache expiration for other
                   6270: # courses, and 2 minutes for current course
1.52      www      6271: 
                   6272:     my $envkey;
                   6273:     if ($thisallowed=~/L/) {
1.1000    raeburn  6274:         foreach $envkey (keys(%env)) {
1.54      www      6275:            if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
                   6276:                my $courseid=$2;
                   6277:                my $roleid=$1.'.'.$2;
1.92      www      6278:                $courseid=~s/^\///;
1.54      www      6279:                my $expiretime=600;
1.620     albertel 6280:                if ($env{'request.role'} eq $roleid) {
1.54      www      6281: 		  $expiretime=120;
                   6282:                }
                   6283: 	       my ($cdom,$cnum,$csec)=split(/\//,$courseid);
                   6284:                my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620     albertel 6285:                if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731     albertel 6286: 		   &coursedescription($courseid,{'freshen_cache' => 1});
1.54      www      6287:                }
1.620     albertel 6288:                if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6289:                 || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
                   6290: 		   if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
                   6291:                        &log($env{'user.domain'},$env{'user.name'},
                   6292:                             $env{'user.home'},
1.57      www      6293:                             'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52      www      6294:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6295:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6296: 		       return '';
                   6297:                    }
                   6298:                }
1.620     albertel 6299:                if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
                   6300:                 || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
                   6301: 		   if ($env{'priv.'.$priv.'.lock.expire'}>time) {
                   6302:                        &log($env{'user.domain'},$env{'user.name'},
                   6303:                             $env{'user.home'},
1.57      www      6304:                             'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52      www      6305:                             $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620     albertel 6306:                             $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52      www      6307: 		       return '';
                   6308:                    }
                   6309:                }
                   6310: 	   }
1.29      www      6311:        }
1.52      www      6312:     }
                   6313:    
                   6314: #
                   6315: # Rest of the restrictions depend on selected course
                   6316: #
                   6317: 
1.620     albertel 6318:     unless ($env{'request.course.id'}) {
1.766     albertel 6319: 	if ($thisallowed eq 'A') {
                   6320: 	    return 'A';
1.814     raeburn  6321:         } elsif ($thisallowed eq 'B') {
                   6322:             return 'B';
1.766     albertel 6323: 	} else {
                   6324: 	    return '1';
                   6325: 	}
1.52      www      6326:     }
1.29      www      6327: 
1.52      www      6328: #
                   6329: # Now user is definitely in a course
                   6330: #
1.53      www      6331: 
                   6332: 
                   6333: # Course preferences
                   6334: 
                   6335:    if ($thisallowed=~/C/) {
1.620     albertel 6336:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
                   6337:        my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
                   6338:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479     albertel 6339: 	   =~/\Q$rolecode\E/) {
1.1103    raeburn  6340: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6341: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6342: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
                   6343: 			$env{'request.course.id'});
                   6344: 	   }
1.237     www      6345:            return '';
                   6346:        }
                   6347: 
1.620     albertel 6348:        if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479     albertel 6349: 	   =~/\Q$unamedom\E/) {
1.1103    raeburn  6350: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6351: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
                   6352: 			'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
                   6353: 			$env{'request.course.id'});
                   6354: 	   }
1.54      www      6355:            return '';
                   6356:        }
1.53      www      6357:    }
                   6358: 
                   6359: # Resource preferences
                   6360: 
                   6361:    if ($thisallowed=~/R/) {
1.620     albertel 6362:        my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479     albertel 6363:        if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103    raeburn  6364: 	   if (($priv ne 'pch') && ($priv ne 'plc')) { 
1.689     albertel 6365: 	       &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
                   6366: 			'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
                   6367: 	   }
                   6368: 	   return '';
1.54      www      6369:        }
1.53      www      6370:    }
1.30      www      6371: 
1.246     www      6372: # Restricted by state or randomout?
1.30      www      6373: 
1.52      www      6374:    if ($thisallowed=~/X/) {
1.620     albertel 6375:       if ($env{'acc.randomout'}) {
1.579     albertel 6376: 	 if (!$symb) { $symb=&symbread($uri,1); }
1.620     albertel 6377:          if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) { 
1.248     www      6378:             return ''; 
                   6379:          }
1.247     www      6380:       }
                   6381:       if (&condval($statecond)) {
1.52      www      6382: 	 return '2';
                   6383:       } else {
                   6384:          return '';
                   6385:       }
                   6386:    }
1.30      www      6387: 
1.766     albertel 6388:     if ($thisallowed eq 'A') {
                   6389: 	return 'A';
1.814     raeburn  6390:     } elsif ($thisallowed eq 'B') {
                   6391:         return 'B';
1.766     albertel 6392:     }
1.52      www      6393:    return 'F';
1.232     www      6394: }
1.1162    raeburn  6395: 
                   6396: sub get_comm_blocks {
                   6397:     my ($cdom,$cnum) = @_;
                   6398:     if ($cdom eq '' || $cnum eq '') {
                   6399:         return unless ($env{'request.course.id'});
                   6400:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   6401:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   6402:     }
                   6403:     my %commblocks;
                   6404:     my $hashid=$cdom.'_'.$cnum;
                   6405:     my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
                   6406:     if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
                   6407:         %commblocks = %{$blocksref};
                   6408:     } else {
                   6409:         %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
                   6410:         my $cachetime = 600;
                   6411:         &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
                   6412:     }
                   6413:     return %commblocks;
                   6414: }
                   6415: 
                   6416: sub has_comm_blocking {
                   6417:     my ($priv,$symb,$uri,$blocks) = @_;
                   6418:     return unless ($env{'request.course.id'});
                   6419:     return unless ($priv eq 'bre');
                   6420:     return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
                   6421:     my %commblocks;
                   6422:     if (ref($blocks) eq 'HASH') {
                   6423:         %commblocks = %{$blocks};
                   6424:     } else {
                   6425:         %commblocks = &get_comm_blocks();
                   6426:     }
                   6427:     return unless (keys(%commblocks) > 0);
                   6428:     if (!$symb) { $symb=&symbread($uri,1); }
                   6429:     my ($map,$resid,undef)=&decode_symb($symb);
                   6430:     my %tocheck = (
                   6431:                     maps      => $map,
                   6432:                     resources => $symb,
                   6433:                   );
                   6434:     my @blockers;
                   6435:     my $now = time;
1.1163    raeburn  6436:     my $navmap = Apache::lonnavmaps::navmap->new();
1.1162    raeburn  6437:     foreach my $block (keys(%commblocks)) {
                   6438:         if ($block =~ /^(\d+)____(\d+)$/) {
                   6439:             my ($start,$end) = ($1,$2);
                   6440:             if ($start <= $now && $end >= $now) {
                   6441:                 if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6442:                     if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6443:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
                   6444:                             if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
                   6445:                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6446:                                     push(@blockers,$block);
                   6447:                                 }
                   6448:                             }
                   6449:                         }
                   6450:                         if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
                   6451:                             if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
                   6452:                                 unless (grep(/^\Q$block\E$/,@blockers)) {  
                   6453:                                     push(@blockers,$block);
                   6454:                                 }
                   6455:                             }
                   6456:                         }
                   6457:                     }
                   6458:                 }
                   6459:             }
                   6460:         } elsif ($block =~ /^firstaccess____(.+)$/) {
                   6461:             my $item = $1;
1.1163    raeburn  6462:             my @to_test;
1.1162    raeburn  6463:             if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   6464:                 if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
                   6465:                     my $check_interval;
                   6466:                     if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
                   6467:                         my @interval;
                   6468:                         my $type = 'map';
                   6469:                         if ($item eq 'course') {
                   6470:                             $type = 'course';
                   6471:                             @interval=&EXT("resource.0.interval");
                   6472:                         } else {
                   6473:                             if ($item =~ /___\d+___/) {
                   6474:                                 $type = 'resource';
                   6475:                                 @interval=&EXT("resource.0.interval",$item);
1.1163    raeburn  6476:                                 if (ref($navmap)) {                        
                   6477:                                     my $res = $navmap->getBySymb($item); 
                   6478:                                     push(@to_test,$res);
                   6479:                                 }
1.1162    raeburn  6480:                             } else {
                   6481:                                 my $mapsymb = &symbread($item,1);
                   6482:                                 if ($mapsymb) {
                   6483:                                     if (ref($navmap)) {
                   6484:                                         my $mapres = $navmap->getBySymb($mapsymb);
1.1163    raeburn  6485:                                         @to_test = $mapres->retrieveResources($mapres,undef,0,1);
                   6486:                                         foreach my $res (@to_test) {
1.1162    raeburn  6487:                                             my $symb = $res->symb();
                   6488:                                             next if ($symb eq $mapsymb);
                   6489:                                             if ($symb ne '') {
                   6490:                                                 @interval=&EXT("resource.0.interval",$symb);
                   6491:                                                 last;
                   6492:                                             }
                   6493:                                         }
                   6494:                                     }
                   6495:                                 }
                   6496:                             }
                   6497:                         }
                   6498:                         if ($interval[0] =~ /\d+/) {
                   6499:                             my $first_access;
                   6500:                             if ($type eq 'resource') {
                   6501:                                 $first_access=&get_first_access($interval[1],$item);
                   6502:                             } elsif ($type eq 'map') {
                   6503:                                 $first_access=&get_first_access($interval[1],undef,$item);
                   6504:                             } else {
                   6505:                                 $first_access=&get_first_access($interval[1]);
                   6506:                             }
                   6507:                             if ($first_access) {
                   6508:                                 my $timesup = $first_access+$interval[0];
                   6509:                                 if ($timesup > $now) {
1.1163    raeburn  6510:                                     foreach my $res (@to_test) {
                   6511:                                         if ($res->is_problem()) {
                   6512:                                             if ($res->completable()) {
                   6513:                                                 unless (grep(/^\Q$block\E$/,@blockers)) {
                   6514:                                                     push(@blockers,$block);
                   6515:                                                 }
                   6516:                                                 last;
                   6517:                                             }
                   6518:                                         }
1.1162    raeburn  6519:                                     }
                   6520:                                 }
                   6521:                             }
                   6522:                         }
                   6523:                     }
                   6524:                 }
                   6525:             }
                   6526:         }
                   6527:     }
                   6528:     return @blockers;
                   6529: }
                   6530: 
                   6531: sub check_docs_block {
                   6532:     my ($docsblock,$tocheck) =@_;
                   6533:     if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
                   6534:         return;
                   6535:     }
                   6536:     if (ref($docsblock->{'maps'}) eq 'HASH') {
                   6537:         if ($tocheck->{'maps'}) {
                   6538:             if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
                   6539:                 return 1;
                   6540:             }
                   6541:         }
                   6542:     }
                   6543:     if (ref($docsblock->{'resources'}) eq 'HASH') {
                   6544:         if ($tocheck->{'resources'}) {
                   6545:             if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
                   6546:                 return 1;
                   6547:             }
                   6548:         }
                   6549:     }
                   6550:     return;
                   6551: }
                   6552: 
1.1133    foxr     6553: #
                   6554: #   Removes the versino from a URI and
                   6555: #   splits it in to its filename and path to the filename.
                   6556: #   Seems like File::Basename could have done this more clearly.
                   6557: #   Parameters:
                   6558: #      $uri   - input URI
                   6559: #   Returns:
                   6560: #     Two element list consisting of 
                   6561: #     $pathname  - the URI up to and excluding the trailing /
                   6562: #     $filename  - The part of the URI following the last /
                   6563: #  NOTE:
                   6564: #    Another realization of this is simply:
                   6565: #    use File::Basename;
                   6566: #    ...
                   6567: #    $uri = shift;
                   6568: #    $filename = basename($uri);
                   6569: #    $path     = dirname($uri);
                   6570: #    return ($filename, $path);
                   6571: #
                   6572: #     The implementation below is probably faster however.
                   6573: #
1.710     albertel 6574: sub split_uri_for_cond {
                   6575:     my $uri=&deversion(&declutter(shift));
                   6576:     my @uriparts=split(/\//,$uri);
                   6577:     my $filename=pop(@uriparts);
                   6578:     my $pathname=join('/',@uriparts);
                   6579:     return ($pathname,$filename);
                   6580: }
1.232     www      6581: # --------------------------------------------------- Is a resource on the map?
                   6582: 
                   6583: sub is_on_map {
1.710     albertel 6584:     my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289     bowersj2 6585:     #Trying to find the conditional for the file
1.620     albertel 6586:     my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289     bowersj2 6587: 	       /\&\Q$filename\E\:([\d\|]+)\&/);
1.232     www      6588:     if ($match) {
1.289     bowersj2 6589: 	return (1,$1);
                   6590:     } else {
1.434     www      6591: 	return (0,0);
1.289     bowersj2 6592:     }
1.12      www      6593: }
                   6594: 
1.427     www      6595: # --------------------------------------------------------- Get symb from alias
                   6596: 
                   6597: sub get_symb_from_alias {
                   6598:     my $symb=shift;
                   6599:     my ($map,$resid,$url)=&decode_symb($symb);
                   6600: # Already is a symb
                   6601:     if ($url) { return $symb; }
                   6602: # Must be an alias
                   6603:     my $aliassymb='';
                   6604:     my %bighash;
1.620     albertel 6605:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427     www      6606:                             &GDBM_READER(),0640)) {
                   6607:         my $rid=$bighash{'mapalias_'.$symb};
                   6608: 	if ($rid) {
                   6609: 	    my ($mapid,$resid)=split(/\./,$rid);
1.429     albertel 6610: 	    $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
                   6611: 				    $resid,$bighash{'src_'.$rid});
1.427     www      6612: 	}
                   6613:         untie %bighash;
                   6614:     }
                   6615:     return $aliassymb;
                   6616: }
                   6617: 
1.12      www      6618: # ----------------------------------------------------------------- Define Role
                   6619: 
                   6620: sub definerole {
                   6621:   if (allowed('mcr','/')) {
                   6622:     my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800     albertel 6623:     foreach my $role (split(':',$sysrole)) {
                   6624: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6625:         if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
                   6626:         if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
                   6627: 	    if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6628:                return "refused:s:$crole&$cqual"; 
                   6629:             }
                   6630:         }
1.191     harris41 6631:     }
1.800     albertel 6632:     foreach my $role (split(':',$domrole)) {
                   6633: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6634:         if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
                   6635:         if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
                   6636: 	    if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) { 
1.21      www      6637:                return "refused:d:$crole&$cqual"; 
                   6638:             }
                   6639:         }
1.191     harris41 6640:     }
1.800     albertel 6641:     foreach my $role (split(':',$courole)) {
                   6642: 	my ($crole,$cqual)=split(/\&/,$role);
1.479     albertel 6643:         if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
                   6644:         if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
                   6645: 	    if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) { 
1.21      www      6646:                return "refused:c:$crole&$cqual"; 
                   6647:             }
                   6648:         }
1.191     harris41 6649:     }
1.620     albertel 6650:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
                   6651:                 "$env{'user.domain'}:$env{'user.name'}:".
1.21      www      6652: 	        "rolesdef_$rolename=".
                   6653:                 escape($sysrole.'_'.$domrole.'_'.$courole);
1.620     albertel 6654:     return reply($command,$env{'user.home'});
1.12      www      6655:   } else {
                   6656:     return 'refused';
                   6657:   }
1.105     harris41 6658: }
                   6659: 
                   6660: # ---------------- Make a metadata query against the network of library servers
                   6661: 
                   6662: sub metadata_query {
1.244     matthew  6663:     my ($query,$custom,$customshow,$server_array)=@_;
1.120     harris41 6664:     my %rhash;
1.845     albertel 6665:     my %libserv = &all_library();
1.244     matthew  6666:     my @server_list = (defined($server_array) ? @$server_array
                   6667:                                               : keys(%libserv) );
                   6668:     for my $server (@server_list) {
1.118     harris41 6669: 	unless ($custom or $customshow) {
                   6670: 	    my $reply=&reply("querysend:".&escape($query),$server);
                   6671: 	    $rhash{$server}=$reply;
                   6672: 	}
                   6673: 	else {
                   6674: 	    my $reply=&reply("querysend:".&escape($query).':'.
                   6675: 			     &escape($custom).':'.&escape($customshow),
                   6676: 			     $server);
                   6677: 	    $rhash{$server}=$reply;
                   6678: 	}
1.112     harris41 6679:     }
1.118     harris41 6680:     return \%rhash;
1.240     www      6681: }
                   6682: 
                   6683: # ----------------------------------------- Send log queries and wait for reply
                   6684: 
                   6685: sub log_query {
                   6686:     my ($uname,$udom,$query,%filters)=@_;
                   6687:     my $uhome=&homeserver($uname,$udom);
                   6688:     if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838     albertel 6689:     my $uhost=&hostname($uhome);
1.800     albertel 6690:     my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240     www      6691:     my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
                   6692:                        $uhome);
1.479     albertel 6693:     unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242     www      6694:     return get_query_reply($queryid);
                   6695: }
                   6696: 
1.818     raeburn  6697: # -------------------------- Update MySQL table for portfolio file
                   6698: 
                   6699: sub update_portfolio_table {
1.821     raeburn  6700:     my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970     raeburn  6701:     if ($group ne '') {
                   6702:         $file_name =~s /^\Q$group\E//;
                   6703:     }
1.818     raeburn  6704:     my $homeserver = &homeserver($uname,$udom);
                   6705:     my $queryid=
1.821     raeburn  6706:         &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
                   6707:                ':'.&escape($file_name).':'.$action,$homeserver);
1.818     raeburn  6708:     my $reply = &get_query_reply($queryid);
                   6709:     return $reply;
                   6710: }
                   6711: 
1.899     raeburn  6712: # -------------------------- Update MySQL allusers table
                   6713: 
                   6714: sub update_allusers_table {
                   6715:     my ($uname,$udom,$names) = @_;
                   6716:     my $homeserver = &homeserver($uname,$udom);
                   6717:     my $queryid=
                   6718:         &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
                   6719:                'lastname='.&escape($names->{'lastname'}).'%%'.
                   6720:                'firstname='.&escape($names->{'firstname'}).'%%'.
                   6721:                'middlename='.&escape($names->{'middlename'}).'%%'.
                   6722:                'generation='.&escape($names->{'generation'}).'%%'.
                   6723:                'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
                   6724:                'id='.&escape($names->{'id'}),$homeserver);
1.1075    raeburn  6725:     return;
1.899     raeburn  6726: }
                   6727: 
1.508     raeburn  6728: # ------- Request retrieval of institutional classlists for course(s)
1.506     raeburn  6729: 
                   6730: sub fetch_enrollment_query {
1.511     raeburn  6731:     my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508     raeburn  6732:     my $homeserver;
1.547     raeburn  6733:     my $maxtries = 1;
1.508     raeburn  6734:     if ($context eq 'automated') {
                   6735:         $homeserver = $perlvar{'lonHostID'};
1.547     raeburn  6736:         $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508     raeburn  6737:     } else {
                   6738:         $homeserver = &homeserver($cnum,$dom);
                   6739:     }
1.838     albertel 6740:     my $host=&hostname($homeserver);
1.506     raeburn  6741:     my $cmd = '';
1.1000    raeburn  6742:     foreach my $affiliate (keys(%{$affiliatesref})) {
1.800     albertel 6743:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506     raeburn  6744:     }
                   6745:     $cmd =~ s/%%$//;
                   6746:     $cmd = &escape($cmd);
                   6747:     my $query = 'fetchenrollment';
1.620     albertel 6748:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526     raeburn  6749:     unless ($queryid=~/^\Q$host\E\_/) { 
                   6750:         &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum); 
                   6751:         return 'error: '.$queryid;
                   6752:     }
1.506     raeburn  6753:     my $reply = &get_query_reply($queryid);
1.547     raeburn  6754:     my $tries = 1;
                   6755:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   6756:         $reply = &get_query_reply($queryid);
                   6757:         $tries ++;
                   6758:     }
1.526     raeburn  6759:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620     albertel 6760:         &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526     raeburn  6761:     } else {
1.901     albertel 6762:         my @responses = split(/:/,$reply);
1.515     raeburn  6763:         if ($homeserver eq $perlvar{'lonHostID'}) {
1.800     albertel 6764:             foreach my $line (@responses) {
                   6765:                 my ($key,$value) = split(/=/,$line,2);
1.515     raeburn  6766:                 $$replyref{$key} = $value;
                   6767:             }
                   6768:         } else {
1.1117    foxr     6769:             my $pathname = LONCAPA::tempdir();
1.800     albertel 6770:             foreach my $line (@responses) {
                   6771:                 my ($key,$value) = split(/=/,$line);
1.506     raeburn  6772:                 $$replyref{$key} = $value;
                   6773:                 if ($value > 0) {
1.800     albertel 6774:                     foreach my $item (@{$$affiliatesref{$key}}) {
                   6775:                         my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506     raeburn  6776:                         my $destname = $pathname.'/'.$filename;
                   6777:                         my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526     raeburn  6778:                         if ($xml_classlist =~ /^error/) {
                   6779:                             &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
                   6780:                         } else {
1.506     raeburn  6781:                             if ( open(FILE,">$destname") ) {
                   6782:                                 print FILE &unescape($xml_classlist);
                   6783:                                 close(FILE);
1.526     raeburn  6784:                             } else {
                   6785:                                 &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506     raeburn  6786:                             }
                   6787:                         }
                   6788:                     }
                   6789:                 }
                   6790:             }
                   6791:         }
                   6792:         return 'ok';
                   6793:     }
                   6794:     return 'error';
                   6795: }
                   6796: 
1.242     www      6797: sub get_query_reply {
                   6798:     my $queryid=shift;
1.1117    foxr     6799:     my $replyfile=LONCAPA::tempdir().$queryid;
1.240     www      6800:     my $reply='';
                   6801:     for (1..100) {
                   6802: 	sleep 2;
                   6803:         if (-e $replyfile.'.end') {
1.448     albertel 6804: 	    if (open(my $fh,$replyfile)) {
1.904     albertel 6805: 		$reply = join('',<$fh>);
                   6806: 		close($fh);
1.240     www      6807: 	   } else { return 'error: reply_file_error'; }
1.242     www      6808:            return &unescape($reply);
                   6809: 	}
1.240     www      6810:     }
1.242     www      6811:     return 'timeout:'.$queryid;
1.240     www      6812: }
                   6813: 
                   6814: sub courselog_query {
1.241     www      6815: #
                   6816: # possible filters:
                   6817: # url: url or symb
                   6818: # username
                   6819: # domain
                   6820: # action: view, submit, grade
                   6821: # start: timestamp
                   6822: # end: timestamp
                   6823: #
1.240     www      6824:     my (%filters)=@_;
1.620     albertel 6825:     unless ($env{'request.course.id'}) { return 'no_course'; }
1.241     www      6826:     if ($filters{'url'}) {
                   6827: 	$filters{'url'}=&symbclean(&declutter($filters{'url'}));
                   6828:         $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
                   6829:         $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
                   6830:     }
1.620     albertel 6831:     my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
                   6832:     my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240     www      6833:     return &log_query($cname,$cdom,'courselog',%filters);
                   6834: }
                   6835: 
                   6836: sub userlog_query {
1.858     raeburn  6837: #
                   6838: # possible filters:
                   6839: # action: log check role
                   6840: # start: timestamp
                   6841: # end: timestamp
                   6842: #
1.240     www      6843:     my ($uname,$udom,%filters)=@_;
                   6844:     return &log_query($uname,$udom,'userlog',%filters);
1.12      www      6845: }
                   6846: 
1.506     raeburn  6847: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course 
                   6848: 
                   6849: sub auto_run {
1.508     raeburn  6850:     my ($cnum,$cdom) = @_;
1.876     raeburn  6851:     my $response = 0;
                   6852:     my $settings;
                   6853:     my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
                   6854:     if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   6855:         $settings = $domconfig{'autoenroll'};
                   6856:         if ($settings->{'run'} eq '1') {
                   6857:             $response = 1;
                   6858:         }
                   6859:     } else {
1.934     raeburn  6860:         my $homeserver;
                   6861:         if (&is_course($cdom,$cnum)) {
                   6862:             $homeserver = &homeserver($cnum,$cdom);
                   6863:         } else {
                   6864:             $homeserver = &domain($cdom,'primary');
                   6865:         }
                   6866:         if ($homeserver ne 'no_host') {
                   6867:             $response = &reply('autorun:'.$cdom,$homeserver);
                   6868:         }
1.876     raeburn  6869:     }
1.506     raeburn  6870:     return $response;
                   6871: }
1.776     albertel 6872: 
1.506     raeburn  6873: sub auto_get_sections {
1.508     raeburn  6874:     my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007    raeburn  6875:     my $homeserver;
                   6876:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) { 
                   6877:         $homeserver = &homeserver($cnum,$cdom);
                   6878:     }
                   6879:     if (!defined($homeserver)) { 
                   6880:         if ($cdom =~ /^$match_domain$/) {
                   6881:             $homeserver = &domain($cdom,'primary');
                   6882:         }
                   6883:     }
                   6884:     my @secs;
                   6885:     if (defined($homeserver)) {
                   6886:         my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
                   6887:         unless ($response eq 'refused') {
                   6888:             @secs = split(/:/,$response);
                   6889:         }
1.506     raeburn  6890:     }
                   6891:     return @secs;
                   6892: }
1.776     albertel 6893: 
1.506     raeburn  6894: sub auto_new_course {
1.1099    raeburn  6895:     my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508     raeburn  6896:     my $homeserver = &homeserver($cnum,$cdom);
1.1099    raeburn  6897:     my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506     raeburn  6898:     return $response;
                   6899: }
1.776     albertel 6900: 
1.506     raeburn  6901: sub auto_validate_courseID {
1.508     raeburn  6902:     my ($cnum,$cdom,$inst_course_id) = @_;
                   6903:     my $homeserver = &homeserver($cnum,$cdom);
1.511     raeburn  6904:     my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506     raeburn  6905:     return $response;
                   6906: }
1.776     albertel 6907: 
1.1007    raeburn  6908: sub auto_validate_instcode {
1.1020    raeburn  6909:     my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007    raeburn  6910:     my ($homeserver,$response);
                   6911:     if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6912:         $homeserver = &homeserver($cnum,$cdom);
                   6913:     }
                   6914:     if (!defined($homeserver)) {
                   6915:         if ($cdom =~ /^$match_domain$/) {
                   6916:             $homeserver = &domain($cdom,'primary');
                   6917:         }
                   6918:     }
1.1065    raeburn  6919:     $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
                   6920:                         &escape($instcode).':'.&escape($owner),$homeserver));
1.1027    raeburn  6921:     my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
                   6922:     return ($outcome,$description);
1.1007    raeburn  6923: }
                   6924: 
1.506     raeburn  6925: sub auto_create_password {
1.873     raeburn  6926:     my ($cnum,$cdom,$authparam,$udom) = @_;
                   6927:     my ($homeserver,$response);
1.506     raeburn  6928:     my $create_passwd = 0;
                   6929:     my $authchk = '';
1.873     raeburn  6930:     if ($udom =~ /^$match_domain$/) {
                   6931:         $homeserver = &domain($udom,'primary');
                   6932:     }
                   6933:     if ($homeserver eq '') {
                   6934:         if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
                   6935:             $homeserver = &homeserver($cnum,$cdom);
                   6936:         }
                   6937:     }
                   6938:     if ($homeserver eq '') {
                   6939:         $authchk = 'nodomain';
1.506     raeburn  6940:     } else {
1.873     raeburn  6941:         $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
                   6942:         if ($response eq 'refused') {
                   6943:             $authchk = 'refused';
                   6944:         } else {
1.901     albertel 6945:             ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873     raeburn  6946:         }
1.506     raeburn  6947:     }
                   6948:     return ($authparam,$create_passwd,$authchk);
                   6949: }
                   6950: 
1.706     raeburn  6951: sub auto_photo_permission {
                   6952:     my ($cnum,$cdom,$students) = @_;
                   6953:     my $homeserver = &homeserver($cnum,$cdom);
1.707     albertel 6954:     my ($outcome,$perm_reqd,$conditions) = 
                   6955: 	split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709     albertel 6956:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6957: 	return (undef,undef);
                   6958:     }
1.706     raeburn  6959:     return ($outcome,$perm_reqd,$conditions);
                   6960: }
                   6961: 
                   6962: sub auto_checkphotos {
                   6963:     my ($uname,$udom,$pid) = @_;
                   6964:     my $homeserver = &homeserver($uname,$udom);
                   6965:     my ($result,$resulttype);
                   6966:     my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707     albertel 6967: 				   &escape($uname).':'.&escape($pid),
                   6968: 				   $homeserver));
1.709     albertel 6969:     if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6970: 	return (undef,undef);
                   6971:     }
1.706     raeburn  6972:     if ($outcome) {
                   6973:         ($result,$resulttype) = split(/:/,$outcome);
                   6974:     } 
                   6975:     return ($result,$resulttype);
                   6976: }
                   6977: 
                   6978: sub auto_photochoice {
                   6979:     my ($cnum,$cdom) = @_;
                   6980:     my $homeserver = &homeserver($cnum,$cdom);
                   6981:     my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707     albertel 6982: 						       &escape($cdom),
                   6983: 						       $homeserver)));
1.709     albertel 6984:     if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
                   6985: 	return (undef,undef);
                   6986:     }
1.706     raeburn  6987:     return ($update,$comment);
                   6988: }
                   6989: 
                   6990: sub auto_photoupdate {
                   6991:     my ($affiliatesref,$dom,$cnum,$photo) = @_;
                   6992:     my $homeserver = &homeserver($cnum,$dom);
1.838     albertel 6993:     my $host=&hostname($homeserver);
1.706     raeburn  6994:     my $cmd = '';
                   6995:     my $maxtries = 1;
1.800     albertel 6996:     foreach my $affiliate (keys(%{$affiliatesref})) {
                   6997:         $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706     raeburn  6998:     }
                   6999:     $cmd =~ s/%%$//;
                   7000:     $cmd = &escape($cmd);
                   7001:     my $query = 'institutionalphotos';
                   7002:     my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
                   7003:     unless ($queryid=~/^\Q$host\E\_/) {
                   7004:         &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
                   7005:         return 'error: '.$queryid;
                   7006:     }
                   7007:     my $reply = &get_query_reply($queryid);
                   7008:     my $tries = 1;
                   7009:     while (($reply=~/^timeout/) && ($tries < $maxtries)) {
                   7010:         $reply = &get_query_reply($queryid);
                   7011:         $tries ++;
                   7012:     }
                   7013:     if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
                   7014:         &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
                   7015:     } else {
                   7016:         my @responses = split(/:/,$reply);
                   7017:         my $outcome = shift(@responses); 
                   7018:         foreach my $item (@responses) {
                   7019:             my ($key,$value) = split(/=/,$item);
                   7020:             $$photo{$key} = $value;
                   7021:         }
                   7022:         return $outcome;
                   7023:     }
                   7024:     return 'error';
                   7025: }
                   7026: 
1.521     raeburn  7027: sub auto_instcode_format {
1.793     albertel 7028:     my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
                   7029: 	$cat_order) = @_;
1.521     raeburn  7030:     my $courses = '';
1.772     raeburn  7031:     my @homeservers;
1.521     raeburn  7032:     if ($caller eq 'global') {
1.841     albertel 7033: 	my %servers = &get_servers($codedom,'library');
                   7034: 	foreach my $tryserver (keys(%servers)) {
                   7035: 	    if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7036: 		push(@homeservers,$tryserver);
                   7037: 	    }
1.584     raeburn  7038:         }
1.1022    raeburn  7039:     } elsif ($caller eq 'requests') {
                   7040:         if ($codedom =~ /^$match_domain$/) {
                   7041:             my $chome = &domain($codedom,'primary');
                   7042:             unless ($chome eq 'no_host') {
                   7043:                 push(@homeservers,$chome);
                   7044:             }
                   7045:         }
1.521     raeburn  7046:     } else {
1.772     raeburn  7047:         push(@homeservers,&homeserver($caller,$codedom));
1.521     raeburn  7048:     }
1.793     albertel 7049:     foreach my $code (keys(%{$instcodes})) {
                   7050:         $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521     raeburn  7051:     }
                   7052:     chop($courses);
1.772     raeburn  7053:     my $ok_response = 0;
                   7054:     my $response;
                   7055:     while (@homeservers > 0 && $ok_response == 0) {
                   7056:         my $server = shift(@homeservers); 
                   7057:         $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
                   7058:         if ($response !~ /(con_lost|error|no_such_host|refused)/) {
                   7059:             my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) = 
1.901     albertel 7060: 		split(/:/,$response);
1.772     raeburn  7061:             %{$codes} = (%{$codes},&str2hash($codes_str));
                   7062:             push(@{$codetitles},&str2array($codetitles_str));
                   7063:             %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
                   7064:             %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
                   7065:             $ok_response = 1;
                   7066:         }
                   7067:     }
                   7068:     if ($ok_response) {
1.521     raeburn  7069:         return 'ok';
1.772     raeburn  7070:     } else {
                   7071:         return $response;
1.521     raeburn  7072:     }
                   7073: }
                   7074: 
1.792     raeburn  7075: sub auto_instcode_defaults {
                   7076:     my ($domain,$returnhash,$code_order) = @_;
                   7077:     my @homeservers;
1.841     albertel 7078: 
                   7079:     my %servers = &get_servers($domain,'library');
                   7080:     foreach my $tryserver (keys(%servers)) {
                   7081: 	if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7082: 	    push(@homeservers,$tryserver);
                   7083: 	}
1.792     raeburn  7084:     }
1.841     albertel 7085: 
1.792     raeburn  7086:     my $response;
1.841     albertel 7087:     foreach my $server (@homeservers) {
1.792     raeburn  7088:         $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841     albertel 7089:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
                   7090: 	
                   7091: 	foreach my $pair (split(/\&/,$response)) {
                   7092: 	    my ($name,$value)=split(/\=/,$pair);
                   7093: 	    if ($name eq 'code_order') {
                   7094: 		@{$code_order} = split(/\&/,&unescape($value));
                   7095: 	    } else {
                   7096: 		$returnhash->{&unescape($name)}=&unescape($value);
                   7097: 	    }
                   7098: 	}
                   7099: 	return 'ok';
1.792     raeburn  7100:     }
1.841     albertel 7101: 
                   7102:     return $response;
1.1003    raeburn  7103: }
                   7104: 
                   7105: sub auto_possible_instcodes {
1.1007    raeburn  7106:     my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
                   7107:     unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') && 
                   7108:             (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
                   7109:         return;
                   7110:     }
1.1003    raeburn  7111:     my (@homeservers,$uhome);
                   7112:     if (defined(&domain($domain,'primary'))) {
                   7113:         $uhome=&domain($domain,'primary');
                   7114:         push(@homeservers,&domain($domain,'primary'));
                   7115:     } else {
                   7116:         my %servers = &get_servers($domain,'library');
                   7117:         foreach my $tryserver (keys(%servers)) {
                   7118:             if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
                   7119:                 push(@homeservers,$tryserver);
                   7120:             }
                   7121:         }
                   7122:     }
                   7123:     my $response;
                   7124:     foreach my $server (@homeservers) {
                   7125:         $response=&reply('autopossibleinstcodes:'.$domain,$server);
                   7126:         next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007    raeburn  7127:         my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) = 
                   7128:             split(':',$response);
                   7129:         @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
                   7130:         @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003    raeburn  7131:         foreach my $item (split('&',$cat_title)) {   
1.1005    raeburn  7132:             my ($name,$value)=split('=',$item);
                   7133:             $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7134:         }
                   7135:         foreach my $item (split('&',$cat_order)) {
1.1005    raeburn  7136:             my ($name,$value)=split('=',$item);
                   7137:             $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003    raeburn  7138:         }
                   7139:         return 'ok';
                   7140:     }
                   7141:     return $response;
                   7142: }
1.792     raeburn  7143: 
1.1010    raeburn  7144: sub auto_courserequest_checks {
                   7145:     my ($dom) = @_;
1.1020    raeburn  7146:     my ($homeserver,%validations);
                   7147:     if ($dom =~ /^$match_domain$/) {
                   7148:         $homeserver = &domain($dom,'primary');
                   7149:     }
                   7150:     unless ($homeserver eq 'no_host') {
                   7151:         my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
                   7152:         unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
                   7153:             my @items = split(/&/,$response);
                   7154:             foreach my $item (@items) {
                   7155:                 my ($key,$value) = split('=',$item);
                   7156:                 $validations{&unescape($key)} = &thaw_unescape($value);
                   7157:             }
                   7158:         }
                   7159:     }
1.1010    raeburn  7160:     return %validations; 
                   7161: }
                   7162: 
1.1020    raeburn  7163: sub auto_courserequest_validation {
                   7164:     my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
                   7165:     my ($homeserver,$response);
                   7166:     if ($dom =~ /^$match_domain$/) {
                   7167:         $homeserver = &domain($dom,'primary');
                   7168:     }
                   7169:     unless ($homeserver eq 'no_host') {  
1.1021    raeburn  7170:           
1.1020    raeburn  7171:         $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021    raeburn  7172:                                     ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020    raeburn  7173:                                     ':'.&escape($instcode).':'.&escape($instseclist),
                   7174:                                     $homeserver));
                   7175:     }
                   7176:     return $response;
                   7177: }
                   7178: 
1.777     albertel 7179: sub auto_validate_class_sec {
1.918     raeburn  7180:     my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773     raeburn  7181:     my $homeserver = &homeserver($cnum,$cdom);
1.918     raeburn  7182:     my $ownerlist;
                   7183:     if (ref($owners) eq 'ARRAY') {
                   7184:         $ownerlist = join(',',@{$owners});
                   7185:     } else {
                   7186:         $ownerlist = $owners;
                   7187:     }
1.773     raeburn  7188:     my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918     raeburn  7189:                         &escape($ownerlist).':'.$cdom,$homeserver);
1.773     raeburn  7190:     return $response;
                   7191: }
                   7192: 
1.679     raeburn  7193: # ------------------------------------------------------- Course Group routines
                   7194: 
                   7195: sub get_coursegroups {
1.809     raeburn  7196:     my ($cdom,$cnum,$group,$namespace) = @_;
                   7197:     return(&dump($namespace,$cdom,$cnum,$group));
1.805     raeburn  7198: }
                   7199: 
1.679     raeburn  7200: sub modify_coursegroup {
                   7201:     my ($cdom,$cnum,$groupsettings) = @_;
                   7202:     return(&put('coursegroups',$groupsettings,$cdom,$cnum));
                   7203: }
                   7204: 
1.809     raeburn  7205: sub toggle_coursegroup_status {
                   7206:     my ($cdom,$cnum,$group,$action) = @_;
                   7207:     my ($from_namespace,$to_namespace);
                   7208:     if ($action eq 'delete') {
                   7209:         $from_namespace = 'coursegroups';
                   7210:         $to_namespace = 'deleted_groups';
                   7211:     } else {
                   7212:         $from_namespace = 'deleted_groups';
                   7213:         $to_namespace = 'coursegroups';
                   7214:     }
                   7215:     my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805     raeburn  7216:     if (my $tmp = &error(%curr_group)) {
                   7217:         &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
                   7218:         return ('read error',$tmp);
                   7219:     } else {
                   7220:         my %savedsettings = %curr_group; 
1.809     raeburn  7221:         my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805     raeburn  7222:         my $deloutcome;
                   7223:         if ($result eq 'ok') {
1.809     raeburn  7224:             $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805     raeburn  7225:         } else {
                   7226:             return ('write error',$result);
                   7227:         }
                   7228:         if ($deloutcome eq 'ok') {
                   7229:             return 'ok';
                   7230:         } else {
                   7231:             return ('delete error',$deloutcome);
                   7232:         }
                   7233:     }
                   7234: }
                   7235: 
1.679     raeburn  7236: sub modify_group_roles {
1.957     raeburn  7237:     my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679     raeburn  7238:     my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
                   7239:     my $role = 'gr/'.&escape($userprivs);
                   7240:     my ($uname,$udom) = split(/:/,$user);
1.957     raeburn  7241:     my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684     raeburn  7242:     if ($result eq 'ok') {
                   7243:         &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
                   7244:     }
1.679     raeburn  7245:     return $result;
                   7246: }
                   7247: 
                   7248: sub modify_coursegroup_membership {
                   7249:     my ($cdom,$cnum,$membership) = @_;
                   7250:     my $result = &put('groupmembership',$membership,$cdom,$cnum);
                   7251:     return $result;
                   7252: }
                   7253: 
1.682     raeburn  7254: sub get_active_groups {
                   7255:     my ($udom,$uname,$cdom,$cnum) = @_;
                   7256:     my $now = time;
                   7257:     my %groups = ();
                   7258:     foreach my $key (keys(%env)) {
1.811     albertel 7259:         if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682     raeburn  7260:             my ($start,$end) = split(/\./,$env{$key});
                   7261:             if (($end!=0) && ($end<$now)) { next; }
                   7262:             if (($start!=0) && ($start>$now)) { next; }
                   7263:             if ($1 eq $cdom && $2 eq $cnum) {
                   7264:                 $groups{$3} = $env{$key} ;
                   7265:             }
                   7266:         }
                   7267:     }
                   7268:     return %groups;
                   7269: }
                   7270: 
1.683     raeburn  7271: sub get_group_membership {
                   7272:     my ($cdom,$cnum,$group) = @_;
                   7273:     return(&dump('groupmembership',$cdom,$cnum,$group));
                   7274: }
                   7275: 
                   7276: sub get_users_groups {
                   7277:     my ($udom,$uname,$courseid) = @_;
1.733     raeburn  7278:     my @usersgroups;
1.683     raeburn  7279:     my $cachetime=1800;
                   7280: 
                   7281:     my $hashid="$udom:$uname:$courseid";
1.733     raeburn  7282:     my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
                   7283:     if (defined($cached)) {
1.734     albertel 7284:         @usersgroups = split(/:/,$grouplist);
1.733     raeburn  7285:     } else {  
                   7286:         $grouplist = '';
1.816     raeburn  7287:         my $courseurl = &courseid_to_courseurl($courseid);
1.1166    raeburn  7288:         my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817     raeburn  7289:         my $access_end = $env{'course.'.$courseid.
                   7290:                               '.default_enrollment_end_date'};
                   7291:         my $now = time;
                   7292:         foreach my $key (keys(%roleshash)) {
                   7293:             if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
                   7294:                 my $group = $1;
                   7295:                 if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
                   7296:                     my $start = $2;
                   7297:                     my $end = $1;
                   7298:                     if ($start == -1) { next; } # deleted from group
                   7299:                     if (($start!=0) && ($start>$now)) { next; }
                   7300:                     if (($end!=0) && ($end<$now)) {
                   7301:                         if ($access_end && $access_end < $now) {
                   7302:                             if ($access_end - $end < 86400) {
                   7303:                                 push(@usersgroups,$group);
1.733     raeburn  7304:                             }
                   7305:                         }
1.817     raeburn  7306:                         next;
1.733     raeburn  7307:                     }
1.817     raeburn  7308:                     push(@usersgroups,$group);
1.683     raeburn  7309:                 }
                   7310:             }
                   7311:         }
1.817     raeburn  7312:         @usersgroups = &sort_course_groups($courseid,@usersgroups);
                   7313:         $grouplist = join(':',@usersgroups);
                   7314:         &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683     raeburn  7315:     }
1.733     raeburn  7316:     return @usersgroups;
1.683     raeburn  7317: }
                   7318: 
                   7319: sub devalidate_getgroups_cache {
                   7320:     my ($udom,$uname,$cdom,$cnum)=@_;
                   7321:     my $courseid = $cdom.'_'.$cnum;
1.807     albertel 7322: 
1.683     raeburn  7323:     my $hashid="$udom:$uname:$courseid";
                   7324:     &devalidate_cache_new('getgroups',$hashid);
                   7325: }
                   7326: 
1.12      www      7327: # ------------------------------------------------------------------ Plain Text
                   7328: 
                   7329: sub plaintext {
1.988     raeburn  7330:     my ($short,$type,$cid,$forcedefault) = @_;
1.1046    raeburn  7331:     if ($short =~ m{^cr/}) {
1.758     albertel 7332: 	return (split('/',$short))[-1];
                   7333:     }
1.742     raeburn  7334:     if (!defined($cid)) {
                   7335:         $cid = $env{'request.course.id'};
                   7336:     }
                   7337:     my %rolenames = (
1.1008    raeburn  7338:                       Course    => 'std',
                   7339:                       Community => 'alt1',
1.742     raeburn  7340:                     );
1.1037    raeburn  7341:     if ($cid ne '') {
                   7342:         if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
                   7343:             unless ($forcedefault) {
                   7344:                 my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'}; 
                   7345:                 &Apache::lonlocal::mt_escape(\$roletext);
                   7346:                 return &Apache::lonlocal::mt($roletext);
                   7347:             }
                   7348:         }
                   7349:     }
                   7350:     if ((defined($type)) && (defined($rolenames{$type})) &&
                   7351:         (defined($rolenames{$type})) && 
                   7352:         (defined($prp{$short}{$rolenames{$type}}))) {
1.742     raeburn  7353:         return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037    raeburn  7354:     } elsif ($cid ne '') {
                   7355:         my $crstype = $env{'course.'.$cid.'.type'};
                   7356:         if (($crstype ne '') && (defined($rolenames{$crstype})) &&
                   7357:             (defined($prp{$short}{$rolenames{$crstype}}))) {
                   7358:             return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
                   7359:         }
1.742     raeburn  7360:     }
1.1037    raeburn  7361:     return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12      www      7362: }
                   7363: 
                   7364: # ----------------------------------------------------------------- Assign Role
                   7365: 
                   7366: sub assignrole {
1.957     raeburn  7367:     my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
                   7368:         $context)=@_;
1.21      www      7369:     my $mrole;
                   7370:     if ($role =~ /^cr\//) {
1.393     www      7371:         my $cwosec=$url;
1.811     albertel 7372:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393     www      7373: 	unless (&allowed('ccr',$cwosec)) {
1.1026    raeburn  7374:            my $refused = 1;
                   7375:            if ($context eq 'requestcourses') {
                   7376:                if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
                   7377:                    if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
                   7378:                        if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
                   7379:                            my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7380:                            my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7381:                            if ($crsenv{'internal.courseowner'} eq
                   7382:                                $env{'user.name'}.':'.$env{'user.domain'}) {
                   7383:                                $refused = '';
                   7384:                            }
                   7385:                        }
                   7386:                    }
                   7387:                }
                   7388:            }
                   7389:            if ($refused) {
                   7390:                &logthis('Refused custom assignrole: '.
                   7391:                         $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
                   7392:                         ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
                   7393:                return 'refused';
                   7394:            }
1.104     www      7395:         }
1.21      www      7396:         $mrole='cr';
1.678     raeburn  7397:     } elsif ($role =~ /^gr\//) {
                   7398:         my $cwogrp=$url;
1.811     albertel 7399:         $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678     raeburn  7400:         unless (&allowed('mdg',$cwogrp)) {
                   7401:             &logthis('Refused group assignrole: '.
                   7402:               $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
                   7403:                     $env{'user.name'}.' at '.$env{'user.domain'});
                   7404:             return 'refused';
                   7405:         }
                   7406:         $mrole='gr';
1.21      www      7407:     } else {
1.82      www      7408:         my $cwosec=$url;
1.811     albertel 7409:         $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932     raeburn  7410:         if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
                   7411:             my $refused;
                   7412:             if (($env{'request.course.sec'}  ne '') && ($role eq 'st')) {
                   7413:                 if (!(&allowed('c'.$role,$url))) {
                   7414:                     $refused = 1;
                   7415:                 }
                   7416:             } else {
                   7417:                 $refused = 1;
                   7418:             }
1.947     raeburn  7419:             if ($refused) {
1.1045    raeburn  7420:                 my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
                   7421:                 if (!$selfenroll && $context eq 'course') {
                   7422:                     my %crsenv;
                   7423:                     if ($role eq 'cc' || $role eq 'co') {
                   7424:                         %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7425:                         if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
                   7426:                             if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
                   7427:                                 if ($crsenv{'internal.courseowner'} eq 
                   7428:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7429:                                     $refused = '';
                   7430:                                 }
                   7431:                             }
                   7432:                         } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) { 
                   7433:                             if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
                   7434:                                 if ($crsenv{'internal.courseowner'} eq 
                   7435:                                     $env{'user.name'}.':'.$env{'user.domain'}) {
                   7436:                                     $refused = '';
                   7437:                                 }
                   7438:                             }
                   7439:                         }
                   7440:                     }
                   7441:                 } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947     raeburn  7442:                     $refused = '';
1.1017    raeburn  7443:                 } elsif ($context eq 'requestcourses') {
1.1041    raeburn  7444:                     my @possroles = ('st','ta','ep','in','cc','co');
1.1026    raeburn  7445:                     if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041    raeburn  7446:                         my $wrongcc;
                   7447:                         if ($cnum =~ /^$match_community$/) {
                   7448:                             $wrongcc = 1 if ($role eq 'cc');
                   7449:                         } else {
                   7450:                             $wrongcc = 1 if ($role eq 'co');
                   7451:                         }
                   7452:                         unless ($wrongcc) {
                   7453:                             my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
                   7454:                             if ($crsenv{'internal.courseowner'} eq 
                   7455:                                  $env{'user.name'}.':'.$env{'user.domain'}) {
                   7456:                                 $refused = '';
                   7457:                             }
1.1017    raeburn  7458:                         }
                   7459:                     }
                   7460:                 }
                   7461:                 if ($refused) {
1.947     raeburn  7462:                     &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
                   7463:                              ' '.$role.' '.$end.' '.$start.' by '.
                   7464: 	  	             $env{'user.name'}.' at '.$env{'user.domain'});
                   7465:                     return 'refused';
                   7466:                 }
1.932     raeburn  7467:             }
1.1131    raeburn  7468:         } elsif ($role eq 'au') {
                   7469:             if ($url ne '/'.$udom.'/') {
                   7470:                 &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
                   7471:                          ' to assign author role for '.$uname.':'.$udom.
                   7472:                          ' in domain: '.$url.' refused (wrong domain).');
                   7473:                 return 'refused';
                   7474:             }
1.104     www      7475:         }
1.21      www      7476:         $mrole=$role;
                   7477:     }
1.620     albertel 7478:     my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21      www      7479:                 "$udom:$uname:$url".'_'."$mrole=$role";
1.81      www      7480:     if ($end) { $command.='_'.$end; }
1.21      www      7481:     if ($start) {
                   7482: 	if ($end) { 
1.81      www      7483:            $command.='_'.$start; 
1.21      www      7484:         } else {
1.81      www      7485:            $command.='_0_'.$start;
1.21      www      7486:         }
                   7487:     }
1.739     raeburn  7488:     my $origstart = $start;
                   7489:     my $origend = $end;
1.957     raeburn  7490:     my $delflag;
1.357     www      7491: # actually delete
                   7492:     if ($deleteflag) {
1.373     www      7493: 	if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357     www      7494: # modify command to delete the role
1.620     albertel 7495:            $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357     www      7496:                 "$udom:$uname:$url".'_'."$mrole";
1.620     albertel 7497: 	   &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom"); 
1.357     www      7498: # set start and finish to negative values for userrolelog
                   7499:            $start=-1;
                   7500:            $end=-1;
1.957     raeburn  7501:            $delflag = 1;
1.357     www      7502:         }
                   7503:     }
                   7504: # send command
1.349     www      7505:     my $answer=&reply($command,&homeserver($uname,$udom));
1.357     www      7506: # log new user role if status is ok
1.349     www      7507:     if ($answer eq 'ok') {
1.663     raeburn  7508: 	&userrolelog($role,$uname,$udom,$url,$start,$end);
1.739     raeburn  7509: # for course roles, perform group memberships changes triggered by role change.
1.957     raeburn  7510:         &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739     raeburn  7511:         unless ($role =~ /^gr/) {
                   7512:             &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957     raeburn  7513:                                              $origstart,$selfenroll,$context);
1.739     raeburn  7514:         }
1.1053    raeburn  7515:         if ($role eq 'cc') {
                   7516:             &autoupdate_coowners($url,$end,$start,$uname,$udom);
                   7517:         }
1.349     www      7518:     }
                   7519:     return $answer;
1.169     harris41 7520: }
                   7521: 
1.1053    raeburn  7522: sub autoupdate_coowners {
                   7523:     my ($url,$end,$start,$uname,$udom) = @_;
                   7524:     my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
                   7525:     if (($cdom ne '') && ($cnum ne '')) {
                   7526:         my $now = time;
                   7527:         my %domdesign = &Apache::loncommon::get_domainconf($cdom);
                   7528:         if ($domdesign{$cdom.'.autoassign.co-owners'}) {
                   7529:             my %coursehash = &coursedescription($cdom.'_'.$cnum);
                   7530:             my $instcode = $coursehash{'internal.coursecode'};
                   7531:             if ($instcode ne '') {
1.1056    raeburn  7532:                 if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
                   7533:                     unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053    raeburn  7534:                         my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056    raeburn  7535:                         my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
                   7536:                         if ($result eq 'valid') {
                   7537:                             if ($coursehash{'internal.co-owners'}) {
1.1053    raeburn  7538:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7539:                                     push(@newcoowners,$coowner);
                   7540:                                 }
                   7541:                                 unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
                   7542:                                     push(@newcoowners,$uname.':'.$udom);
                   7543:                                 }
                   7544:                                 @newcoowners = sort(@newcoowners);
                   7545:                             } else {
                   7546:                                 push(@newcoowners,$uname.':'.$udom);
                   7547:                             }
                   7548:                         } else {
                   7549:                             if ($coursehash{'internal.co-owners'}) {
                   7550:                                 foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
                   7551:                                     unless ($coowner eq $uname.':'.$udom) {
                   7552:                                         push(@newcoowners,$coowner);
                   7553:                                     }
                   7554:                                 }
                   7555:                                 unless (@newcoowners > 0) {
                   7556:                                     $delcoowners = 1;
                   7557:                                     $coowners = '';
                   7558:                                 }
                   7559:                             }
                   7560:                         }
                   7561:                         if (@newcoowners || $delcoowners) {
                   7562:                             &store_coowners($cdom,$cnum,$coursehash{'home'},
                   7563:                                             $delcoowners,@newcoowners);
                   7564:                         }
                   7565:                     }
                   7566:                 }
                   7567:             }
                   7568:         }
                   7569:     }
                   7570: }
                   7571: 
                   7572: sub store_coowners {
                   7573:     my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
                   7574:     my $cid = $cdom.'_'.$cnum;
                   7575:     my ($coowners,$delresult,$putresult);
                   7576:     if (@newcoowners) {
                   7577:         $coowners = join(',',@newcoowners);
                   7578:         my %coownershash = (
                   7579:                             'internal.co-owners' => $coowners,
                   7580:                            );
                   7581:         $putresult = &put('environment',\%coownershash,$cdom,$cnum);
                   7582:         if ($putresult eq 'ok') {
                   7583:             if ($env{'course.'.$cid.'.num'} eq $cnum) {
                   7584:                 &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
                   7585:             }
                   7586:         }
                   7587:     }
                   7588:     if ($delcoowners) {
                   7589:         $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
                   7590:         if ($delresult eq 'ok') {
                   7591:             if ($env{'course.'.$cid.'.internal.co-owners'}) {
                   7592:                 &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
                   7593:             }
                   7594:         }
                   7595:     }
                   7596:     if (($putresult eq 'ok') || ($delresult eq 'ok')) {
                   7597:         my %crsinfo =
                   7598:             &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
                   7599:         if (ref($crsinfo{$cid}) eq 'HASH') {
                   7600:             $crsinfo{$cid}{'co-owners'} = \@newcoowners;
                   7601:             my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
                   7602:         }
                   7603:     }
                   7604: }
                   7605: 
1.169     harris41 7606: # -------------------------------------------------- Modify user authentication
1.197     www      7607: # Overrides without validation
                   7608: 
1.169     harris41 7609: sub modifyuserauth {
                   7610:     my ($udom,$uname,$umode,$upass)=@_;
                   7611:     my $uhome=&homeserver($uname,$udom);
1.197     www      7612:     unless (&allowed('mau',$udom)) { return 'refused'; }
                   7613:     &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620     albertel 7614:              $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7615:              ' in domain '.$env{'request.role.domain'});  
1.169     harris41 7616:     my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
                   7617: 		     &escape($upass),$uhome);
1.620     albertel 7618:     &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197     www      7619:         'Authentication changed for '.$udom.', '.$uname.', '.$umode.
                   7620:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
                   7621:     &log($udom,,$uname,$uhome,
1.620     albertel 7622:         'Authentication changed by '.$env{'user.domain'}.', '.
                   7623:                                      $env{'user.name'}.', '.$umode.
1.197     www      7624:          '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169     harris41 7625:     unless ($reply eq 'ok') {
1.197     www      7626:         &logthis('Authentication mode error: '.$reply);
1.169     harris41 7627: 	return 'error: '.$reply;
                   7628:     }   
1.170     harris41 7629:     return 'ok';
1.80      www      7630: }
                   7631: 
1.81      www      7632: # --------------------------------------------------------------- Modify a user
1.80      www      7633: 
1.81      www      7634: sub modifyuser {
1.206     matthew  7635:     my ($udom,    $uname, $uid,
                   7636:         $umode,   $upass, $first,
                   7637:         $middle,  $last,  $gene,
1.1058    raeburn  7638:         $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807     albertel 7639:     $udom= &LONCAPA::clean_domain($udom);
                   7640:     $uname=&LONCAPA::clean_username($uname);
1.1059    raeburn  7641:     my $showcandelete = 'none';
                   7642:     if (ref($candelete) eq 'ARRAY') {
                   7643:         if (@{$candelete} > 0) {
                   7644:             $showcandelete = join(', ',@{$candelete});
                   7645:         }
                   7646:     }
1.81      www      7647:     &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80      www      7648:              $umode.', '.$first.', '.$middle.', '.
1.1059    raeburn  7649: 	     $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206     matthew  7650:              (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
                   7651:                                      ' desiredhome not specified'). 
1.620     albertel 7652:              ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
                   7653:              ' in domain '.$env{'request.role.domain'});
1.230     stredwic 7654:     my $uhome=&homeserver($uname,$udom,'true');
1.1075    raeburn  7655:     my $newuser;
                   7656:     if ($uhome eq 'no_host') {
                   7657:         $newuser = 1;
                   7658:     }
1.80      www      7659: # ----------------------------------------------------------------- Create User
1.406     albertel 7660:     if (($uhome eq 'no_host') && 
                   7661: 	(($umode && $upass) || ($umode eq 'localauth'))) {
1.80      www      7662:         my $unhome='';
1.844     albertel 7663:         if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) { 
1.209     matthew  7664:             $unhome = $desiredhome;
1.620     albertel 7665: 	} elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
                   7666: 	    $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209     matthew  7667:         } else { # load balancing routine for determining $unhome
1.81      www      7668:             my $loadm=10000000;
1.841     albertel 7669: 	    my %servers = &get_servers($udom,'library');
                   7670: 	    foreach my $tryserver (keys(%servers)) {
                   7671: 		my $answer=reply('load',$tryserver);
                   7672: 		if (($answer=~/\d+/) && ($answer<$loadm)) {
                   7673: 		    $loadm=$answer;
                   7674: 		    $unhome=$tryserver;
                   7675: 		}
1.80      www      7676: 	    }
                   7677:         }
                   7678:         if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206     matthew  7679: 	    return 'error: unable to find a home server for '.$uname.
                   7680:                    ' in domain '.$udom;
1.80      www      7681:         }
                   7682:         my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
                   7683:                          &escape($upass),$unhome);
                   7684: 	unless ($reply eq 'ok') {
                   7685:             return 'error: '.$reply;
                   7686:         }   
1.230     stredwic 7687:         $uhome=&homeserver($uname,$udom,'true');
1.80      www      7688:         if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386     matthew  7689: 	    return 'error: unable verify users home machine.';
1.80      www      7690:         }
1.209     matthew  7691:     }   # End of creation of new user
1.80      www      7692: # ---------------------------------------------------------------------- Add ID
                   7693:     if ($uid) {
                   7694:        $uid=~tr/A-Z/a-z/;
                   7695:        my %uidhash=&idrget($udom,$uname);
1.196     www      7696:        if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/) 
                   7697:          && (!$forceid)) {
1.80      www      7698: 	  unless ($uid eq $uidhash{$uname}) {
1.386     matthew  7699: 	      return 'error: user id "'.$uid.'" does not match '.
                   7700:                   'current user id "'.$uidhash{$uname}.'".';
1.80      www      7701:           }
                   7702:        } else {
                   7703: 	  &idput($udom,($uname => $uid));
                   7704:        }
                   7705:     }
                   7706: # -------------------------------------------------------------- Add names, etc
1.313     matthew  7707:     my @tmp=&get('environment',
1.899     raeburn  7708: 		   ['firstname','middlename','lastname','generation','id',
1.963     raeburn  7709:                     'permanentemail','inststatus'],
1.134     albertel 7710: 		   $udom,$uname);
1.1075    raeburn  7711:     my (%names,%oldnames);
1.313     matthew  7712:     if ($tmp[0] =~ m/^error:.*/) { 
                   7713:         %names=(); 
                   7714:     } else {
                   7715:         %names = @tmp;
1.1075    raeburn  7716:         %oldnames = %names;
1.313     matthew  7717:     }
1.388     www      7718: #
1.1058    raeburn  7719: # If name, email and/or uid are blank (e.g., because an uploaded file
                   7720: # of users did not contain them), do not overwrite existing values
                   7721: # unless field is in $candelete array ref.  
                   7722: #
                   7723: 
                   7724:     my @fields = ('firstname','middlename','lastname','generation',
                   7725:                   'permanentemail','id');
                   7726:     my %newvalues;
                   7727:     if (ref($candelete) eq 'ARRAY') {
                   7728:         foreach my $field (@fields) {
                   7729:             if (grep(/^\Q$field\E$/,@{$candelete})) {
                   7730:                 if ($field eq 'firstname') {
                   7731:                     $names{$field} = $first;
                   7732:                 } elsif ($field eq 'middlename') {
                   7733:                     $names{$field} = $middle;
                   7734:                 } elsif ($field eq 'lastname') {
                   7735:                     $names{$field} = $last;
                   7736:                 } elsif ($field eq 'generation') { 
                   7737:                     $names{$field} = $gene;
                   7738:                 } elsif ($field eq 'permanentemail') {
                   7739:                     $names{$field} = $email;
                   7740:                 } elsif ($field eq 'id') {
                   7741:                     $names{$field}  = $uid;
                   7742:                 }
                   7743:             }
                   7744:         }
                   7745:     }
1.388     www      7746:     if ($first)  { $names{'firstname'}  = $first; }
1.385     matthew  7747:     if (defined($middle)) { $names{'middlename'} = $middle; }
1.388     www      7748:     if ($last)   { $names{'lastname'}   = $last; }
1.385     matthew  7749:     if (defined($gene))   { $names{'generation'} = $gene; }
1.592     www      7750:     if ($email) {
                   7751:        $email=~s/[^\w\@\.\-\,]//gs;
1.963     raeburn  7752:        if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592     www      7753:     }
1.899     raeburn  7754:     if ($uid) { $names{'id'}  = $uid; }
1.989     raeburn  7755:     if (defined($inststatus)) {
                   7756:         $names{'inststatus'} = '';
                   7757:         my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
                   7758:         if (ref($usertypes) eq 'HASH') {
                   7759:             my @okstatuses; 
                   7760:             foreach my $item (split(/:/,$inststatus)) {
                   7761:                 if (defined($usertypes->{$item})) {
                   7762:                     push(@okstatuses,$item);  
                   7763:                 }
                   7764:             }
                   7765:             if (@okstatuses) {
                   7766:                 $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
                   7767:             }
                   7768:         }
                   7769:     }
1.1075    raeburn  7770:     my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963     raeburn  7771:                  $umode.', '.$first.', '.$middle.', '.
1.1075    raeburn  7772:                  $last.', '.$gene.', '.$email.', '.$inststatus;
1.963     raeburn  7773:     if ($env{'user.name'} ne '' && $env{'user.domain'}) {
                   7774:         $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
                   7775:     } else {
                   7776:         $logmsg .= ' during self creation';
                   7777:     }
1.1075    raeburn  7778:     my $changed;
                   7779:     if ($newuser) {
                   7780:         $changed = 1;
                   7781:     } else {
                   7782:         foreach my $field (@fields) {
                   7783:             if ($names{$field} ne $oldnames{$field}) {
                   7784:                 $changed = 1;
                   7785:                 last;
                   7786:             }
                   7787:         }
                   7788:     }
                   7789:     unless ($changed) {
                   7790:         $logmsg = 'No changes in user information needed for: '.$logmsg;
                   7791:         &logthis($logmsg);
                   7792:         return 'ok';
                   7793:     }
                   7794:     my $reply = &put('environment', \%names, $udom,$uname);
                   7795:     if ($reply ne 'ok') { 
                   7796:         return 'error: '.$reply;
                   7797:     }
1.1087    raeburn  7798:     if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
                   7799:         &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
                   7800:     }
1.1075    raeburn  7801:     my $sqlresult = &update_allusers_table($uname,$udom,\%names);
                   7802:     &devalidate_cache_new('namescache',$uname.':'.$udom);
                   7803:     $logmsg = 'Success modifying user '.$logmsg;
1.963     raeburn  7804:     &logthis($logmsg);
1.134     albertel 7805:     return 'ok';
1.80      www      7806: }
                   7807: 
1.81      www      7808: # -------------------------------------------------------------- Modify student
1.80      www      7809: 
1.81      www      7810: sub modifystudent {
                   7811:     my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957     raeburn  7812:         $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990     raeburn  7813:         $selfenroll,$context,$inststatus)=@_;
1.455     albertel 7814:     if (!$cid) {
1.620     albertel 7815: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7816: 	    return 'not_in_class';
                   7817: 	}
1.80      www      7818:     }
                   7819: # --------------------------------------------------------------- Make the user
1.81      www      7820:     my $reply=&modifyuser
1.209     matthew  7821: 	($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990     raeburn  7822:          $desiredhome,$email,$inststatus);
1.80      www      7823:     unless ($reply eq 'ok') { return $reply; }
1.297     matthew  7824:     # This will cause &modify_student_enrollment to get the uid from the
                   7825:     # students environment
                   7826:     $uid = undef if (!$forceid);
1.455     albertel 7827:     $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957     raeburn  7828: 					$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297     matthew  7829:     return $reply;
                   7830: }
                   7831: 
                   7832: sub modify_student_enrollment {
1.957     raeburn  7833:     my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455     albertel 7834:     my ($cdom,$cnum,$chome);
                   7835:     if (!$cid) {
1.620     albertel 7836: 	unless ($cid=$env{'request.course.id'}) {
1.455     albertel 7837: 	    return 'not_in_class';
                   7838: 	}
1.620     albertel 7839: 	$cdom=$env{'course.'.$cid.'.domain'};
                   7840: 	$cnum=$env{'course.'.$cid.'.num'};
1.455     albertel 7841:     } else {
                   7842: 	($cdom,$cnum)=split(/_/,$cid);
                   7843:     }
1.620     albertel 7844:     $chome=$env{'course.'.$cid.'.home'};
1.455     albertel 7845:     if (!$chome) {
1.457     raeburn  7846: 	$chome=&homeserver($cnum,$cdom);
1.297     matthew  7847:     }
1.455     albertel 7848:     if (!$chome) { return 'unknown_course'; }
1.297     matthew  7849:     # Make sure the user exists
1.81      www      7850:     my $uhome=&homeserver($uname,$udom);
                   7851:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   7852: 	return 'error: no such user';
                   7853:     }
1.297     matthew  7854:     # Get student data if we were not given enough information
                   7855:     if (!defined($first)  || $first  eq '' || 
                   7856:         !defined($last)   || $last   eq '' || 
                   7857:         !defined($uid)    || $uid    eq '' || 
                   7858:         !defined($middle) || $middle eq '' || 
                   7859:         !defined($gene)   || $gene   eq '') {
1.294     matthew  7860:         # They did not supply us with enough data to enroll the student, so
                   7861:         # we need to pick up more information.
1.297     matthew  7862:         my %tmp = &get('environment',
1.294     matthew  7863:                        ['firstname','middlename','lastname', 'generation','id']
1.297     matthew  7864:                        ,$udom,$uname);
                   7865: 
1.800     albertel 7866:         #foreach my $key (keys(%tmp)) {
                   7867:         #    &logthis("key $key = ".$tmp{$key});
1.455     albertel 7868:         #}
1.294     matthew  7869:         $first  = $tmp{'firstname'}  if (!defined($first)  || $first  eq '');
                   7870:         $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
                   7871:         $last   = $tmp{'lastname'}   if (!defined($last)   || $last eq '');
1.297     matthew  7872:         $gene   = $tmp{'generation'} if (!defined($gene)   || $gene eq '');
1.294     matthew  7873:         $uid    = $tmp{'id'}         if (!defined($uid)    || $uid  eq '');
                   7874:     }
1.556     albertel 7875:     my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148    raeburn  7876:     my $user = "$uname:$udom";
                   7877:     my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487     albertel 7878:     my $reply=cput('classlist',
1.1148    raeburn  7879: 		   {$user => 
1.515     raeburn  7880: 			join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487     albertel 7881: 		   $cdom,$cnum);
1.1148    raeburn  7882:     if (($reply eq 'ok') || ($reply eq 'delayed')) {
                   7883:         &devalidate_getsection_cache($udom,$uname,$cid);
                   7884:     } else { 
1.81      www      7885: 	return 'error: '.$reply;
                   7886:     }
1.297     matthew  7887:     # Add student role to user
1.83      www      7888:     my $uurl='/'.$cid;
1.81      www      7889:     $uurl=~s/\_/\//g;
                   7890:     if ($usec) {
                   7891: 	$uurl.='/'.$usec;
                   7892:     }
1.1148    raeburn  7893:     my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
                   7894:                              $selfenroll,$context);
                   7895:     if ($result ne 'ok') {
                   7896:         if ($old_entry{$user} ne '') {
                   7897:             $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
                   7898:         } else {
                   7899:             $reply = &del('classlist',[$user],$cdom,$cnum);
                   7900:         }
                   7901:     }
                   7902:     return $result; 
1.21      www      7903: }
                   7904: 
1.556     albertel 7905: sub format_name {
                   7906:     my ($firstname,$middlename,$lastname,$generation,$first)=@_;
                   7907:     my $name;
                   7908:     if ($first ne 'lastname') {
                   7909: 	$name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
                   7910:     } else {
                   7911: 	if ($lastname=~/\S/) {
                   7912: 	    $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
                   7913: 	    $name=~s/\s+,/,/;
                   7914: 	} else {
                   7915: 	    $name.= $firstname.' '.$middlename.' '.$generation;
                   7916: 	}
                   7917:     }
                   7918:     $name=~s/^\s+//;
                   7919:     $name=~s/\s+$//;
                   7920:     $name=~s/\s+/ /g;
                   7921:     return $name;
                   7922: }
                   7923: 
1.84      www      7924: # ------------------------------------------------- Write to course preferences
                   7925: 
                   7926: sub writecoursepref {
                   7927:     my ($courseid,%prefs)=@_;
                   7928:     $courseid=~s/^\///;
                   7929:     $courseid=~s/\_/\//g;
                   7930:     my ($cdomain,$cnum)=split(/\//,$courseid);
                   7931:     my $chome=homeserver($cnum,$cdomain);
                   7932:     if (($chome eq '') || ($chome eq 'no_host')) { 
                   7933: 	return 'error: no such course';
                   7934:     }
                   7935:     my $cstring='';
1.800     albertel 7936:     foreach my $pref (keys(%prefs)) {
                   7937: 	$cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191     harris41 7938:     }
1.84      www      7939:     $cstring=~s/\&$//;
                   7940:     return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
                   7941: }
                   7942: 
                   7943: # ---------------------------------------------------------- Make/modify course
                   7944: 
                   7945: sub createcourse {
1.741     raeburn  7946:     my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017    raeburn  7947:         $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84      www      7948:     $url=&declutter($url);
                   7949:     my $cid='';
1.1028    raeburn  7950:     if ($context eq 'requestcourses') {
                   7951:         my $can_create = 0;
                   7952:         my ($ownername,$ownerdom) = split(':',$course_owner);
                   7953:         if ($udom eq $ownerdom) {
                   7954:             if (&usertools_access($ownername,$ownerdom,$category,undef,
                   7955:                                   $context)) {
                   7956:                 $can_create = 1;
                   7957:             }
                   7958:         } else {
                   7959:             my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
                   7960:                                            $category);
                   7961:             if ($userenv{'reqcrsotherdom.'.$category} ne '') {
                   7962:                 my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
                   7963:                 if (@curr > 0) {
                   7964:                     my @options = qw(approval validate autolimit);
                   7965:                     my $optregex = join('|',@options);
                   7966:                     if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
                   7967:                         $can_create = 1;
                   7968:                     }
                   7969:                 }
                   7970:             }
                   7971:         }
                   7972:         if ($can_create) {
                   7973:             unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
                   7974:                 unless (&allowed('ccc',$udom)) {
                   7975:                     return 'refused'; 
                   7976:                 }
1.1017    raeburn  7977:             }
                   7978:         } else {
                   7979:             return 'refused';
                   7980:         }
1.1028    raeburn  7981:     } elsif (!&allowed('ccc',$udom)) {
                   7982:         return 'refused';
1.84      www      7983:     }
1.1011    raeburn  7984: # --------------------------------------------------------------- Get Unique ID
                   7985:     my $uname;
                   7986:     if ($cnum =~ /^$match_courseid$/) {
                   7987:         my $chome=&homeserver($cnum,$udom,'true');
                   7988:         if (($chome eq '') || ($chome eq 'no_host')) {
                   7989:             $uname = $cnum;
                   7990:         } else {
1.1038    raeburn  7991:             $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7992:         }
                   7993:     } else {
1.1038    raeburn  7994:         $uname = &generate_coursenum($udom,$crstype);
1.1011    raeburn  7995:     }
                   7996:     return $uname if ($uname =~ /^error/);
                   7997: # -------------------------------------------------- Check supplied server name
1.1052    raeburn  7998:     if (!defined($course_server)) {
                   7999:         if (defined(&domain($udom,'primary'))) {
                   8000:             $course_server = &domain($udom,'primary');
                   8001:         } else {
                   8002:             $course_server = $env{'user.home'}; 
                   8003:         }
                   8004:     }
                   8005:     my %host_servers =
                   8006:         &Apache::lonnet::get_servers($udom,'library');
                   8007:     unless ($host_servers{$course_server}) {
                   8008:         return 'error: invalid home server for course: '.$course_server;
1.264     matthew  8009:     }
1.84      www      8010: # ------------------------------------------------------------- Make the course
                   8011:     my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264     matthew  8012:                       $course_server);
1.84      www      8013:     unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011    raeburn  8014:     my $uhome=&homeserver($uname,$udom,'true');
1.84      www      8015:     if (($uhome eq '') || ($uhome eq 'no_host')) { 
                   8016: 	return 'error: no such course';
                   8017:     }
1.271     www      8018: # ----------------------------------------------------------------- Course made
1.516     raeburn  8019: # log existence
1.1029    raeburn  8020:     my $now = time;
1.918     raeburn  8021:     my $newcourse = {
                   8022:                     $udom.'_'.$uname => {
1.921     raeburn  8023:                                      description => $description,
                   8024:                                      inst_code   => $inst_code,
                   8025:                                      owner       => $course_owner,
                   8026:                                      type        => $crstype,
1.1029    raeburn  8027:                                      creator     => $env{'user.name'}.':'.
                   8028:                                                     $env{'user.domain'},
                   8029:                                      created     => $now,
                   8030:                                      context     => $context,
1.918     raeburn  8031:                                                 },
                   8032:                     };
1.921     raeburn  8033:     &courseidput($udom,$newcourse,$uhome,'notime');
1.358     www      8034: # set toplevel url
1.271     www      8035:     my $topurl=$url;
                   8036:     unless ($nonstandard) {
                   8037: # ------------------------------------------ For standard courses, make top url
                   8038:         my $mapurl=&clutter($url);
1.278     www      8039:         if ($mapurl eq '/res/') { $mapurl=''; }
1.620     albertel 8040:         $env{'form.initmap'}=(<<ENDINITMAP);
1.271     www      8041: <map>
                   8042: <resource id="1" type="start"></resource>
                   8043: <resource id="2" src="$mapurl"></resource>
                   8044: <resource id="3" type="finish"></resource>
                   8045: <link index="1" from="1" to="2"></link>
                   8046: <link index="2" from="2" to="3"></link>
                   8047: </map>
                   8048: ENDINITMAP
                   8049:         $topurl=&declutter(
1.638     albertel 8050:         &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271     www      8051:                           );
                   8052:     }
                   8053: # ----------------------------------------------------------- Write preferences
1.84      www      8054:     &writecoursepref($udom.'_'.$uname,
1.1056    raeburn  8055:                      ('description'              => $description,
                   8056:                       'url'                      => $topurl,
                   8057:                       'internal.creator'         => $env{'user.name'}.':'.
                   8058:                                                     $env{'user.domain'},
                   8059:                       'internal.created'         => $now,
                   8060:                       'internal.creationcontext' => $context)
                   8061:                     );
1.84      www      8062:     return '/'.$udom.'/'.$uname;
                   8063: }
                   8064: 
1.1011    raeburn  8065: # ------------------------------------------------------------------- Create ID
                   8066: sub generate_coursenum {
1.1038    raeburn  8067:     my ($udom,$crstype) = @_;
1.1011    raeburn  8068:     my $domdesc = &domain($udom);
                   8069:     return 'error: invalid domain' if ($domdesc eq '');
1.1038    raeburn  8070:     my $first;
                   8071:     if ($crstype eq 'Community') {
                   8072:         $first = '0';
                   8073:     } else {
                   8074:         $first = int(1+rand(9)); 
                   8075:     } 
                   8076:     my $uname=$first.
1.1011    raeburn  8077:         ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8078:         substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8079:         unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8080: # ----------------------------------------------- Make sure that does not exist
                   8081:     my $uhome=&homeserver($uname,$udom,'true');
                   8082:     unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038    raeburn  8083:         if ($crstype eq 'Community') {
                   8084:             $first = '0';
                   8085:         } else {
                   8086:             $first = int(1+rand(9));
                   8087:         }
                   8088:         $uname=$first.
1.1011    raeburn  8089:                ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
                   8090:                substr($$.time,0,5).unpack("H8",pack("I32",time)).
                   8091:                unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
                   8092:         $uhome=&homeserver($uname,$udom,'true');
                   8093:         unless (($uhome eq '') || ($uhome eq 'no_host')) {
                   8094:             return 'error: unable to generate unique course-ID';
                   8095:         }
                   8096:     }
                   8097:     return $uname;
                   8098: }
                   8099: 
1.813     albertel 8100: sub is_course {
1.1167    droeschl 8101:     my ($cdom, $cnum) = scalar(@_) == 1 ? 
                   8102:          ($_[0] =~ /^($match_domain)_($match_courseid)$/)  :  @_;
                   8103: 
                   8104:     return unless $cdom and $cnum;
                   8105: 
                   8106:     my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
                   8107:         '.');
                   8108: 
                   8109:     return unless exists($courses{$cdom.'_'.$cnum});
                   8110:     return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813     albertel 8111: }
                   8112: 
1.1015    raeburn  8113: sub store_userdata {
                   8114:     my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013    raeburn  8115:     my $result;
1.1016    raeburn  8116:     if ($datakey ne '') {
1.1013    raeburn  8117:         if (ref($storehash) eq 'HASH') {
1.1017    raeburn  8118:             if ($udom eq '' || $uname eq '') {
                   8119:                 $udom = $env{'user.domain'};
                   8120:                 $uname = $env{'user.name'};
                   8121:             }
                   8122:             my $uhome=&homeserver($uname,$udom);
1.1013    raeburn  8123:             if (($uhome eq '') || ($uhome eq 'no_host')) {
                   8124:                 $result = 'error: no_host';
                   8125:             } else {
                   8126:                 $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
                   8127:                 $storehash->{'host'} = $perlvar{'lonHostID'};
                   8128: 
                   8129:                 my $namevalue='';
                   8130:                 foreach my $key (keys(%{$storehash})) {
                   8131:                     $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
                   8132:                 }
                   8133:                 $namevalue=~s/\&$//;
1.1105    raeburn  8134:                 $result =  &reply("store:$udom:$uname:$namespace:$datakey:".
                   8135:                                   $namevalue,$uhome);
1.1013    raeburn  8136:             }
                   8137:         } else {
                   8138:             $result = 'error: data to store was not a hash reference'; 
                   8139:         }
                   8140:     } else {
                   8141:         $result= 'error: invalid requestkey'; 
                   8142:     }
                   8143:     return $result;
                   8144: }
                   8145: 
1.21      www      8146: # ---------------------------------------------------------- Assign Custom Role
                   8147: 
                   8148: sub assigncustomrole {
1.957     raeburn  8149:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8150:     return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957     raeburn  8151:                        $end,$start,$deleteflag,$selfenroll,$context);
1.21      www      8152: }
                   8153: 
                   8154: # ----------------------------------------------------------------- Revoke Role
                   8155: 
                   8156: sub revokerole {
1.957     raeburn  8157:     my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8158:     my $now=time;
1.965     raeburn  8159:     return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21      www      8160: }
                   8161: 
                   8162: # ---------------------------------------------------------- Revoke Custom Role
                   8163: 
                   8164: sub revokecustomrole {
1.957     raeburn  8165:     my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21      www      8166:     my $now=time;
1.357     www      8167:     return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957     raeburn  8168:            $deleteflag,$selfenroll,$context);
1.17      www      8169: }
                   8170: 
1.533     banghart 8171: # ------------------------------------------------------------ Disk usage
1.535     albertel 8172: sub diskusage {
1.955     raeburn  8173:     my ($udom,$uname,$directorypath,$getpropath)=@_;
                   8174:     $directorypath =~ s/\/$//;
                   8175:     my $listing=&reply('du2:'.&escape($directorypath).':'
                   8176:                        .&escape($getpropath).':'.&escape($uname).':'
                   8177:                        .&escape($udom),homeserver($uname,$udom));
                   8178:     if ($listing eq 'unknown_cmd') {
                   8179:         if ($getpropath) {
                   8180:             $directorypath = &propath($udom,$uname).'/'.$directorypath; 
                   8181:         }
                   8182:         $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
                   8183:     }
1.514     albertel 8184:     return $listing;
1.512     banghart 8185: }
                   8186: 
1.566     banghart 8187: sub is_locked {
1.1096    raeburn  8188:     my ($file_name, $domain, $user, $which) = @_;
1.566     banghart 8189:     my @check;
                   8190:     my $is_locked;
1.1093    raeburn  8191:     push (@check,$file_name);
1.613     albertel 8192:     my %locked = &get('file_permissions',\@check,
1.620     albertel 8193: 		      $env{'user.domain'},$env{'user.name'});
1.615     albertel 8194:     my ($tmp)=keys(%locked);
                   8195:     if ($tmp=~/^error:/) { undef(%locked); }
1.745     raeburn  8196:     
1.566     banghart 8197:     if (ref($locked{$file_name}) eq 'ARRAY') {
1.745     raeburn  8198:         $is_locked = 'false';
                   8199:         foreach my $entry (@{$locked{$file_name}}) {
1.1096    raeburn  8200:            if (ref($entry) eq 'ARRAY') {
1.746     raeburn  8201:                $is_locked = 'true';
1.1096    raeburn  8202:                if (ref($which) eq 'ARRAY') {
                   8203:                    push(@{$which},$entry);
                   8204:                } else {
                   8205:                    last;
                   8206:                }
1.745     raeburn  8207:            }
                   8208:        }
1.566     banghart 8209:     } else {
                   8210:         $is_locked = 'false';
                   8211:     }
1.1093    raeburn  8212:     return $is_locked;
1.566     banghart 8213: }
                   8214: 
1.759     albertel 8215: sub declutter_portfile {
                   8216:     my ($file) = @_;
1.833     albertel 8217:     $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759     albertel 8218:     return $file;
                   8219: }
                   8220: 
1.559     banghart 8221: # ------------------------------------------------------------- Mark as Read Only
                   8222: 
                   8223: sub mark_as_readonly {
                   8224:     my ($domain,$user,$files,$what) = @_;
1.613     albertel 8225:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8226:     my ($tmp)=keys(%current_permissions);
                   8227:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560     banghart 8228:     foreach my $file (@{$files}) {
1.759     albertel 8229: 	$file = &declutter_portfile($file);
1.561     banghart 8230:         push(@{$current_permissions{$file}},$what);
1.559     banghart 8231:     }
1.613     albertel 8232:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8233:     return;
                   8234: }
                   8235: 
1.572     banghart 8236: # ------------------------------------------------------------Save Selected Files
                   8237: 
                   8238: sub save_selected_files {
                   8239:     my ($user, $path, @files) = @_;
                   8240:     my $filename = $user."savedfiles";
1.573     banghart 8241:     my @other_files = &files_not_in_path($user, $path);
1.871     albertel 8242:     open (OUT, '>'.$tmpdir.$filename);
1.573     banghart 8243:     foreach my $file (@files) {
1.620     albertel 8244:         print (OUT $env{'form.currentpath'}.$file."\n");
1.573     banghart 8245:     }
                   8246:     foreach my $file (@other_files) {
1.574     banghart 8247:         print (OUT $file."\n");
1.572     banghart 8248:     }
1.574     banghart 8249:     close (OUT);
1.572     banghart 8250:     return 'ok';
                   8251: }
                   8252: 
1.574     banghart 8253: sub clear_selected_files {
                   8254:     my ($user) = @_;
                   8255:     my $filename = $user."savedfiles";
1.1117    foxr     8256:     open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574     banghart 8257:     print (OUT undef);
                   8258:     close (OUT);
                   8259:     return ("ok");    
                   8260: }
                   8261: 
1.572     banghart 8262: sub files_in_path {
                   8263:     my ($user, $path) = @_;
                   8264:     my $filename = $user."savedfiles";
                   8265:     my %return_files;
1.1117    foxr     8266:     open (IN, '<'.LONCAPA::tempdir().$filename);
1.573     banghart 8267:     while (my $line_in = <IN>) {
1.574     banghart 8268:         chomp ($line_in);
                   8269:         my @paths_and_file = split (m!/!, $line_in);
                   8270:         my $file_part = pop (@paths_and_file);
                   8271:         my $path_part = join ('/', @paths_and_file);
1.573     banghart 8272:         $path_part.='/';
                   8273:         my $path_and_file = $path_part.$file_part;
                   8274:         if ($path_part eq $path) {
                   8275:             $return_files{$file_part}= 'selected';
                   8276:         }
                   8277:     }
1.574     banghart 8278:     close (IN);
                   8279:     return (\%return_files);
1.572     banghart 8280: }
                   8281: 
                   8282: # called in portfolio select mode, to show files selected NOT in current directory
                   8283: sub files_not_in_path {
                   8284:     my ($user, $path) = @_;
                   8285:     my $filename = $user."savedfiles";
                   8286:     my @return_files;
                   8287:     my $path_part;
1.1117    foxr     8288:     open(IN, '<'.LONCAPA::.$filename);
1.800     albertel 8289:     while (my $line = <IN>) {
1.572     banghart 8290:         #ok, I know it's clunky, but I want it to work
1.800     albertel 8291:         my @paths_and_file = split(m|/|, $line);
                   8292:         my $file_part = pop(@paths_and_file);
                   8293:         chomp($file_part);
                   8294:         my $path_part = join('/', @paths_and_file);
1.572     banghart 8295:         $path_part .= '/';
                   8296:         my $path_and_file = $path_part.$file_part;
                   8297:         if ($path_part ne $path) {
1.800     albertel 8298:             push(@return_files, ($path_and_file));
1.572     banghart 8299:         }
                   8300:     }
1.800     albertel 8301:     close(OUT);
1.574     banghart 8302:     return (@return_files);
1.572     banghart 8303: }
                   8304: 
1.745     raeburn  8305: #----------------------------------------------Get portfolio file permissions
1.629     banghart 8306: 
1.745     raeburn  8307: sub get_portfile_permissions {
                   8308:     my ($domain,$user) = @_;
1.613     albertel 8309:     my %current_permissions = &dump('file_permissions',$domain,$user);
1.615     albertel 8310:     my ($tmp)=keys(%current_permissions);
                   8311:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8312:     return \%current_permissions;
                   8313: }
                   8314: 
                   8315: #---------------------------------------------Get portfolio file access controls
                   8316: 
1.749     raeburn  8317: sub get_access_controls {
1.745     raeburn  8318:     my ($current_permissions,$group,$file) = @_;
1.769     albertel 8319:     my %access;
                   8320:     my $real_file = $file;
                   8321:     $file =~ s/\.meta$//;
1.745     raeburn  8322:     if (defined($file)) {
1.749     raeburn  8323:         if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
                   8324:             foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769     albertel 8325:                 $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749     raeburn  8326:             }
                   8327:         }
1.745     raeburn  8328:     } else {
1.749     raeburn  8329:         foreach my $key (keys(%{$current_permissions})) {
                   8330:             if ($key =~ /\0accesscontrol$/) {
                   8331:                 if (defined($group)) {
                   8332:                     if ($key !~ m-^\Q$group\E/-) {
                   8333:                         next;
                   8334:                     }
                   8335:                 }
                   8336:                 my ($fullpath) = split(/\0/,$key);
                   8337:                 if (ref($$current_permissions{$key}) eq 'HASH') {
                   8338:                     foreach my $control (keys(%{$$current_permissions{$key}})) {
                   8339:                         $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
                   8340:                     }
                   8341:                 }
                   8342:             }
                   8343:         }
                   8344:     }
                   8345:     return %access;
                   8346: }
                   8347: 
                   8348: sub modify_access_controls {
                   8349:     my ($file_name,$changes,$domain,$user)=@_;
                   8350:     my ($outcome,$deloutcome);
                   8351:     my %store_permissions;
                   8352:     my %new_values;
                   8353:     my %new_control;
                   8354:     my %translation;
                   8355:     my @deletions = ();
                   8356:     my $now = time;
                   8357:     if (exists($$changes{'activate'})) {
                   8358:         if (ref($$changes{'activate'}) eq 'HASH') {
                   8359:             my @newitems = sort(keys(%{$$changes{'activate'}}));
                   8360:             my $numnew = scalar(@newitems);
                   8361:             for (my $i=0; $i<$numnew; $i++) {
                   8362:                 my $newkey = $newitems[$i];
                   8363:                 my $newid = &Apache::loncommon::get_cgi_id();
1.797     raeburn  8364:                 if ($newkey =~ /^\d+:/) { 
                   8365:                     $newkey =~ s/^(\d+)/$newid/;
                   8366:                     $translation{$1} = $newid;
                   8367:                 } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
                   8368:                     $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
                   8369:                     $translation{$1} = $newid;
                   8370:                 }
1.749     raeburn  8371:                 $new_values{$file_name."\0".$newkey} = 
                   8372:                                           $$changes{'activate'}{$newitems[$i]};
                   8373:                 $new_control{$newkey} = $now;
                   8374:             }
                   8375:         }
                   8376:     }
                   8377:     my %todelete;
                   8378:     my %changed_items;
                   8379:     foreach my $action ('delete','update') {
                   8380:         if (exists($$changes{$action})) {
                   8381:             if (ref($$changes{$action}) eq 'HASH') {
                   8382:                 foreach my $key (keys(%{$$changes{$action}})) {
                   8383:                     my ($itemnum) = ($key =~ /^([^:]+):/);
                   8384:                     if ($action eq 'delete') { 
                   8385:                         $todelete{$itemnum} = 1;
                   8386:                     } else {
                   8387:                         $changed_items{$itemnum} = $key;
                   8388:                     }
                   8389:                 }
1.745     raeburn  8390:             }
                   8391:         }
1.749     raeburn  8392:     }
                   8393:     # get lock on access controls for file.
                   8394:     my $lockhash = {
                   8395:                   $file_name."\0".'locked_access_records' => $env{'user.name'}.
                   8396:                                                        ':'.$env{'user.domain'},
                   8397:                    }; 
                   8398:     my $tries = 0;
                   8399:     my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8400:    
                   8401:     while (($gotlock ne 'ok') && $tries <3) {
                   8402:         $tries ++;
                   8403:         sleep 1;
                   8404:         $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
                   8405:     }
                   8406:     if ($gotlock eq 'ok') {
                   8407:         my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
                   8408:         my ($tmp)=keys(%curr_permissions);
                   8409:         if ($tmp=~/^error:/) { undef(%curr_permissions); }
                   8410:         if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
                   8411:             my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
                   8412:             if (ref($curr_controls) eq 'HASH') {
                   8413:                 foreach my $control_item (keys(%{$curr_controls})) {
                   8414:                     my ($itemnum) = ($control_item =~ /^([^:]+):/);
                   8415:                     if (defined($todelete{$itemnum})) {
                   8416:                         push(@deletions,$file_name."\0".$control_item);
                   8417:                     } else {
                   8418:                         if (defined($changed_items{$itemnum})) {
                   8419:                             $new_control{$changed_items{$itemnum}} = $now;
                   8420:                             push(@deletions,$file_name."\0".$control_item);
                   8421:                             $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
                   8422:                         } else {
                   8423:                             $new_control{$control_item} = $$curr_controls{$control_item};
                   8424:                         }
                   8425:                     }
1.745     raeburn  8426:                 }
                   8427:             }
                   8428:         }
1.970     raeburn  8429:         my ($group);
                   8430:         if (&is_course($domain,$user)) {
                   8431:             ($group,my $file) = split(/\//,$file_name,2);
                   8432:         }
1.749     raeburn  8433:         $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
                   8434:         $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
                   8435:         $outcome = &put('file_permissions',\%new_values,$domain,$user);
                   8436:         #  remove lock
                   8437:         my @del_lock = ($file_name."\0".'locked_access_records');
                   8438:         my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818     raeburn  8439:         my $sqlresult =
1.970     raeburn  8440:             &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818     raeburn  8441:                                     $group);
1.749     raeburn  8442:     } else {
                   8443:         $outcome = "error: could not obtain lockfile\n";  
1.745     raeburn  8444:     }
1.749     raeburn  8445:     return ($outcome,$deloutcome,\%new_values,\%translation);
1.745     raeburn  8446: }
                   8447: 
1.827     raeburn  8448: sub make_public_indefinitely {
                   8449:     my ($requrl) = @_;
                   8450:     my $now = time;
                   8451:     my $action = 'activate';
                   8452:     my $aclnum = 0;
                   8453:     if (&is_portfolio_url($requrl)) {
                   8454:         my (undef,$udom,$unum,$file_name,$group) =
                   8455:             &parse_portfolio_url($requrl);
                   8456:         my $current_perms = &get_portfile_permissions($udom,$unum);
                   8457:         my %access_controls = &get_access_controls($current_perms,
                   8458:                                                    $group,$file_name);
                   8459:         foreach my $key (keys(%{$access_controls{$file_name}})) {
                   8460:             my ($num,$scope,$end,$start) = 
                   8461:                 ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
                   8462:             if ($scope eq 'public') {
                   8463:                 if ($start <= $now && $end == 0) {
                   8464:                     $action = 'none';
                   8465:                 } else {
                   8466:                     $action = 'update';
                   8467:                     $aclnum = $num;
                   8468:                 }
                   8469:                 last;
                   8470:             }
                   8471:         }
                   8472:         if ($action eq 'none') {
                   8473:              return 'ok';
                   8474:         } else {
                   8475:             my %changes;
                   8476:             my $newend = 0;
                   8477:             my $newstart = $now;
                   8478:             my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
                   8479:             $changes{$action}{$newkey} = {
                   8480:                 type => 'public',
                   8481:                 time => {
                   8482:                     start => $newstart,
                   8483:                     end   => $newend,
                   8484:                 },
                   8485:             };
                   8486:             my ($outcome,$deloutcome,$new_values,$translation) =
                   8487:                 &modify_access_controls($file_name,\%changes,$udom,$unum);
                   8488:             return $outcome;
                   8489:         }
                   8490:     } else {
                   8491:         return 'invalid';
                   8492:     }
                   8493: }
                   8494: 
1.745     raeburn  8495: #------------------------------------------------------Get Marked as Read Only
                   8496: 
                   8497: sub get_marked_as_readonly {
                   8498:     my ($domain,$user,$what,$group) = @_;
                   8499:     my $current_permissions = &get_portfile_permissions($domain,$user);
1.563     banghart 8500:     my @readonly_files;
1.629     banghart 8501:     my $cmp1=$what;
                   8502:     if (ref($what)) { $cmp1=join('',@{$what}) };
1.745     raeburn  8503:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8504:         if (defined($group)) {
                   8505:             if ($file_name !~ m-^\Q$group\E/-) {
                   8506:                 next;
                   8507:             }
                   8508:         }
1.561     banghart 8509:         if (ref($value) eq "ARRAY"){
                   8510:             foreach my $stored_what (@{$value}) {
1.629     banghart 8511:                 my $cmp2=$stored_what;
1.759     albertel 8512:                 if (ref($stored_what) eq 'ARRAY') {
1.746     raeburn  8513:                     $cmp2=join('',@{$stored_what});
1.745     raeburn  8514:                 }
1.629     banghart 8515:                 if ($cmp1 eq $cmp2) {
1.561     banghart 8516:                     push(@readonly_files, $file_name);
1.745     raeburn  8517:                     last;
1.563     banghart 8518:                 } elsif (!defined($what)) {
                   8519:                     push(@readonly_files, $file_name);
1.745     raeburn  8520:                     last;
1.561     banghart 8521:                 }
                   8522:             }
1.745     raeburn  8523:         }
1.561     banghart 8524:     }
                   8525:     return @readonly_files;
                   8526: }
1.577     banghart 8527: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561     banghart 8528: 
1.577     banghart 8529: sub get_marked_as_readonly_hash {
1.745     raeburn  8530:     my ($current_permissions,$group,$what) = @_;
1.577     banghart 8531:     my %readonly_files;
1.745     raeburn  8532:     while (my ($file_name,$value) = each(%{$current_permissions})) {
                   8533:         if (defined($group)) {
                   8534:             if ($file_name !~ m-^\Q$group\E/-) {
                   8535:                 next;
                   8536:             }
                   8537:         }
1.577     banghart 8538:         if (ref($value) eq "ARRAY"){
                   8539:             foreach my $stored_what (@{$value}) {
1.745     raeburn  8540:                 if (ref($stored_what) eq 'ARRAY') {
1.750     banghart 8541:                     foreach my $lock_descriptor(@{$stored_what}) {
                   8542:                         if ($lock_descriptor eq 'graded') {
                   8543:                             $readonly_files{$file_name} = 'graded';
                   8544:                         } elsif ($lock_descriptor eq 'handback') {
                   8545:                             $readonly_files{$file_name} = 'handback';
                   8546:                         } else {
                   8547:                             if (!exists($readonly_files{$file_name})) {
                   8548:                                 $readonly_files{$file_name} = 'locked';
                   8549:                             }
                   8550:                         }
1.745     raeburn  8551:                     }
1.750     banghart 8552:                 } 
1.577     banghart 8553:             }
                   8554:         } 
                   8555:     }
                   8556:     return %readonly_files;
                   8557: }
1.559     banghart 8558: # ------------------------------------------------------------ Unmark as Read Only
                   8559: 
                   8560: sub unmark_as_readonly {
1.629     banghart 8561:     # unmarks $file_name (if $file_name is defined), or all files locked by $what 
                   8562:     # for portfolio submissions, $what contains [$symb,$crsid] 
1.745     raeburn  8563:     my ($domain,$user,$what,$file_name,$group) = @_;
1.759     albertel 8564:     $file_name = &declutter_portfile($file_name);
1.634     albertel 8565:     my $symb_crs = $what;
                   8566:     if (ref($what)) { $symb_crs=join('',@$what); }
1.745     raeburn  8567:     my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615     albertel 8568:     my ($tmp)=keys(%current_permissions);
                   8569:     if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745     raeburn  8570:     my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650     albertel 8571:     foreach my $file (@readonly_files) {
1.759     albertel 8572: 	my $clean_file = &declutter_portfile($file);
                   8573: 	if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650     albertel 8574: 	my $current_locks = $current_permissions{$file};
1.563     banghart 8575:         my @new_locks;
                   8576:         my @del_keys;
                   8577:         if (ref($current_locks) eq "ARRAY"){
                   8578:             foreach my $locker (@{$current_locks}) {
1.632     albertel 8579:                 my $compare=$locker;
1.749     raeburn  8580:                 if (ref($locker) eq 'ARRAY') {
1.745     raeburn  8581:                     $compare=join('',@{$locker});
1.746     raeburn  8582:                     if ($compare ne $symb_crs) {
                   8583:                         push(@new_locks, $locker);
                   8584:                     }
1.563     banghart 8585:                 }
                   8586:             }
1.650     albertel 8587:             if (scalar(@new_locks) > 0) {
1.563     banghart 8588:                 $current_permissions{$file} = \@new_locks;
                   8589:             } else {
                   8590:                 push(@del_keys, $file);
1.613     albertel 8591:                 &del('file_permissions',\@del_keys, $domain, $user);
1.650     albertel 8592:                 delete($current_permissions{$file});
1.563     banghart 8593:             }
                   8594:         }
1.561     banghart 8595:     }
1.613     albertel 8596:     &put('file_permissions',\%current_permissions,$domain,$user);
1.559     banghart 8597:     return;
                   8598: }
1.512     banghart 8599: 
1.17      www      8600: # ------------------------------------------------------------ Directory lister
                   8601: 
                   8602: sub dirlist {
1.955     raeburn  8603:     my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18      www      8604:     $uri=~s/^\///;
                   8605:     $uri=~s/\/$//;
1.253     stredwic 8606:     my ($udom, $uname);
1.955     raeburn  8607:     if ($getuserdir) {
1.253     stredwic 8608:         $udom = $userdomain;
                   8609:         $uname = $username;
1.955     raeburn  8610:     } else {
                   8611:         (undef,$udom,$uname)=split(/\//,$uri);
                   8612:         if(defined($userdomain)) {
                   8613:             $udom = $userdomain;
                   8614:         }
                   8615:         if(defined($username)) {
                   8616:             $uname = $username;
                   8617:         }
1.253     stredwic 8618:     }
1.955     raeburn  8619:     my ($dirRoot,$listing,@listing_results);
1.253     stredwic 8620: 
1.955     raeburn  8621:     $dirRoot = $perlvar{'lonDocRoot'};
                   8622:     if (defined($getpropath)) {
                   8623:         $dirRoot = &propath($udom,$uname);
1.253     stredwic 8624:         $dirRoot =~ s/\/$//;
1.955     raeburn  8625:     } elsif (defined($getuserdir)) {
                   8626:         my $subdir=$uname.'__';
                   8627:         $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
                   8628:         $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
                   8629:                    ."/$udom/$subdir/$uname";
                   8630:     } elsif (defined($alternateRoot)) {
                   8631:         $dirRoot = $alternateRoot;
1.751     banghart 8632:     }
1.253     stredwic 8633: 
                   8634:     if($udom) {
                   8635:         if($uname) {
1.1135    raeburn  8636:             my $uhome = &homeserver($uname,$udom);
1.1136    raeburn  8637:             if ($uhome eq 'no_host') {
                   8638:                 return ([],'no_host');
                   8639:             }
1.955     raeburn  8640:             $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956     raeburn  8641:                               .$getuserdir.':'.&escape($dirRoot)
1.1135    raeburn  8642:                               .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955     raeburn  8643:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8644:                 $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955     raeburn  8645:             } else {
                   8646:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8647:             }
1.605     matthew  8648:             if ($listing eq 'unknown_cmd') {
1.1135    raeburn  8649:                 $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605     matthew  8650:                 @listing_results = split(/:/,$listing);
                   8651:             } else {
                   8652:                 @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8653:             }
1.1135    raeburn  8654:             if (($listing eq 'no_such_host') || ($listing eq 'con_lost') || 
1.1136    raeburn  8655:                 ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8656:                 ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8657:                 return ([],$listing);
                   8658:             } else {
                   8659:                 return (\@listing_results);
1.1135    raeburn  8660:             }
1.955     raeburn  8661:         } elsif(!$alternateRoot) {
1.1136    raeburn  8662:             my (%allusers,%listerror);
1.841     albertel 8663: 	    my %servers = &get_servers($udom,'library');
1.955     raeburn  8664:  	    foreach my $tryserver (keys(%servers)) {
                   8665:                 $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
                   8666:                                   &escape($udom),$tryserver);
                   8667:                 if ($listing eq 'unknown_cmd') {
                   8668: 		    $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8669: 				      $udom, $tryserver);
                   8670:                 } else {
                   8671:                     @listing_results = map { &unescape($_); } split(/:/,$listing);
                   8672:                 }
1.841     albertel 8673: 		if ($listing eq 'unknown_cmd') {
                   8674: 		    $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
                   8675: 				      $udom, $tryserver);
                   8676: 		    @listing_results = split(/:/,$listing);
                   8677: 		} else {
                   8678: 		    @listing_results =
                   8679: 			map { &unescape($_); } split(/:/,$listing);
                   8680: 		}
1.1136    raeburn  8681:                 if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
                   8682:                     ($listing eq 'rejected') || ($listing eq 'refused') ||
                   8683:                     ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
                   8684:                     $listerror{$tryserver} = $listing;
                   8685:                 } else {
1.841     albertel 8686: 		    foreach my $line (@listing_results) {
                   8687: 			my ($entry) = split(/&/,$line,2);
                   8688: 			$allusers{$entry} = 1;
                   8689: 		    }
                   8690: 		}
1.253     stredwic 8691:             }
1.1136    raeburn  8692:             my @alluserslist=();
1.800     albertel 8693:             foreach my $user (sort(keys(%allusers))) {
1.1136    raeburn  8694:                 push(@alluserslist,$user.'&user');
1.253     stredwic 8695:             }
1.1136    raeburn  8696:             return (\@alluserslist);
1.253     stredwic 8697:         } else {
1.1136    raeburn  8698:             return ([],'missing username');
1.253     stredwic 8699:         }
1.955     raeburn  8700:     } elsif(!defined($getpropath)) {
1.1136    raeburn  8701:         my $path = $perlvar{'lonDocRoot'}.'/res/'; 
                   8702:         my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
                   8703:         return (\@all_domains);
1.955     raeburn  8704:     } else {
1.1136    raeburn  8705:         return ([],'missing domain');
1.275     stredwic 8706:     }
                   8707: }
                   8708: 
                   8709: # --------------------------------------------- GetFileTimestamp
                   8710: # This function utilizes dirlist and returns the date stamp for
                   8711: # when it was last modified.  It will also return an error of -1
                   8712: # if an error occurs
                   8713: 
                   8714: sub GetFileTimestamp {
1.955     raeburn  8715:     my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807     albertel 8716:     $studentDomain = &LONCAPA::clean_domain($studentDomain);
                   8717:     $studentName   = &LONCAPA::clean_username($studentName);
1.1136    raeburn  8718:     my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
                   8719:                                     undef,$getuserdir);
                   8720:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8721:         return -1;
                   8722:     }
                   8723:     if (ref($fileref) eq 'ARRAY') {
                   8724:         my @stats = split('&',$fileref->[0]);
1.375     matthew  8725:         # @stats contains first the filename, then the stat output
                   8726:         return $stats[10]; # so this is 10 instead of 9.
1.275     stredwic 8727:     } else {
                   8728:         return -1;
1.253     stredwic 8729:     }
1.26      www      8730: }
                   8731: 
1.712     albertel 8732: sub stat_file {
                   8733:     my ($uri) = @_;
1.787     albertel 8734:     $uri = &clutter_with_no_wrapper($uri);
1.722     albertel 8735: 
1.955     raeburn  8736:     my ($udom,$uname,$file);
1.712     albertel 8737:     if ($uri =~ m-^/(uploaded|editupload)/-) {
                   8738: 	($udom,$uname,$file) =
1.811     albertel 8739: 	    ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712     albertel 8740: 	$file = 'userfiles/'.$file;
                   8741:     }
                   8742:     if ($uri =~ m-^/res/-) {
                   8743: 	($udom,$uname) = 
1.807     albertel 8744: 	    ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712     albertel 8745: 	$file = $uri;
                   8746:     }
                   8747: 
                   8748:     if (!$udom || !$uname || !$file) {
                   8749: 	# unable to handle the uri
                   8750: 	return ();
                   8751:     }
1.956     raeburn  8752:     my $getpropath;
                   8753:     if ($file =~ /^userfiles\//) {
                   8754:         $getpropath = 1;
                   8755:     }
1.1136    raeburn  8756:     my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
                   8757:     if (($error eq 'empty') || ($error eq 'no_such_dir')) {
                   8758:         return ();
                   8759:     } else {
                   8760:         if (ref($listref) eq 'ARRAY') {
                   8761:             my @stats = split('&',$listref->[0]);
                   8762: 	    shift(@stats); #filename is first
                   8763: 	    return @stats;
                   8764:         }
1.712     albertel 8765:     }
                   8766:     return ();
                   8767: }
                   8768: 
1.26      www      8769: # -------------------------------------------------------- Value of a Condition
                   8770: 
1.713     albertel 8771: # gets the value of a specific preevaluated condition
                   8772: #    stored in the string  $env{user.state.<cid>}
                   8773: # or looks up a condition reference in the bighash and if if hasn't
                   8774: # already been evaluated recurses into docondval to get the value of
                   8775: # the condition, then memoizing it to 
                   8776: #   $env{user.state.<cid>.<condition>}
1.40      www      8777: sub directcondval {
                   8778:     my $number=shift;
1.620     albertel 8779:     if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555     albertel 8780: 	&Apache::lonuserstate::evalstate();
                   8781:     }
1.713     albertel 8782:     if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
                   8783: 	return $env{'user.state.'.$env{'request.course.id'}.".$number"};
                   8784:     } elsif ($number =~ /^_/) {
                   8785: 	my $sub_condition;
                   8786: 	if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   8787: 		&GDBM_READER(),0640)) {
                   8788: 	    $sub_condition=$bighash{'conditions'.$number};
                   8789: 	    untie(%bighash);
                   8790: 	}
                   8791: 	my $value = &docondval($sub_condition);
1.949     raeburn  8792: 	&appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713     albertel 8793: 	return $value;
                   8794:     }
1.620     albertel 8795:     if ($env{'user.state.'.$env{'request.course.id'}}) {
                   8796:        return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40      www      8797:     } else {
                   8798:        return 2;
                   8799:     }
                   8800: }
                   8801: 
1.713     albertel 8802: # get the collection of conditions for this resource
1.26      www      8803: sub condval {
                   8804:     my $condidx=shift;
1.54      www      8805:     my $allpathcond='';
1.713     albertel 8806:     foreach my $cond (split(/\|/,$condidx)) {
                   8807: 	if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
                   8808: 	    $allpathcond.=
                   8809: 		'('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
                   8810: 	}
1.191     harris41 8811:     }
1.54      www      8812:     $allpathcond=~s/\|$//;
1.713     albertel 8813:     return &docondval($allpathcond);
                   8814: }
                   8815: 
                   8816: #evaluates an expression of conditions
                   8817: sub docondval {
                   8818:     my ($allpathcond) = @_;
                   8819:     my $result=0;
                   8820:     if ($env{'request.course.id'}
                   8821: 	&& defined($allpathcond)) {
                   8822: 	my $operand='|';
                   8823: 	my @stack;
                   8824: 	foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
                   8825: 	    if ($chunk eq '(') {
                   8826: 		push @stack,($operand,$result);
                   8827: 	    } elsif ($chunk eq ')') {
                   8828: 		my $before=pop @stack;
                   8829: 		if (pop @stack eq '&') {
                   8830: 		    $result=$result>$before?$before:$result;
                   8831: 		} else {
                   8832: 		    $result=$result>$before?$result:$before;
                   8833: 		}
                   8834: 	    } elsif (($chunk eq '&') || ($chunk eq '|')) {
                   8835: 		$operand=$chunk;
                   8836: 	    } else {
                   8837: 		my $new=directcondval($chunk);
                   8838: 		if ($operand eq '&') {
                   8839: 		    $result=$result>$new?$new:$result;
                   8840: 		} else {
                   8841: 		    $result=$result>$new?$result:$new;
                   8842: 		}
                   8843: 	    }
                   8844: 	}
1.26      www      8845:     }
                   8846:     return $result;
1.421     albertel 8847: }
                   8848: 
                   8849: # ---------------------------------------------------- Devalidate courseresdata
                   8850: 
                   8851: sub devalidatecourseresdata {
                   8852:     my ($coursenum,$coursedomain)=@_;
                   8853:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8854:     &devalidate_cache_new('courseres',$hashid);
1.28      www      8855: }
                   8856: 
1.763     www      8857: 
1.200     www      8858: # --------------------------------------------------- Course Resourcedata Query
1.878     foxr     8859: #
                   8860: #  Parameters:
                   8861: #      $coursenum    - Number of the course.
                   8862: #      $coursedomain - Domain at which the course was created.
                   8863: #  Returns:
                   8864: #     A hash of the course parameters along (I think) with timestamps
                   8865: #     and version info.
1.877     foxr     8866: 
1.624     albertel 8867: sub get_courseresdata {
                   8868:     my ($coursenum,$coursedomain)=@_;
1.200     www      8869:     my $coursehom=&homeserver($coursenum,$coursedomain);
                   8870:     my $hashid=$coursenum.':'.$coursedomain;
1.599     albertel 8871:     my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624     albertel 8872:     my %dumpreply;
1.417     albertel 8873:     unless (defined($cached)) {
1.624     albertel 8874: 	%dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417     albertel 8875: 	$result=\%dumpreply;
1.251     albertel 8876: 	my ($tmp) = keys(%dumpreply);
                   8877: 	if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599     albertel 8878: 	    &do_cache_new('courseres',$hashid,$result,600);
1.306     albertel 8879: 	} elsif ($tmp =~ /^(con_lost|no_such_host)/) {
                   8880: 	    return $tmp;
1.416     albertel 8881: 	} elsif ($tmp =~ /^(error)/) {
1.417     albertel 8882: 	    $result=undef;
1.599     albertel 8883: 	    &do_cache_new('courseres',$hashid,$result,600);
1.250     albertel 8884: 	}
                   8885:     }
1.624     albertel 8886:     return $result;
                   8887: }
                   8888: 
1.633     albertel 8889: sub devalidateuserresdata {
                   8890:     my ($uname,$udom)=@_;
                   8891:     my $hashid="$udom:$uname";
                   8892:     &devalidate_cache_new('userres',$hashid);
                   8893: }
                   8894: 
1.624     albertel 8895: sub get_userresdata {
                   8896:     my ($uname,$udom)=@_;
                   8897:     #most student don\'t have any data set, check if there is some data
                   8898:     if (&EXT_cache_status($udom,$uname)) { return undef; }
                   8899: 
                   8900:     my $hashid="$udom:$uname";
                   8901:     my ($result,$cached)=&is_cached_new('userres',$hashid);
                   8902:     if (!defined($cached)) {
                   8903: 	my %resourcedata=&dump('resourcedata',$udom,$uname);
                   8904: 	$result=\%resourcedata;
                   8905: 	&do_cache_new('userres',$hashid,$result,600);
                   8906:     }
                   8907:     my ($tmp)=keys(%$result);
                   8908:     if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
                   8909: 	return $result;
                   8910:     }
                   8911:     #error 2 occurs when the .db doesn't exist
                   8912:     if ($tmp!~/error: 2 /) {
1.672     albertel 8913: 	&logthis("<font color=\"blue\">WARNING:".
1.624     albertel 8914: 		 " Trying to get resource data for ".
                   8915: 		 $uname." at ".$udom.": ".
                   8916: 		 $tmp."</font>");
                   8917:     } elsif ($tmp=~/error: 2 /) {
1.633     albertel 8918: 	#&EXT_cache_set($udom,$uname);
                   8919: 	&do_cache_new('userres',$hashid,undef,600);
1.636     albertel 8920: 	undef($tmp); # not really an error so don't send it back
1.624     albertel 8921:     }
                   8922:     return $tmp;
                   8923: }
1.879     foxr     8924: #----------------------------------------------- resdata - return resource data
                   8925: #  Purpose:
                   8926: #    Return resource data for either users or for a course.
                   8927: #  Parameters:
                   8928: #     $name      - Course/user name.
                   8929: #     $domain    - Name of the domain the user/course is registered on.
                   8930: #     $type      - Type of thing $name is (must be 'course' or 'user'
                   8931: #     @which     - Array of names of resources desired.
                   8932: #  Returns:
                   8933: #     The value of the first reasource in @which that is found in the
                   8934: #     resource hash.
                   8935: #  Exceptional Conditions:
                   8936: #     If the $type passed in is not valid (not the string 'course' or 
                   8937: #     'user', an undefined  reference is returned.
                   8938: #     If none of the resources are found, an undef is returned
1.624     albertel 8939: sub resdata {
                   8940:     my ($name,$domain,$type,@which)=@_;
                   8941:     my $result;
                   8942:     if ($type eq 'course') {
                   8943: 	$result=&get_courseresdata($name,$domain);
                   8944:     } elsif ($type eq 'user') {
                   8945: 	$result=&get_userresdata($name,$domain);
                   8946:     }
                   8947:     if (!ref($result)) { return $result; }    
1.251     albertel 8948:     foreach my $item (@which) {
1.927     albertel 8949: 	if (defined($result->{$item->[0]})) {
                   8950: 	    return [$result->{$item->[0]},$item->[1]];
1.251     albertel 8951: 	}
1.250     albertel 8952:     }
1.291     albertel 8953:     return undef;
1.200     www      8954: }
                   8955: 
1.379     matthew  8956: #
                   8957: # EXT resource caching routines
                   8958: #
                   8959: 
                   8960: sub clear_EXT_cache_status {
1.383     albertel 8961:     &delenv('cache.EXT.');
1.379     matthew  8962: }
                   8963: 
                   8964: sub EXT_cache_status {
                   8965:     my ($target_domain,$target_user) = @_;
1.383     albertel 8966:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620     albertel 8967:     if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379     matthew  8968:         # We know already the user has no data
                   8969:         return 1;
                   8970:     } else {
                   8971:         return 0;
                   8972:     }
                   8973: }
                   8974: 
                   8975: sub EXT_cache_set {
                   8976:     my ($target_domain,$target_user) = @_;
1.383     albertel 8977:     my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949     raeburn  8978:     #&appenv({$cachename => time});
1.379     matthew  8979: }
                   8980: 
1.28      www      8981: # --------------------------------------------------------- Value of a Variable
1.58      www      8982: sub EXT {
1.715     albertel 8983: 
1.395     albertel 8984:     my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68      www      8985:     unless ($varname) { return ''; }
1.218     albertel 8986:     #get real user name/domain, courseid and symb
                   8987:     my $courseid;
1.359     albertel 8988:     my $publicuser;
1.427     www      8989:     if ($symbparm) {
                   8990: 	$symbparm=&get_symb_from_alias($symbparm);
                   8991:     }
1.218     albertel 8992:     if (!($uname && $udom)) {
1.790     albertel 8993:       (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218     albertel 8994:       if (!$symbparm) {	$symbparm=$cursymb; }
                   8995:     } else {
1.620     albertel 8996: 	$courseid=$env{'request.course.id'};
1.218     albertel 8997:     }
1.48      www      8998:     my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
                   8999:     my $rest;
1.320     albertel 9000:     if (defined($therest[0])) {
1.48      www      9001:        $rest=join('.',@therest);
                   9002:     } else {
                   9003:        $rest='';
                   9004:     }
1.320     albertel 9005: 
1.57      www      9006:     my $qualifierrest=$qualifier;
                   9007:     if ($rest) { $qualifierrest.='.'.$rest; }
                   9008:     my $spacequalifierrest=$space;
                   9009:     if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28      www      9010:     if ($realm eq 'user') {
1.48      www      9011: # --------------------------------------------------------------- user.resource
                   9012: 	if ($space eq 'resource') {
1.651     albertel 9013: 	    if ( (defined($Apache::lonhomework::parsing_a_problem)
                   9014: 		  || defined($Apache::lonhomework::parsing_a_task))
                   9015: 		 &&
1.744     albertel 9016: 		 ($symbparm eq &symbread()) ) {	
                   9017: 		# if we are in the middle of processing the resource the
                   9018: 		# get the value we are planning on committing
                   9019:                 if (defined($Apache::lonhomework::results{$qualifierrest})) {
                   9020:                     return $Apache::lonhomework::results{$qualifierrest};
                   9021:                 } else {
                   9022:                     return $Apache::lonhomework::history{$qualifierrest};
                   9023:                 }
1.335     albertel 9024: 	    } else {
1.359     albertel 9025: 		my %restored;
1.620     albertel 9026: 		if ($publicuser || $env{'request.state'} eq 'construct') {
1.359     albertel 9027: 		    %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
                   9028: 		} else {
                   9029: 		    %restored=&restore($symbparm,$courseid,$udom,$uname);
                   9030: 		}
1.335     albertel 9031: 		return $restored{$qualifierrest};
                   9032: 	    }
1.48      www      9033: # ----------------------------------------------------------------- user.access
                   9034:         } elsif ($space eq 'access') {
1.218     albertel 9035: 	    # FIXME - not supporting calls for a specific user
1.48      www      9036:             return &allowed($qualifier,$rest);
                   9037: # ------------------------------------------ user.preferences, user.environment
                   9038:         } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620     albertel 9039: 	    if (($uname eq $env{'user.name'}) &&
                   9040: 		($udom eq $env{'user.domain'})) {
                   9041: 		return $env{join('.',('environment',$qualifierrest))};
1.218     albertel 9042: 	    } else {
1.359     albertel 9043: 		my %returnhash;
                   9044: 		if (!$publicuser) {
                   9045: 		    %returnhash=&userenvironment($udom,$uname,
                   9046: 						 $qualifierrest);
                   9047: 		}
1.218     albertel 9048: 		return $returnhash{$qualifierrest};
                   9049: 	    }
1.48      www      9050: # ----------------------------------------------------------------- user.course
                   9051:         } elsif ($space eq 'course') {
1.218     albertel 9052: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9053:             return $env{join('.',('request.course',$qualifier))};
1.48      www      9054: # ------------------------------------------------------------------- user.role
                   9055:         } elsif ($space eq 'role') {
1.218     albertel 9056: 	    # FIXME - not supporting calls for a specific user
1.620     albertel 9057:             my ($role,$where)=split(/\./,$env{'request.role'});
1.48      www      9058:             if ($qualifier eq 'value') {
                   9059: 		return $role;
                   9060:             } elsif ($qualifier eq 'extent') {
                   9061:                 return $where;
                   9062:             }
                   9063: # ----------------------------------------------------------------- user.domain
                   9064:         } elsif ($space eq 'domain') {
1.218     albertel 9065:             return $udom;
1.48      www      9066: # ------------------------------------------------------------------- user.name
                   9067:         } elsif ($space eq 'name') {
1.218     albertel 9068:             return $uname;
1.48      www      9069: # ---------------------------------------------------- Any other user namespace
1.29      www      9070:         } else {
1.359     albertel 9071: 	    my %reply;
                   9072: 	    if (!$publicuser) {
                   9073: 		%reply=&get($space,[$qualifierrest],$udom,$uname);
                   9074: 	    }
                   9075: 	    return $reply{$qualifierrest};
1.48      www      9076:         }
1.236     www      9077:     } elsif ($realm eq 'query') {
                   9078: # ---------------------------------------------- pull stuff out of query string
1.384     albertel 9079:         &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
                   9080: 						[$spacequalifierrest]);
1.620     albertel 9081: 	return $env{'form.'.$spacequalifierrest}; 
1.236     www      9082:    } elsif ($realm eq 'request') {
1.48      www      9083: # ------------------------------------------------------------- request.browser
                   9084:         if ($space eq 'browser') {
1.1145    bisitz   9085:             return $env{'browser.'.$qualifier};
1.57      www      9086: # ------------------------------------------------------------ request.filename
                   9087:         } else {
1.620     albertel 9088:             return $env{'request.'.$spacequalifierrest};
1.29      www      9089:         }
1.28      www      9090:     } elsif ($realm eq 'course') {
1.48      www      9091: # ---------------------------------------------------------- course.description
1.620     albertel 9092:         return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57      www      9093:     } elsif ($realm eq 'resource') {
1.165     www      9094: 
1.620     albertel 9095: 	if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539     albertel 9096: 	    if (!$symbparm) { $symbparm=&symbread(); }
                   9097: 	}
1.693     albertel 9098: 
                   9099: 	if ($space eq 'title') {
                   9100: 	    if (!$symbparm) { $symbparm = $env{'request.filename'}; }
                   9101: 	    return &gettitle($symbparm);
                   9102: 	}
                   9103: 	
                   9104: 	if ($space eq 'map') {
                   9105: 	    my ($map) = &decode_symb($symbparm);
                   9106: 	    return &symbread($map);
                   9107: 	}
1.905     albertel 9108: 	if ($space eq 'filename') {
                   9109: 	    if ($symbparm) {
                   9110: 		return &clutter((&decode_symb($symbparm))[2]);
                   9111: 	    }
                   9112: 	    return &hreflocation('',$env{'request.filename'});
                   9113: 	}
1.693     albertel 9114: 
                   9115: 	my ($section, $group, @groups);
1.593     albertel 9116: 	my ($courselevelm,$courselevel);
1.539     albertel 9117: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9118: 	    $courseid eq $env{'request.course.id'}) {
1.165     www      9119: 
1.218     albertel 9120: 	    #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165     www      9121: 
1.60      www      9122: # ----------------------------------------------------- Cascading lookup scheme
1.218     albertel 9123: 	    my $symbp=$symbparm;
1.735     albertel 9124: 	    my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218     albertel 9125: 
                   9126: 	    my $symbparm=$symbp.'.'.$spacequalifierrest;
                   9127: 	    my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
                   9128: 
1.620     albertel 9129: 	    if (($env{'user.name'} eq $uname) &&
                   9130: 		($env{'user.domain'} eq $udom)) {
                   9131: 		$section=$env{'request.course.sec'};
1.733     raeburn  9132:                 @groups = split(/:/,$env{'request.course.groups'});  
                   9133:                 @groups=&sort_course_groups($courseid,@groups); 
1.218     albertel 9134: 	    } else {
1.539     albertel 9135: 		if (! defined($usection)) {
1.551     albertel 9136: 		    $section=&getsection($udom,$uname,$courseid);
1.539     albertel 9137: 		} else {
                   9138: 		    $section = $usection;
                   9139: 		}
1.733     raeburn  9140:                 @groups = &get_users_groups($udom,$uname,$courseid);
1.218     albertel 9141: 	    }
                   9142: 
                   9143: 	    my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
                   9144: 	    my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
                   9145: 	    my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
                   9146: 
1.593     albertel 9147: 	    $courselevel=$courseid.'.'.$spacequalifierrest;
1.218     albertel 9148: 	    my $courselevelr=$courseid.'.'.$symbparm;
1.593     albertel 9149: 	    $courselevelm=$courseid.'.'.$mapparm;
1.69      www      9150: 
1.60      www      9151: # ----------------------------------------------------------- first, check user
1.624     albertel 9152: 
                   9153: 	    my $userreply=&resdata($uname,$udom,'user',
1.927     albertel 9154: 				       ([$courselevelr,'resource'],
                   9155: 					[$courselevelm,'map'     ],
                   9156: 					[$courselevel, 'course'  ]));
1.931     albertel 9157: 	    if (defined($userreply)) { return &get_reply($userreply); }
1.95      www      9158: 
1.594     albertel 9159: # ------------------------------------------------ second, check some of course
1.684     raeburn  9160:             my $coursereply;
1.691     raeburn  9161:             if (@groups > 0) {
                   9162:                 $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
                   9163:                                        $mapparm,$spacequalifierrest);
1.927     albertel 9164:                 if (defined($coursereply)) { return &get_reply($coursereply); }
1.684     raeburn  9165:             }
1.96      www      9166: 
1.684     raeburn  9167: 	    $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927     albertel 9168: 				  $env{'course.'.$courseid.'.domain'},
                   9169: 				  'course',
                   9170: 				  ([$seclevelr,   'resource'],
                   9171: 				   [$seclevelm,   'map'     ],
                   9172: 				   [$seclevel,    'course'  ],
                   9173: 				   [$courselevelr,'resource']));
                   9174: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.200     www      9175: 
1.60      www      9176: # ------------------------------------------------------ third, check map parms
1.218     albertel 9177: 	    my %parmhash=();
                   9178: 	    my $thisparm='';
                   9179: 	    if (tie(%parmhash,'GDBM_File',
1.620     albertel 9180: 		    $env{'request.course.fn'}.'_parms.db',
1.256     albertel 9181: 		    &GDBM_READER(),0640)) {
1.218     albertel 9182: 		$thisparm=$parmhash{$symbparm};
                   9183: 		untie(%parmhash);
                   9184: 	    }
1.927     albertel 9185: 	    if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218     albertel 9186: 	}
1.594     albertel 9187: # ------------------------------------------ fourth, look in resource metadata
1.71      www      9188: 
1.218     albertel 9189: 	$spacequalifierrest=~s/\./\_/;
1.282     albertel 9190: 	my $filename;
                   9191: 	if (!$symbparm) { $symbparm=&symbread(); }
                   9192: 	if ($symbparm) {
1.409     www      9193: 	    $filename=(&decode_symb($symbparm))[2];
1.282     albertel 9194: 	} else {
1.620     albertel 9195: 	    $filename=$env{'request.filename'};
1.282     albertel 9196: 	}
                   9197: 	my $metadata=&metadata($filename,$spacequalifierrest);
1.927     albertel 9198: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282     albertel 9199: 	$metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927     albertel 9200: 	if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142     www      9201: 
1.927     albertel 9202: # ---------------------------------------------- fourth, look in rest of course
1.593     albertel 9203: 	if ($symbparm && defined($courseid) && 
1.620     albertel 9204: 	    $courseid eq $env{'request.course.id'}) {
1.624     albertel 9205: 	    my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
                   9206: 				     $env{'course.'.$courseid.'.domain'},
                   9207: 				     'course',
1.927     albertel 9208: 				     ([$courselevelm,'map'   ],
                   9209: 				      [$courselevel, 'course']));
                   9210: 	    if (defined($coursereply)) { return &get_reply($coursereply); }
1.593     albertel 9211: 	}
1.145     www      9212: # ------------------------------------------------------------------ Cascade up
1.218     albertel 9213: 	unless ($space eq '0') {
1.336     albertel 9214: 	    my @parts=split(/_/,$space);
                   9215: 	    my $id=pop(@parts);
                   9216: 	    my $part=join('_',@parts);
                   9217: 	    if ($part eq '') { $part='0'; }
1.927     albertel 9218: 	    my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395     albertel 9219: 				 $symbparm,$udom,$uname,$section,1);
1.938     raeburn  9220: 	    if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218     albertel 9221: 	}
1.395     albertel 9222: 	if ($recurse) { return undef; }
                   9223: 	my $pack_def=&packages_tab_default($filename,$varname);
1.927     albertel 9224: 	if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48      www      9225: # ---------------------------------------------------- Any other user namespace
                   9226:     } elsif ($realm eq 'environment') {
                   9227: # ----------------------------------------------------------------- environment
1.620     albertel 9228: 	if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
                   9229: 	    return $env{'environment.'.$spacequalifierrest};
1.219     albertel 9230: 	} else {
1.770     albertel 9231: 	    if ($uname eq 'anonymous' && $udom eq '') {
                   9232: 		return '';
                   9233: 	    }
1.219     albertel 9234: 	    my %returnhash=&userenvironment($udom,$uname,
                   9235: 					    $spacequalifierrest);
                   9236: 	    return $returnhash{$spacequalifierrest};
                   9237: 	}
1.28      www      9238:     } elsif ($realm eq 'system') {
1.48      www      9239: # ----------------------------------------------------------------- system.time
                   9240: 	if ($space eq 'time') {
                   9241: 	    return time;
                   9242:         }
1.696     albertel 9243:     } elsif ($realm eq 'server') {
                   9244: # ----------------------------------------------------------------- system.time
                   9245: 	if ($space eq 'name') {
                   9246: 	    return $ENV{'SERVER_NAME'};
                   9247:         }
1.28      www      9248:     }
1.48      www      9249:     return '';
1.61      www      9250: }
                   9251: 
1.927     albertel 9252: sub get_reply {
                   9253:     my ($reply_value) = @_;
1.940     raeburn  9254:     if (ref($reply_value) eq 'ARRAY') {
                   9255:         if (wantarray) {
                   9256: 	    return @$reply_value;
                   9257:         }
                   9258:         return $reply_value->[0];
                   9259:     } else {
                   9260:         return $reply_value;
1.927     albertel 9261:     }
                   9262: }
                   9263: 
1.691     raeburn  9264: sub check_group_parms {
                   9265:     my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
                   9266:     my @groupitems = ();
                   9267:     my $resultitem;
1.927     albertel 9268:     my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691     raeburn  9269:     foreach my $group (@{$groups}) {
                   9270:         foreach my $level (@levels) {
1.927     albertel 9271:              my $item = $courseid.'.['.$group.'].'.$level->[0];
                   9272:              push(@groupitems,[$item,$level->[1]]);
1.691     raeburn  9273:         }
                   9274:     }
                   9275:     my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
                   9276:                             $env{'course.'.$courseid.'.domain'},
                   9277:                                      'course',@groupitems);
                   9278:     return $coursereply;
                   9279: }
                   9280: 
                   9281: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733     raeburn  9282:     my ($courseid,@groups) = @_;
                   9283:     @groups = sort(@groups);
1.691     raeburn  9284:     return @groups;
                   9285: }
                   9286: 
1.395     albertel 9287: sub packages_tab_default {
                   9288:     my ($uri,$varname)=@_;
                   9289:     my (undef,$part,$name)=split(/\./,$varname);
1.738     albertel 9290: 
                   9291:     my (@extension,@specifics,$do_default);
                   9292:     foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395     albertel 9293: 	my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738     albertel 9294: 	if ($pack_type eq 'default') {
                   9295: 	    $do_default=1;
                   9296: 	} elsif ($pack_type eq 'extension') {
                   9297: 	    push(@extension,[$package,$pack_type,$pack_part]);
1.885     albertel 9298: 	} elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848     albertel 9299: 	    # only look at packages defaults for packages that this id is
1.738     albertel 9300: 	    push(@specifics,[$package,$pack_type,$pack_part]);
                   9301: 	}
                   9302:     }
                   9303:     # first look for a package that matches the requested part id
                   9304:     foreach my $package (@specifics) {
                   9305: 	my (undef,$pack_type,$pack_part)=@{$package};
                   9306: 	next if ($pack_part ne $part);
                   9307: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9308: 	    return $packagetab{"$pack_type&$name&default"};
                   9309: 	}
                   9310:     }
                   9311:     # look for any possible matching non extension_ package
                   9312:     foreach my $package (@specifics) {
                   9313: 	my (undef,$pack_type,$pack_part)=@{$package};
1.468     albertel 9314: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9315: 	    return $packagetab{"$pack_type&$name&default"};
                   9316: 	}
1.585     albertel 9317: 	if ($pack_type eq 'part') { $pack_part='0'; }
1.468     albertel 9318: 	if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
                   9319: 	    return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395     albertel 9320: 	}
                   9321:     }
1.738     albertel 9322:     # look for any posible extension_ match
                   9323:     foreach my $package (@extension) {
                   9324: 	my ($package,$pack_type)=@{$package};
                   9325: 	if (defined($packagetab{"$pack_type&$name&default"})) {
                   9326: 	    return $packagetab{"$pack_type&$name&default"};
                   9327: 	}
                   9328: 	if (defined($packagetab{$package."&$name&default"})) {
                   9329: 	    return $packagetab{$package."&$name&default"};
                   9330: 	}
                   9331:     }
                   9332:     # look for a global default setting
                   9333:     if ($do_default && defined($packagetab{"default&$name&default"})) {
                   9334: 	return $packagetab{"default&$name&default"};
                   9335:     }
1.395     albertel 9336:     return undef;
                   9337: }
                   9338: 
1.334     albertel 9339: sub add_prefix_and_part {
                   9340:     my ($prefix,$part)=@_;
                   9341:     my $keyroot;
                   9342:     if (defined($prefix) && $prefix !~ /^__/) {
                   9343: 	# prefix that has a part already
                   9344: 	$keyroot=$prefix;
                   9345:     } elsif (defined($prefix)) {
                   9346: 	# prefix that is missing a part
                   9347: 	if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
                   9348:     } else {
                   9349: 	# no prefix at all
                   9350: 	if (defined($part)) { $keyroot='_'.$part; }
                   9351:     }
                   9352:     return $keyroot;
                   9353: }
                   9354: 
1.71      www      9355: # ---------------------------------------------------------------- Get metadata
                   9356: 
1.599     albertel 9357: my %metaentry;
1.1070    www      9358: my %importedpartids;
1.71      www      9359: sub metadata {
1.176     www      9360:     my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71      www      9361:     $uri=&declutter($uri);
1.288     albertel 9362:     # if it is a non metadata possible uri return quickly
1.529     albertel 9363:     if (($uri eq '') || 
                   9364: 	(($uri =~ m|^/*adm/|) && 
1.698     albertel 9365: 	     ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108    raeburn  9366:         ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924     albertel 9367: 	return undef;
                   9368:     }
1.1140    www      9369:     if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) 
1.924     albertel 9370: 	&& &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468     albertel 9371: 	return undef;
1.288     albertel 9372:     }
1.73      www      9373:     my $filename=$uri;
                   9374:     $uri=~s/\.meta$//;
1.172     www      9375: #
                   9376: # Is the metadata already cached?
1.177     www      9377: # Look at timestamp of caching
1.172     www      9378: # Everything is cached by the main uri, libraries are never directly cached
                   9379: #
1.428     albertel 9380:     if (!defined($liburi)) {
1.599     albertel 9381: 	my ($result,$cached)=&is_cached_new('meta',$uri);
1.428     albertel 9382: 	if (defined($cached)) { return $result->{':'.$what}; }
                   9383:     }
                   9384:     {
1.1069    www      9385: # Imported parts would go here
1.1070    www      9386:         my %importedids=();
                   9387:         my @origfileimportpartids=();
1.1069    www      9388:         my $importedparts=0;
1.172     www      9389: #
                   9390: # Is this a recursive call for a library?
                   9391: #
1.599     albertel 9392: #	if (! exists($metacache{$uri})) {
                   9393: #	    $metacache{$uri}={};
                   9394: #	}
1.924     albertel 9395: 	my $cachetime = 60*60;
1.171     www      9396:         if ($liburi) {
                   9397: 	    $liburi=&declutter($liburi);
                   9398:             $filename=$liburi;
1.401     bowersj2 9399:         } else {
1.599     albertel 9400: 	    &devalidate_cache_new('meta',$uri);
                   9401: 	    undef(%metaentry);
1.401     bowersj2 9402: 	}
1.140     www      9403:         my %metathesekeys=();
1.73      www      9404:         unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489     albertel 9405: 	my $metastring;
1.1140    www      9406: 	if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929     albertel 9407: 	    my $which = &hreflocation('','/'.($liburi || $uri));
1.924     albertel 9408: 	    $metastring = 
1.929     albertel 9409: 		&Apache::lonnet::ssi_body($which,
1.924     albertel 9410: 					  ('grade_target' => 'meta'));
                   9411: 	    $cachetime = 1; # only want this cached in the child not long term
1.1108    raeburn  9412: 	} elsif (($uri !~ m -^(editupload)/-) && 
                   9413:                  ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543     albertel 9414: 	    my $file=&filelocation('',&clutter($filename));
1.599     albertel 9415: 	    #push(@{$metaentry{$uri.'.file'}},$file);
1.543     albertel 9416: 	    $metastring=&getfile($file);
1.489     albertel 9417: 	}
1.208     albertel 9418:         my $parser=HTML::LCParser->new(\$metastring);
1.71      www      9419:         my $token;
1.140     www      9420:         undef %metathesekeys;
1.71      www      9421:         while ($token=$parser->get_token) {
1.339     albertel 9422: 	    if ($token->[0] eq 'S') {
                   9423: 		if (defined($token->[2]->{'package'})) {
1.172     www      9424: #
                   9425: # This is a package - get package info
                   9426: #
1.339     albertel 9427: 		    my $package=$token->[2]->{'package'};
                   9428: 		    my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9429: 		    if (defined($token->[2]->{'id'})) { 
                   9430: 			$keyroot.='_'.$token->[2]->{'id'}; 
                   9431: 		    }
1.599     albertel 9432: 		    if ($metaentry{':packages'}) {
                   9433: 			$metaentry{':packages'}.=','.$package.$keyroot;
1.339     albertel 9434: 		    } else {
1.599     albertel 9435: 			$metaentry{':packages'}=$package.$keyroot;
1.339     albertel 9436: 		    }
1.736     albertel 9437: 		    foreach my $pack_entry (keys(%packagetab)) {
1.432     albertel 9438: 			my $part=$keyroot;
                   9439: 			$part=~s/^\_//;
1.736     albertel 9440: 			if ($pack_entry=~/^\Q$package\E\&/ || 
                   9441: 			    $pack_entry=~/^\Q$package\E_0\&/) {
                   9442: 			    my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395     albertel 9443: 			    # ignore package.tab specified default values
                   9444:                             # here &package_tab_default() will fetch those
                   9445: 			    if ($subp eq 'default') { next; }
1.736     albertel 9446: 			    my $value=$packagetab{$pack_entry};
1.432     albertel 9447: 			    my $unikey;
                   9448: 			    if ($pack =~ /_0$/) {
                   9449: 				$unikey='parameter_0_'.$name;
                   9450: 				$part=0;
                   9451: 			    } else {
                   9452: 				$unikey='parameter'.$keyroot.'_'.$name;
                   9453: 			    }
1.339     albertel 9454: 			    if ($subp eq 'display') {
                   9455: 				$value.=' [Part: '.$part.']';
                   9456: 			    }
1.599     albertel 9457: 			    $metaentry{':'.$unikey.'.part'}=$part;
1.395     albertel 9458: 			    $metathesekeys{$unikey}=1;
1.599     albertel 9459: 			    unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9460: 				$metaentry{':'.$unikey.'.'.$subp}=$value;
1.339     albertel 9461: 			    }
1.599     albertel 9462: 			    if (defined($metaentry{':'.$unikey.'.default'})) {
                   9463: 				$metaentry{':'.$unikey}=
                   9464: 				    $metaentry{':'.$unikey.'.default'};
1.356     albertel 9465: 			    }
1.339     albertel 9466: 			}
                   9467: 		    }
                   9468: 		} else {
1.172     www      9469: #
                   9470: # This is not a package - some other kind of start tag
1.339     albertel 9471: #
                   9472: 		    my $entry=$token->[1];
1.1068    www      9473: 		    my $unikey='';
1.175     www      9474: 
1.339     albertel 9475: 		    if ($entry eq 'import') {
1.175     www      9476: #
                   9477: # Importing a library here
1.339     albertel 9478: #
1.1067    www      9479:                         my $location=$parser->get_text('/import');
                   9480:                         my $dir=$filename;
                   9481:                         $dir=~s|[^/]*$||;
                   9482:                         $location=&filelocation($dir,$location);
1.1069    www      9483:                        
1.1068    www      9484:                         my $importmode=$token->[2]->{'importmode'};
                   9485:                         if ($importmode eq 'problem') {
1.1069    www      9486: # Import as problem/response
1.1068    www      9487:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9488:                         } elsif ($importmode eq 'part') {
                   9489: # Import as part(s)
1.1069    www      9490:                            $importedparts=1;
                   9491: # We need to get the original file and the imported file to get the part order correct
                   9492: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
                   9493: # Load and inspect original file
1.1070    www      9494:                            if ($#origfileimportpartids<0) {
                   9495:                               undef(%importedpartids);
                   9496:                               my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
                   9497:                               my $origfile=&getfile($origfilelocation);
                   9498:                               @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9499:                            }
                   9500: 
1.1069    www      9501: # Load and inspect imported file
                   9502:                            my $impfile=&getfile($location);
                   9503:                            my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
                   9504:                            if ($#impfilepartids>=0) {
                   9505: # This problem had parts
1.1070    www      9506:                                $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069    www      9507:                            } else {
                   9508: # Importing by turning a single problem into a problem part
                   9509: # It gets the import-tags ID as part-ID
                   9510:                                $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070    www      9511:                                $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069    www      9512:                            }
1.1068    www      9513:                         } else {
                   9514: # Normal import
                   9515:                            $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9516:                            if (defined($token->[2]->{'id'})) {
                   9517:                               $unikey.='_'.$token->[2]->{'id'};
                   9518:                            }
1.1067    www      9519:                         }
                   9520: 
1.339     albertel 9521: 			if ($depthcount<20) {
1.736     albertel 9522: 			    my $metadata = 
                   9523: 				&metadata($uri,'keys', $location,$unikey,
                   9524: 					  $depthcount+1);
                   9525: 			    foreach my $meta (split(',',$metadata)) {
                   9526: 				$metaentry{':'.$meta}=$metaentry{':'.$meta};
                   9527: 				$metathesekeys{$meta}=1;
1.339     albertel 9528: 			    }
1.1068    www      9529: 			
                   9530:                         }
1.1067    www      9531: 		    } else {
                   9532: #
                   9533: # Not importing, some other kind of non-package, non-library start tag
                   9534: # 
                   9535:                         $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
                   9536:                         if (defined($token->[2]->{'id'})) {
                   9537:                             $unikey.='_'.$token->[2]->{'id'};
                   9538:                         }
1.339     albertel 9539: 			if (defined($token->[2]->{'name'})) { 
                   9540: 			    $unikey.='_'.$token->[2]->{'name'}; 
                   9541: 			}
                   9542: 			$metathesekeys{$unikey}=1;
1.736     albertel 9543: 			foreach my $param (@{$token->[3]}) {
                   9544: 			    $metaentry{':'.$unikey.'.'.$param} =
                   9545: 				$token->[2]->{$param};
1.339     albertel 9546: 			}
                   9547: 			my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599     albertel 9548: 			my $default=$metaentry{':'.$unikey.'.default'};
1.339     albertel 9549: 			if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
                   9550: 		 # only ws inside the tag, and not in default, so use default
                   9551: 		 # as value
1.599     albertel 9552: 			    $metaentry{':'.$unikey}=$default;
1.908     albertel 9553: 			} elsif ( $internaltext =~ /\S/ ) {
                   9554: 		  # something interesting inside the tag
                   9555: 			    $metaentry{':'.$unikey}=$internaltext;
1.339     albertel 9556: 			} else {
1.908     albertel 9557: 		  # no interesting values, don't set a default
1.339     albertel 9558: 			}
1.172     www      9559: # end of not-a-package not-a-library import
1.339     albertel 9560: 		    }
1.172     www      9561: # end of not-a-package start tag
1.339     albertel 9562: 		}
1.172     www      9563: # the next is the end of "start tag"
1.339     albertel 9564: 	    }
                   9565: 	}
1.483     albertel 9566: 	my ($extension) = ($uri =~ /\.(\w+)$/);
1.883     albertel 9567: 	$extension = lc($extension);
                   9568: 	if ($extension eq 'htm') { $extension='html'; }
                   9569: 
1.737     albertel 9570: 	foreach my $key (keys(%packagetab)) {
1.483     albertel 9571: 	    #no specific packages #how's our extension
                   9572: 	    if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488     albertel 9573: 	    &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483     albertel 9574: 					 \%metathesekeys);
                   9575: 	}
1.883     albertel 9576: 
                   9577: 	if (!exists($metaentry{':packages'})
                   9578: 	    || $packagetab{"import_defaults&extension_$extension"}) {
1.737     albertel 9579: 	    foreach my $key (keys(%packagetab)) {
1.483     albertel 9580: 		#no specific packages well let's get default then
                   9581: 		if ($key!~/^default&/) { next; }
1.488     albertel 9582: 		&metadata_create_package_def($uri,$key,'default',
1.483     albertel 9583: 					     \%metathesekeys);
                   9584: 	    }
                   9585: 	}
1.338     www      9586: # are there custom rights to evaluate
1.599     albertel 9587: 	if ($metaentry{':copyright'} eq 'custom') {
1.339     albertel 9588: 
1.338     www      9589:     #
                   9590:     # Importing a rights file here
1.339     albertel 9591:     #
                   9592: 	    unless ($depthcount) {
1.599     albertel 9593: 		my $location=$metaentry{':customdistributionfile'};
1.339     albertel 9594: 		my $dir=$filename;
                   9595: 		$dir=~s|[^/]*$||;
                   9596: 		$location=&filelocation($dir,$location);
1.736     albertel 9597: 		my $rights_metadata =
                   9598: 		    &metadata($uri,'keys',$location,'_rights',
                   9599: 			      $depthcount+1);
                   9600: 		foreach my $rights (split(',',$rights_metadata)) {
                   9601: 		    #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
                   9602: 		    $metathesekeys{$rights}=1;
1.339     albertel 9603: 		}
                   9604: 	    }
                   9605: 	}
1.737     albertel 9606: 	# uniqifiy package listing
                   9607: 	my %seen;
                   9608: 	my @uniq_packages =
                   9609: 	    grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
                   9610: 	$metaentry{':packages'} = join(',',@uniq_packages);
                   9611: 
1.1070    www      9612:         if ($importedparts) {
                   9613: # We had imported parts and need to rebuild partorder
                   9614:            $metaentry{':partorder'}='';
                   9615:            $metathesekeys{'partorder'}=1;
                   9616:            for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
                   9617:                if ($origfileimportpartids[$index] eq 'part') {
                   9618: # original part, part of the problem
                   9619:                   $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
                   9620:                } else {
                   9621: # we have imported parts at this position
                   9622:                   $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
                   9623:                }
                   9624:            }
                   9625:            $metaentry{':partorder'}=~s/^\,//;
                   9626:         }
                   9627: 
1.737     albertel 9628: 	$metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599     albertel 9629: 	&metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
                   9630: 	$metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924     albertel 9631: 	&do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177     www      9632: # this is the end of "was not already recently cached
1.71      www      9633:     }
1.599     albertel 9634:     return $metaentry{':'.$what};
1.261     albertel 9635: }
                   9636: 
1.488     albertel 9637: sub metadata_create_package_def {
1.483     albertel 9638:     my ($uri,$key,$package,$metathesekeys)=@_;
                   9639:     my ($pack,$name,$subp)=split(/\&/,$key);
                   9640:     if ($subp eq 'default') { next; }
                   9641:     
1.599     albertel 9642:     if (defined($metaentry{':packages'})) {
                   9643: 	$metaentry{':packages'}.=','.$package;
1.483     albertel 9644:     } else {
1.599     albertel 9645: 	$metaentry{':packages'}=$package;
1.483     albertel 9646:     }
                   9647:     my $value=$packagetab{$key};
                   9648:     my $unikey;
                   9649:     $unikey='parameter_0_'.$name;
1.599     albertel 9650:     $metaentry{':'.$unikey.'.part'}=0;
1.483     albertel 9651:     $$metathesekeys{$unikey}=1;
1.599     albertel 9652:     unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
                   9653: 	$metaentry{':'.$unikey.'.'.$subp}=$value;
1.483     albertel 9654:     }
1.599     albertel 9655:     if (defined($metaentry{':'.$unikey.'.default'})) {
                   9656: 	$metaentry{':'.$unikey}=
                   9657: 	    $metaentry{':'.$unikey.'.default'};
1.483     albertel 9658:     }
                   9659: }
                   9660: 
1.261     albertel 9661: sub metadata_generate_part0 {
                   9662:     my ($metadata,$metacache,$uri) = @_;
                   9663:     my %allnames;
1.737     albertel 9664:     foreach my $metakey (keys(%$metadata)) {
1.261     albertel 9665: 	if ($metakey=~/^parameter\_(.*)/) {
1.428     albertel 9666: 	  my $part=$$metacache{':'.$metakey.'.part'};
                   9667: 	  my $name=$$metacache{':'.$metakey.'.name'};
1.356     albertel 9668: 	  if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261     albertel 9669: 	    $allnames{$name}=$part;
                   9670: 	  }
                   9671: 	}
                   9672:     }
                   9673:     foreach my $name (keys(%allnames)) {
                   9674:       $$metadata{"parameter_0_$name"}=1;
1.428     albertel 9675:       my $key=":parameter_0_$name";
1.261     albertel 9676:       $$metacache{"$key.part"}='0';
                   9677:       $$metacache{"$key.name"}=$name;
1.428     albertel 9678:       $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261     albertel 9679: 					   $allnames{$name}.'_'.$name.
                   9680: 					   '.type'};
1.428     albertel 9681:       my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261     albertel 9682: 			     '.display'};
1.644     www      9683:       my $expr='[Part: '.$allnames{$name}.']';
1.479     albertel 9684:       $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261     albertel 9685:       $$metacache{"$key.display"}=$olddis;
                   9686:     }
1.71      www      9687: }
                   9688: 
1.764     albertel 9689: # ------------------------------------------------------ Devalidate title cache
                   9690: 
                   9691: sub devalidate_title_cache {
                   9692:     my ($url)=@_;
                   9693:     if (!$env{'request.course.id'}) { return; }
                   9694:     my $symb=&symbread($url);
                   9695:     if (!$symb) { return; }
                   9696:     my $key=$env{'request.course.id'}."\0".$symb;
                   9697:     &devalidate_cache_new('title',$key);
                   9698: }
                   9699: 
1.1014    droeschl 9700: # ------------------------------------------------- Get the title of a course
                   9701: 
                   9702: sub current_course_title {
                   9703:     return $env{ 'course.' . $env{'request.course.id'} . '.description' };
                   9704: }
1.301     www      9705: # ------------------------------------------------- Get the title of a resource
                   9706: 
                   9707: sub gettitle {
                   9708:     my $urlsymb=shift;
                   9709:     my $symb=&symbread($urlsymb);
1.534     albertel 9710:     if ($symb) {
1.620     albertel 9711: 	my $key=$env{'request.course.id'}."\0".$symb;
1.599     albertel 9712: 	my ($result,$cached)=&is_cached_new('title',$key);
1.575     albertel 9713: 	if (defined($cached)) { 
                   9714: 	    return $result;
                   9715: 	}
1.534     albertel 9716: 	my ($map,$resid,$url)=&decode_symb($symb);
                   9717: 	my $title='';
1.907     albertel 9718: 	if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
                   9719: 	    $title = $env{'course.'.$env{'request.course.id'}.'.description'};
                   9720: 	} else {
                   9721: 	    if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
                   9722: 		    &GDBM_READER(),0640)) {
                   9723: 		my $mapid=$bighash{'map_pc_'.&clutter($map)};
                   9724: 		$title=$bighash{'title_'.$mapid.'.'.$resid};
                   9725: 		untie(%bighash);
                   9726: 	    }
1.534     albertel 9727: 	}
                   9728: 	$title=~s/\&colon\;/\:/gs;
                   9729: 	if ($title) {
1.1159    www      9730: # Remember both $symb and $title for dynamic metadata
                   9731:             $accesshash{$symb.'___crstitle'}=$title;
1.1161    www      9732:             $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159    www      9733: # Cache this title and then return it
1.599     albertel 9734: 	    return &do_cache_new('title',$key,$title,600);
1.534     albertel 9735: 	}
                   9736: 	$urlsymb=$url;
                   9737:     }
                   9738:     my $title=&metadata($urlsymb,'title');
                   9739:     if (!$title) { $title=(split('/',$urlsymb))[-1]; }    
                   9740:     return $title;
1.301     www      9741: }
1.613     albertel 9742: 
1.614     albertel 9743: sub get_slot {
                   9744:     my ($which,$cnum,$cdom)=@_;
                   9745:     if (!$cnum || !$cdom) {
1.790     albertel 9746: 	(undef,my $courseid)=&whichuser();
1.620     albertel 9747: 	$cdom=$env{'course.'.$courseid.'.domain'};
                   9748: 	$cnum=$env{'course.'.$courseid.'.num'};
1.614     albertel 9749:     }
1.703     albertel 9750:     my $key=join("\0",'slots',$cdom,$cnum,$which);
                   9751:     my %slotinfo;
                   9752:     if (exists($remembered{$key})) {
                   9753: 	$slotinfo{$which} = $remembered{$key};
                   9754:     } else {
                   9755: 	%slotinfo=&get('slots',[$which],$cdom,$cnum);
                   9756: 	&Apache::lonhomework::showhash(%slotinfo);
                   9757: 	my ($tmp)=keys(%slotinfo);
                   9758: 	if ($tmp=~/^error:/) { return (); }
                   9759: 	$remembered{$key} = $slotinfo{$which};
                   9760:     }
1.616     albertel 9761:     if (ref($slotinfo{$which}) eq 'HASH') {
                   9762: 	return %{$slotinfo{$which}};
                   9763:     }
                   9764:     return $slotinfo{$which};
1.614     albertel 9765: }
1.1150    raeburn  9766: 
                   9767: sub get_reservable_slots {
                   9768:     my ($cnum,$cdom,$uname,$udom) = @_;
                   9769:     my $now = time;
                   9770:     my $reservable_info;
                   9771:     my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
                   9772:     if (exists($remembered{$key})) {
                   9773:         $reservable_info = $remembered{$key};
                   9774:     } else {
                   9775:         my %resv;
                   9776:         ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
                   9777:         &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
                   9778:         $reservable_info = \%resv;
                   9779:         $remembered{$key} = $reservable_info;
                   9780:     }
                   9781:     return $reservable_info;
                   9782: }
                   9783: 
                   9784: sub get_course_slots {
                   9785:     my ($cnum,$cdom) = @_;
                   9786:     my $hashid=$cnum.':'.$cdom;
                   9787:     my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
                   9788:     if (defined($cached)) {
                   9789:         if (ref($result) eq 'HASH') {
                   9790:             return %{$result};
                   9791:         }
                   9792:     } else {
                   9793:         my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
                   9794:         my ($tmp) = keys(%slots);
                   9795:         if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9796:             &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
                   9797:             return %slots;
                   9798:         }
                   9799:     }
                   9800:     return;
                   9801: }
                   9802: 
                   9803: sub devalidate_slots_cache {
                   9804:     my ($cnum,$cdom)=@_;
                   9805:     my $hashid=$cnum.':'.$cdom;
                   9806:     &devalidate_cache_new('allslots',$hashid);
                   9807: }
                   9808: 
1.31      www      9809: # ------------------------------------------------- Update symbolic store links
                   9810: 
                   9811: sub symblist {
                   9812:     my ($mapname,%newhash)=@_;
1.438     www      9813:     $mapname=&deversion(&declutter($mapname));
1.31      www      9814:     my %hash;
1.620     albertel 9815:     if (($env{'request.course.fn'}) && (%newhash)) {
                   9816:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9817:                       &GDBM_WRCREAT(),0640)) {
1.1000    raeburn  9818: 	    foreach my $url (keys(%newhash)) {
1.711     albertel 9819: 		next if ($url eq 'last_known'
                   9820: 			 && $env{'form.no_update_last_known'});
                   9821: 		$hash{declutter($url)}=&encode_symb($mapname,
                   9822: 						    $newhash{$url}->[1],
                   9823: 						    $newhash{$url}->[0]);
1.191     harris41 9824:             }
1.31      www      9825:             if (untie(%hash)) {
                   9826: 		return 'ok';
                   9827:             }
                   9828:         }
                   9829:     }
                   9830:     return 'error';
1.212     www      9831: }
                   9832: 
                   9833: # --------------------------------------------------------------- Verify a symb
                   9834: 
                   9835: sub symbverify {
1.510     www      9836:     my ($symb,$thisurl)=@_;
                   9837:     my $thisfn=$thisurl;
1.439     www      9838:     $thisfn=&declutter($thisfn);
1.215     www      9839: # direct jump to resource in page or to a sequence - will construct own symbs
                   9840:     if ($thisfn=~/\.(page|sequence)$/) { return 1; }
                   9841: # check URL part
1.409     www      9842:     my ($map,$resid,$url)=&decode_symb($symb);
1.439     www      9843: 
1.431     www      9844:     unless ($url eq $thisfn) { return 0; }
1.213     www      9845: 
1.216     www      9846:     $symb=&symbclean($symb);
1.510     www      9847:     $thisurl=&deversion($thisurl);
1.439     www      9848:     $thisfn=&deversion($thisfn);
1.213     www      9849: 
                   9850:     my %bighash;
                   9851:     my $okay=0;
1.431     www      9852: 
1.620     albertel 9853:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9854:                             &GDBM_READER(),0640)) {
1.1032    raeburn  9855:         if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
                   9856:             $thisurl =~ s/\?.+$//;
                   9857:         }
1.510     www      9858:         my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102    raeburn  9859:         unless ($ids) {
                   9860:             my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;  
                   9861:             $ids=$bighash{$idkey};
1.216     www      9862:         }
                   9863:         if ($ids) {
                   9864: # ------------------------------------------------------------------- Has ID(s)
1.800     albertel 9865: 	    foreach my $id (split(/\,/,$ids)) {
                   9866: 	       my ($mapid,$resid)=split(/\./,$id);
1.1032    raeburn  9867:                if ($thisfn =~ m{^/adm/wrapper/ext/}) {
                   9868:                    $symb =~ s/\?.+$//;
                   9869:                }
1.216     www      9870:                if (
                   9871:   &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
                   9872:    eq $symb) { 
1.620     albertel 9873: 		   if (($env{'request.role.adv'}) ||
1.1101    raeburn  9874: 		       ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
                   9875:                        ($thisurl eq '/adm/navmaps')) {
1.582     albertel 9876: 		       $okay=1; 
                   9877: 		   }
                   9878: 	       }
1.216     www      9879: 	   }
                   9880:         }
1.213     www      9881: 	untie(%bighash);
                   9882:     }
                   9883:     return $okay;
1.31      www      9884: }
                   9885: 
1.210     www      9886: # --------------------------------------------------------------- Clean-up symb
                   9887: 
                   9888: sub symbclean {
                   9889:     my $symb=shift;
1.568     albertel 9890:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210     www      9891: # remove version from map
                   9892:     $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215     www      9893: 
1.210     www      9894: # remove version from URL
                   9895:     $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213     www      9896: 
1.507     www      9897: # remove wrapper
                   9898: 
1.510     www      9899:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694     albertel 9900:     $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210     www      9901:     return $symb;
1.409     www      9902: }
                   9903: 
                   9904: # ---------------------------------------------- Split symb to find map and url
1.429     albertel 9905: 
                   9906: sub encode_symb {
                   9907:     my ($map,$resid,$url)=@_;
                   9908:     return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
                   9909: }
1.409     www      9910: 
                   9911: sub decode_symb {
1.568     albertel 9912:     my $symb=shift;
                   9913:     if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
                   9914:     my ($map,$resid,$url)=split(/___/,$symb);
1.413     www      9915:     return (&fixversion($map),$resid,&fixversion($url));
                   9916: }
                   9917: 
                   9918: sub fixversion {
                   9919:     my $fn=shift;
1.609     banghart 9920:     if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435     www      9921:     my %bighash;
                   9922:     my $uri=&clutter($fn);
1.620     albertel 9923:     my $key=$env{'request.course.id'}.'_'.$uri;
1.440     www      9924: # is this cached?
1.599     albertel 9925:     my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440     www      9926:     if (defined($cached)) { return $result; }
                   9927: # unfortunately not cached, or expired
1.620     albertel 9928:     if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440     www      9929: 	    &GDBM_READER(),0640)) {
                   9930:  	if ($bighash{'version_'.$uri}) {
                   9931:  	    my $version=$bighash{'version_'.$uri};
1.444     www      9932:  	    unless (($version eq 'mostrecent') || 
                   9933: 		    ($version==&getversion($uri))) {
1.440     www      9934:  		$uri=~s/\.(\w+)$/\.$version\.$1/;
                   9935:  	    }
                   9936:  	}
                   9937:  	untie %bighash;
1.413     www      9938:     }
1.599     albertel 9939:     return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438     www      9940: }
                   9941: 
                   9942: sub deversion {
                   9943:     my $url=shift;
                   9944:     $url=~s/\.\d+\.(\w+)$/\.$1/;
                   9945:     return $url;
1.210     www      9946: }
                   9947: 
1.31      www      9948: # ------------------------------------------------------ Return symb list entry
                   9949: 
                   9950: sub symbread {
1.249     www      9951:     my ($thisfn,$donotrecurse)=@_;
1.542     albertel 9952:     my $cache_str='request.symbread.cached.'.$thisfn;
1.620     albertel 9953:     if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242     www      9954: # no filename provided? try from environment
1.44      www      9955:     unless ($thisfn) {
1.620     albertel 9956:         if ($env{'request.symb'}) {
                   9957: 	    return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539     albertel 9958: 	}
1.620     albertel 9959: 	$thisfn=$env{'request.filename'};
1.44      www      9960:     }
1.569     albertel 9961:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242     www      9962: # is that filename actually a symb? Verify, clean, and return
                   9963:     if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539     albertel 9964: 	if (&symbverify($thisfn,$1)) {
1.620     albertel 9965: 	    return $env{$cache_str}=&symbclean($thisfn);
1.539     albertel 9966: 	}
1.242     www      9967:     }
1.44      www      9968:     $thisfn=declutter($thisfn);
1.31      www      9969:     my %hash;
1.37      www      9970:     my %bighash;
                   9971:     my $syval='';
1.620     albertel 9972:     if (($env{'request.course.fn'}) && ($thisfn)) {
1.481     raeburn  9973:         my $targetfn = $thisfn;
1.609     banghart 9974:         if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481     raeburn  9975:             $targetfn = 'adm/wrapper/'.$thisfn;
                   9976:         }
1.687     albertel 9977: 	if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
                   9978: 	    $targetfn=$1;
                   9979: 	}
1.620     albertel 9980:         if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256     albertel 9981:                       &GDBM_READER(),0640)) {
1.481     raeburn  9982: 	    $syval=$hash{$targetfn};
1.37      www      9983:             untie(%hash);
                   9984:         }
                   9985: # ---------------------------------------------------------- There was an entry
                   9986:         if ($syval) {
1.601     albertel 9987: 	    #unless ($syval=~/\_\d+$/) {
1.620     albertel 9988: 		#unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949     raeburn  9989: 		    #&appenv({'request.ambiguous' => $thisfn});
1.620     albertel 9990: 		    #return $env{$cache_str}='';
1.601     albertel 9991: 		#}    
                   9992: 		#$syval.=$1;
                   9993: 	    #}
1.37      www      9994:         } else {
                   9995: # ------------------------------------------------------- Was not in symb table
1.620     albertel 9996:            if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256     albertel 9997:                             &GDBM_READER(),0640)) {
1.37      www      9998: # ---------------------------------------------- Get ID(s) for current resource
1.280     www      9999:               my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65      www      10000:               unless ($ids) { 
                   10001:                  $ids=$bighash{'ids_/'.$thisfn};
1.242     www      10002:               }
                   10003:               unless ($ids) {
                   10004: # alias?
                   10005: 		  $ids=$bighash{'mapalias_'.$thisfn};
1.65      www      10006:               }
1.37      www      10007:               if ($ids) {
                   10008: # ------------------------------------------------------------------- Has ID(s)
                   10009:                  my @possibilities=split(/\,/,$ids);
1.39      www      10010:                  if ($#possibilities==0) {
                   10011: # ----------------------------------------------- There is only one possibility
1.37      www      10012: 		     my ($mapid,$resid)=split(/\./,$ids);
1.626     albertel 10013: 		     $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10014: 						    $resid,$thisfn);
1.249     www      10015:                  } elsif (!$donotrecurse) {
1.39      www      10016: # ------------------------------------------ There is more than one possibility
                   10017:                      my $realpossible=0;
1.800     albertel 10018:                      foreach my $id (@possibilities) {
                   10019: 			 my $file=$bighash{'src_'.$id};
1.39      www      10020:                          if (&allowed('bre',$file)) {
1.800     albertel 10021:          		    my ($mapid,$resid)=split(/\./,$id);
1.39      www      10022:                             if ($bighash{'map_type_'.$mapid} ne 'page') {
                   10023: 				$realpossible++;
1.626     albertel 10024:                                 $syval=&encode_symb($bighash{'map_id_'.$mapid},
                   10025: 						    $resid,$thisfn);
1.39      www      10026:                             }
                   10027: 			 }
1.191     harris41 10028:                      }
1.39      www      10029: 		     if ($realpossible!=1) { $syval=''; }
1.249     www      10030:                  } else {
                   10031:                      $syval='';
1.37      www      10032:                  }
                   10033: 	      }
                   10034:               untie(%bighash)
1.481     raeburn  10035:            }
1.31      www      10036:         }
1.62      www      10037:         if ($syval) {
1.620     albertel 10038: 	    return $env{$cache_str}=$syval;
1.62      www      10039:         }
1.31      www      10040:     }
1.949     raeburn  10041:     &appenv({'request.ambiguous' => $thisfn});
1.620     albertel 10042:     return $env{$cache_str}='';
1.31      www      10043: }
                   10044: 
                   10045: # ---------------------------------------------------------- Return random seed
                   10046: 
1.32      www      10047: sub numval {
                   10048:     my $txt=shift;
                   10049:     $txt=~tr/A-J/0-9/;
                   10050:     $txt=~tr/a-j/0-9/;
                   10051:     $txt=~tr/K-T/0-9/;
                   10052:     $txt=~tr/k-t/0-9/;
                   10053:     $txt=~tr/U-Z/0-5/;
                   10054:     $txt=~tr/u-z/0-5/;
                   10055:     $txt=~s/\D//g;
1.564     albertel 10056:     if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32      www      10057:     return int($txt);
1.368     albertel 10058: }
                   10059: 
1.484     albertel 10060: sub numval2 {
                   10061:     my $txt=shift;
                   10062:     $txt=~tr/A-J/0-9/;
                   10063:     $txt=~tr/a-j/0-9/;
                   10064:     $txt=~tr/K-T/0-9/;
                   10065:     $txt=~tr/k-t/0-9/;
                   10066:     $txt=~tr/U-Z/0-5/;
                   10067:     $txt=~tr/u-z/0-5/;
                   10068:     $txt=~s/\D//g;
                   10069:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10070:     my $total;
                   10071:     foreach my $val (@txts) { $total+=$val; }
1.564     albertel 10072:     if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484     albertel 10073:     return int($total);
                   10074: }
                   10075: 
1.575     albertel 10076: sub numval3 {
                   10077:     use integer;
                   10078:     my $txt=shift;
                   10079:     $txt=~tr/A-J/0-9/;
                   10080:     $txt=~tr/a-j/0-9/;
                   10081:     $txt=~tr/K-T/0-9/;
                   10082:     $txt=~tr/k-t/0-9/;
                   10083:     $txt=~tr/U-Z/0-5/;
                   10084:     $txt=~tr/u-z/0-5/;
                   10085:     $txt=~s/\D//g;
                   10086:     my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
                   10087:     my $total;
                   10088:     foreach my $val (@txts) { $total+=$val; }
                   10089:     if ($_64bit) { $total=(($total<<32)>>32); }
                   10090:     return $total;
                   10091: }
                   10092: 
1.675     albertel 10093: sub digest {
                   10094:     my ($data)=@_;
                   10095:     my $digest=&Digest::MD5::md5($data);
                   10096:     my ($a,$b,$c,$d)=unpack("iiii",$digest);
                   10097:     my ($e,$f);
                   10098:     {
                   10099:         use integer;
                   10100:         $e=($a+$b);
                   10101:         $f=($c+$d);
                   10102:         if ($_64bit) {
                   10103:             $e=(($e<<32)>>32);
                   10104:             $f=(($f<<32)>>32);
                   10105:         }
                   10106:     }
                   10107:     if (wantarray) {
                   10108: 	return ($e,$f);
                   10109:     } else {
                   10110: 	my $g;
                   10111: 	{
                   10112: 	    use integer;
                   10113: 	    $g=($e+$f);
                   10114: 	    if ($_64bit) {
                   10115: 		$g=(($g<<32)>>32);
                   10116: 	    }
                   10117: 	}
                   10118: 	return $g;
                   10119:     }
                   10120: }
                   10121: 
1.368     albertel 10122: sub latest_rnd_algorithm_id {
1.675     albertel 10123:     return '64bit5';
1.366     albertel 10124: }
1.32      www      10125: 
1.503     albertel 10126: sub get_rand_alg {
                   10127:     my ($courseid)=@_;
1.790     albertel 10128:     if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503     albertel 10129:     if ($courseid) {
1.620     albertel 10130: 	return $env{"course.$courseid.rndseed"};
1.503     albertel 10131:     }
                   10132:     return &latest_rnd_algorithm_id();
                   10133: }
                   10134: 
1.562     albertel 10135: sub validCODE {
                   10136:     my ($CODE)=@_;
                   10137:     if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
                   10138:     return 0;
                   10139: }
                   10140: 
1.491     albertel 10141: sub getCODE {
1.620     albertel 10142:     if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618     albertel 10143:     if ( (defined($Apache::lonhomework::parsing_a_problem) ||
                   10144: 	  defined($Apache::lonhomework::parsing_a_task) ) &&
                   10145: 	 &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491     albertel 10146: 	return $Apache::lonhomework::history{'resource.CODE'};
                   10147:     }
                   10148:     return undef;
                   10149: }
1.1133    foxr     10150: #
                   10151: #  Determines the random seed for a specific context:
                   10152: #
                   10153: # parameters:
                   10154: #   symb      - in course context the symb for the seed.
                   10155: #   course_id - The course id of the form domain_coursenum.
                   10156: #   domain    - Domain for the user.
                   10157: #   course    - Course for the user.
                   10158: #   cenv      - environment of the course.
                   10159: #
                   10160: # NOTE:
                   10161: #   All parameters are picked out of the environment if missing
                   10162: #   or not defined.
                   10163: #   If a symb cannot be determined the current time is used instead.
                   10164: #
                   10165: #  For a given well defined symb, courside, domain, username,
                   10166: #  and course environment, the seed is reproducible.
                   10167: #
1.31      www      10168: sub rndseed {
1.1133    foxr     10169:     my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790     albertel 10170:     my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896     albertel 10171:     if (!defined($symb)) {
1.366     albertel 10172: 	unless ($symb=$wsymb) { return time; }
                   10173:     }
1.1146    foxr     10174:     if (!defined $courseid) { 
                   10175: 	$courseid=$wcourseid; 
                   10176:     }
                   10177:     if (!defined $domain) { $domain=$wdomain; }
                   10178:     if (!defined $username) { $username=$wusername }
1.1133    foxr     10179: 
                   10180:     my $which;
                   10181:     if (defined($cenv->{'rndseed'})) {
                   10182: 	$which = $cenv->{'rndseed'};
                   10183:     } else {
                   10184: 	$which =&get_rand_alg($courseid);
                   10185:     }
1.491     albertel 10186:     if (defined(&getCODE())) {
1.1133    foxr     10187: 
1.675     albertel 10188: 	if ($which eq '64bit5') {
                   10189: 	    return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
                   10190: 	} elsif ($which eq '64bit4') {
1.575     albertel 10191: 	    return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
                   10192: 	} else {
                   10193: 	    return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
                   10194: 	}
1.675     albertel 10195:     } elsif ($which eq '64bit5') {
                   10196: 	return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575     albertel 10197:     } elsif ($which eq '64bit4') {
                   10198: 	return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501     albertel 10199:     } elsif ($which eq '64bit3') {
                   10200: 	return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443     albertel 10201:     } elsif ($which eq '64bit2') {
                   10202: 	return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366     albertel 10203:     } elsif ($which eq '64bit') {
                   10204: 	return &rndseed_64bit($symb,$courseid,$domain,$username);
                   10205:     }
                   10206:     return &rndseed_32bit($symb,$courseid,$domain,$username);
                   10207: }
                   10208: 
                   10209: sub rndseed_32bit {
                   10210:     my ($symb,$courseid,$domain,$username)=@_;
                   10211:     {
                   10212: 	use integer;
                   10213: 	my $symbchck=unpack("%32C*",$symb) << 27;
                   10214: 	my $symbseed=numval($symb) << 22;
                   10215: 	my $namechck=unpack("%32C*",$username) << 17;
                   10216: 	my $nameseed=numval($username) << 12;
                   10217: 	my $domainseed=unpack("%32C*",$domain) << 7;
                   10218: 	my $courseseed=unpack("%32C*",$courseid);
                   10219: 	my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790     albertel 10220: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10221: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10222: 	if ($_64bit) { $num=(($num<<32)>>32); }
1.366     albertel 10223: 	return $num;
                   10224:     }
                   10225: }
                   10226: 
                   10227: sub rndseed_64bit {
                   10228:     my ($symb,$courseid,$domain,$username)=@_;
                   10229:     {
                   10230: 	use integer;
                   10231: 	my $symbchck=unpack("%32S*",$symb) << 21;
                   10232: 	my $symbseed=numval($symb) << 10;
                   10233: 	my $namechck=unpack("%32S*",$username);
                   10234: 	
                   10235: 	my $nameseed=numval($username) << 21;
                   10236: 	my $domainseed=unpack("%32S*",$domain) << 10;
                   10237: 	my $courseseed=unpack("%32S*",$courseid);
                   10238: 	
                   10239: 	my $num1=$symbchck+$symbseed+$namechck;
                   10240: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10241: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10242: 	#&logthis("rndseed :$num:$symb");
1.564     albertel 10243: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366     albertel 10244: 	return "$num1,$num2";
1.155     albertel 10245:     }
1.366     albertel 10246: }
                   10247: 
1.443     albertel 10248: sub rndseed_64bit2 {
                   10249:     my ($symb,$courseid,$domain,$username)=@_;
                   10250:     {
                   10251: 	use integer;
                   10252: 	# strings need to be an even # of cahracters long, it it is odd the
                   10253:         # last characters gets thrown away
                   10254: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10255: 	my $symbseed=numval($symb) << 10;
                   10256: 	my $namechck=unpack("%32S*",$username.' ');
                   10257: 	
                   10258: 	my $nameseed=numval($username) << 21;
1.501     albertel 10259: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10260: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10261: 	
                   10262: 	my $num1=$symbchck+$symbseed+$namechck;
                   10263: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10264: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10265: 	#&logthis("rndseed :$num:$symb");
1.803     albertel 10266: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501     albertel 10267: 	return "$num1,$num2";
                   10268:     }
                   10269: }
                   10270: 
                   10271: sub rndseed_64bit3 {
                   10272:     my ($symb,$courseid,$domain,$username)=@_;
                   10273:     {
                   10274: 	use integer;
                   10275: 	# strings need to be an even # of cahracters long, it it is odd the
                   10276:         # last characters gets thrown away
                   10277: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10278: 	my $symbseed=numval2($symb) << 10;
                   10279: 	my $namechck=unpack("%32S*",$username.' ');
                   10280: 	
                   10281: 	my $nameseed=numval2($username) << 21;
1.443     albertel 10282: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10283: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10284: 	
                   10285: 	my $num1=$symbchck+$symbseed+$namechck;
                   10286: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10287: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10288: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.564     albertel 10289: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10290: 	
1.503     albertel 10291: 	return "$num1:$num2";
1.443     albertel 10292:     }
                   10293: }
                   10294: 
1.575     albertel 10295: sub rndseed_64bit4 {
                   10296:     my ($symb,$courseid,$domain,$username)=@_;
                   10297:     {
                   10298: 	use integer;
                   10299: 	# strings need to be an even # of cahracters long, it it is odd the
                   10300:         # last characters gets thrown away
                   10301: 	my $symbchck=unpack("%32S*",$symb.' ') << 21;
                   10302: 	my $symbseed=numval3($symb) << 10;
                   10303: 	my $namechck=unpack("%32S*",$username.' ');
                   10304: 	
                   10305: 	my $nameseed=numval3($username) << 21;
                   10306: 	my $domainseed=unpack("%32S*",$domain.' ') << 10;
                   10307: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10308: 	
                   10309: 	my $num1=$symbchck+$symbseed+$namechck;
                   10310: 	my $num2=$nameseed+$domainseed+$courseseed;
1.790     albertel 10311: 	#&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
                   10312: 	#&logthis("rndseed :$num1:$num2:$_64bit");
1.575     albertel 10313: 	if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110    www      10314: 	
1.575     albertel 10315: 	return "$num1:$num2";
                   10316:     }
                   10317: }
                   10318: 
1.675     albertel 10319: sub rndseed_64bit5 {
                   10320:     my ($symb,$courseid,$domain,$username)=@_;
                   10321:     my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
                   10322:     return "$num1:$num2";
                   10323: }
                   10324: 
1.366     albertel 10325: sub rndseed_CODE_64bit {
                   10326:     my ($symb,$courseid,$domain,$username)=@_;
1.155     albertel 10327:     {
1.366     albertel 10328: 	use integer;
1.443     albertel 10329: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484     albertel 10330: 	my $symbseed=numval2($symb);
1.491     albertel 10331: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10332: 	my $CODEseed=numval(&getCODE());
1.443     albertel 10333: 	my $courseseed=unpack("%32S*",$courseid.' ');
1.484     albertel 10334: 	my $num1=$symbseed+$CODEchck;
                   10335: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10336: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10337: 	#&logthis("rndseed :$num1:$num2:$symb");
1.564     albertel 10338: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10339: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503     albertel 10340: 	return "$num1:$num2";
1.366     albertel 10341:     }
                   10342: }
                   10343: 
1.575     albertel 10344: sub rndseed_CODE_64bit4 {
                   10345:     my ($symb,$courseid,$domain,$username)=@_;
                   10346:     {
                   10347: 	use integer;
                   10348: 	my $symbchck=unpack("%32S*",$symb.' ') << 16;
                   10349: 	my $symbseed=numval3($symb);
                   10350: 	my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
                   10351: 	my $CODEseed=numval3(&getCODE());
                   10352: 	my $courseseed=unpack("%32S*",$courseid.' ');
                   10353: 	my $num1=$symbseed+$CODEchck;
                   10354: 	my $num2=$CODEseed+$courseseed+$symbchck;
1.790     albertel 10355: 	#&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
                   10356: 	#&logthis("rndseed :$num1:$num2:$symb");
1.575     albertel 10357: 	if ($_64bit) { $num1=(($num1<<32)>>32); }
                   10358: 	if ($_64bit) { $num2=(($num2<<32)>>32); }
                   10359: 	return "$num1:$num2";
                   10360:     }
                   10361: }
                   10362: 
1.675     albertel 10363: sub rndseed_CODE_64bit5 {
                   10364:     my ($symb,$courseid,$domain,$username)=@_;
                   10365:     my $code = &getCODE();
                   10366:     my ($num1,$num2)=&digest("$symb,$courseid,$code");
                   10367:     return "$num1:$num2";
                   10368: }
                   10369: 
1.366     albertel 10370: sub setup_random_from_rndseed {
                   10371:     my ($rndseed)=@_;
1.503     albertel 10372:     if ($rndseed =~/([,:])/) {
                   10373: 	my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366     albertel 10374: 	&Math::Random::random_set_seed(abs($num1),abs($num2));
                   10375:     } else {
                   10376: 	&Math::Random::random_set_seed_from_phrase($rndseed);
1.98      albertel 10377:     }
1.36      albertel 10378: }
                   10379: 
1.474     albertel 10380: sub latest_receipt_algorithm_id {
1.835     albertel 10381:     return 'receipt3';
1.474     albertel 10382: }
                   10383: 
1.480     www      10384: sub recunique {
                   10385:     my $fucourseid=shift;
                   10386:     my $unique;
1.835     albertel 10387:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
                   10388: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10389: 	$unique=$env{"course.$fucourseid.internal.encseed"};
1.480     www      10390:     } else {
                   10391: 	$unique=$perlvar{'lonReceipt'};
                   10392:     }
                   10393:     return unpack("%32C*",$unique);
                   10394: }
                   10395: 
                   10396: sub recprefix {
                   10397:     my $fucourseid=shift;
                   10398:     my $prefix;
1.835     albertel 10399:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
                   10400: 	$env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620     albertel 10401: 	$prefix=$env{"course.$fucourseid.internal.encpref"};
1.480     www      10402:     } else {
                   10403: 	$prefix=$perlvar{'lonHostID'};
                   10404:     }
                   10405:     return unpack("%32C*",$prefix);
                   10406: }
                   10407: 
1.76      www      10408: sub ireceipt {
1.474     albertel 10409:     my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835     albertel 10410: 
                   10411:     my $return =&recprefix($fucourseid).'-';
                   10412: 
                   10413:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
                   10414: 	$env{'request.state'} eq 'construct') {
                   10415: 	$return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
                   10416: 	return $return;
                   10417:     }
                   10418: 
1.76      www      10419:     my $cuname=unpack("%32C*",$funame);
                   10420:     my $cudom=unpack("%32C*",$fudom);
                   10421:     my $cucourseid=unpack("%32C*",$fucourseid);
                   10422:     my $cusymb=unpack("%32C*",$fusymb);
1.480     www      10423:     my $cunique=&recunique($fucourseid);
1.474     albertel 10424:     my $cpart=unpack("%32S*",$part);
1.835     albertel 10425:     if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
                   10426: 
1.790     albertel 10427: 	#&logthis("doing receipt2  using parts $cpart, uname $cuname and udom $cudom gets  ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474     albertel 10428: 			       
                   10429: 	$return.= ($cunique%$cuname+
                   10430: 		   $cunique%$cudom+
                   10431: 		   $cusymb%$cuname+
                   10432: 		   $cusymb%$cudom+
                   10433: 		   $cucourseid%$cuname+
                   10434: 		   $cucourseid%$cudom+
                   10435: 		   $cpart%$cuname+
                   10436: 		   $cpart%$cudom);
                   10437:     } else {
                   10438: 	$return.= ($cunique%$cuname+
                   10439: 		   $cunique%$cudom+
                   10440: 		   $cusymb%$cuname+
                   10441: 		   $cusymb%$cudom+
                   10442: 		   $cucourseid%$cuname+
                   10443: 		   $cucourseid%$cudom);
                   10444:     }
                   10445:     return $return;
1.76      www      10446: }
                   10447: 
                   10448: sub receipt {
1.474     albertel 10449:     my ($part)=@_;
1.790     albertel 10450:     my ($symb,$courseid,$domain,$name) = &whichuser();
1.474     albertel 10451:     return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76      www      10452: }
1.260     ng       10453: 
1.790     albertel 10454: sub whichuser {
                   10455:     my ($passedsymb)=@_;
                   10456:     my ($symb,$courseid,$domain,$name,$publicuser);
                   10457:     if (defined($env{'form.grade_symb'})) {
                   10458: 	my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
                   10459: 	my $allowed=&allowed('vgr',$tmp_courseid);
                   10460: 	if (!$allowed &&
                   10461: 	    exists($env{'request.course.sec'}) &&
                   10462: 	    $env{'request.course.sec'} !~ /^\s*$/) {
                   10463: 	    $allowed=&allowed('vgr',$tmp_courseid.
                   10464: 			      '/'.$env{'request.course.sec'});
                   10465: 	}
                   10466: 	if ($allowed) {
                   10467: 	    ($symb)=&get_env_multiple('form.grade_symb');
                   10468: 	    $courseid=$tmp_courseid;
                   10469: 	    ($domain)=&get_env_multiple('form.grade_domain');
                   10470: 	    ($name)=&get_env_multiple('form.grade_username');
                   10471: 	    return ($symb,$courseid,$domain,$name,$publicuser);
                   10472: 	}
                   10473:     }
                   10474:     if (!$passedsymb) {
                   10475: 	$symb=&symbread();
                   10476:     } else {
                   10477: 	$symb=$passedsymb;
                   10478:     }
                   10479:     $courseid=$env{'request.course.id'};
                   10480:     $domain=$env{'user.domain'};
                   10481:     $name=$env{'user.name'};
                   10482:     if ($name eq 'public' && $domain eq 'public') {
                   10483: 	if (!defined($env{'form.username'})) {
                   10484: 	    $env{'form.username'}.=time.rand(10000000);
                   10485: 	}
                   10486: 	$name.=$env{'form.username'};
                   10487:     }
                   10488:     return ($symb,$courseid,$domain,$name,$publicuser);
                   10489: 
                   10490: }
                   10491: 
1.36      albertel 10492: # ------------------------------------------------------------ Serves up a file
1.472     albertel 10493: # returns either the contents of the file or 
                   10494: # -1 if the file doesn't exist
1.481     raeburn  10495: #
                   10496: # if the target is a file that was uploaded via DOCS, 
                   10497: # a check will be made to see if a current copy exists on the local server,
                   10498: # if it does this will be served, otherwise a copy will be retrieved from
                   10499: # the home server for the course and stored in /home/httpd/html/userfiles on
                   10500: # the local server.   
1.472     albertel 10501: 
1.36      albertel 10502: sub getfile {
1.538     albertel 10503:     my ($file) = @_;
1.609     banghart 10504:     if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538     albertel 10505:     &repcopy($file);
                   10506:     return &readfile($file);
                   10507: }
                   10508: 
                   10509: sub repcopy_userfile {
                   10510:     my ($file)=@_;
1.1142    raeburn  10511:     my $londocroot = $perlvar{'lonDocRoot'};
                   10512:     if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164    raeburn  10513:     if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538     albertel 10514:     my ($cdom,$cnum,$filename) = 
1.811     albertel 10515: 	($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538     albertel 10516:     my $uri="/uploaded/$cdom/$cnum/$filename";
                   10517:     if (-e "$file") {
1.828     www      10518: # we already have a local copy, check it out
1.538     albertel 10519: 	my @fileinfo = stat($file);
1.828     www      10520: 	my $rtncode;
                   10521: 	my $info;
1.538     albertel 10522: 	my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482     albertel 10523: 	if ($lwpresp ne 'ok') {
1.828     www      10524: # there is no such file anymore, even though we had a local copy
1.482     albertel 10525: 	    if ($rtncode eq '404') {
1.538     albertel 10526: 		unlink($file);
1.482     albertel 10527: 	    }
                   10528: 	    return -1;
                   10529: 	}
                   10530: 	if ($info < $fileinfo[9]) {
1.828     www      10531: # nice, the file we have is up-to-date, just say okay
1.607     raeburn  10532: 	    return 'ok';
1.828     www      10533: 	} else {
                   10534: # the file is outdated, get rid of it
                   10535: 	    unlink($file);
1.482     albertel 10536: 	}
1.828     www      10537:     }
                   10538: # one way or the other, at this point, we don't have the file
                   10539: # construct the correct path for the file
                   10540:     my @parts = ($cdom,$cnum); 
                   10541:     if ($filename =~ m|^(.+)/[^/]+$|) {
                   10542: 	push @parts, split(/\//,$1);
                   10543:     }
                   10544:     my $path = $perlvar{'lonDocRoot'}.'/userfiles';
                   10545:     foreach my $part (@parts) {
                   10546: 	$path .= '/'.$part;
                   10547: 	if (!-e $path) {
                   10548: 	    mkdir($path,0770);
1.482     albertel 10549: 	}
                   10550:     }
1.828     www      10551: # now the path exists for sure
                   10552: # get a user agent
                   10553:     my $ua=new LWP::UserAgent;
                   10554:     my $transferfile=$file.'.in.transfer';
                   10555: # FIXME: this should flock
                   10556:     if (-e $transferfile) { return 'ok'; }
                   10557:     my $request;
                   10558:     $uri=~s/^\///;
1.980     raeburn  10559:     my $homeserver = &homeserver($cnum,$cdom);
                   10560:     my $protocol = $protocol{$homeserver};
                   10561:     $protocol = 'http' if ($protocol ne 'https');
                   10562:     $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828     www      10563:     my $response=$ua->request($request,$transferfile);
                   10564: # did it work?
                   10565:     if ($response->is_error()) {
                   10566: 	unlink($transferfile);
                   10567: 	&logthis("Userfile repcopy failed for $uri");
                   10568: 	return -1;
                   10569:     }
                   10570: # worked, rename the transfer file
                   10571:     rename($transferfile,$file);
1.607     raeburn  10572:     return 'ok';
1.481     raeburn  10573: }
                   10574: 
1.517     albertel 10575: sub tokenwrapper {
                   10576:     my $uri=shift;
1.980     raeburn  10577:     $uri=~s|^https?\://([^/]+)||;
1.552     albertel 10578:     $uri=~s|^/||;
1.620     albertel 10579:     $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517     albertel 10580:     my $token=$1;
1.552     albertel 10581:     my (undef,$udom,$uname,$file)=split('/',$uri,4);
                   10582:     if ($udom && $uname && $file) {
                   10583: 	$file=~s|(\?\.*)*$||;
1.949     raeburn  10584:         &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980     raeburn  10585:         my $homeserver = &homeserver($uname,$udom);
                   10586:         my $protocol = $protocol{$homeserver};
                   10587:         $protocol = 'http' if ($protocol ne 'https');
                   10588:         return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517     albertel 10589:                (($uri=~/\?/)?'&':'?').'token='.$token.
                   10590:                                '&tokenissued='.$perlvar{'lonHostID'};
                   10591:     } else {
                   10592:         return '/adm/notfound.html';
                   10593:     }
                   10594: }
                   10595: 
1.828     www      10596: # call with reqtype HEAD: get last modification time
                   10597: # call with reqtype GET: get the file contents
                   10598: # Do not call this with reqtype GET for large files! It loads everything into memory
                   10599: #
1.481     raeburn  10600: sub getuploaded {
                   10601:     my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
                   10602:     $uri=~s/^\///;
1.980     raeburn  10603:     my $homeserver = &homeserver($cnum,$cdom);
                   10604:     my $protocol = $protocol{$homeserver};
                   10605:     $protocol = 'http' if ($protocol ne 'https');
                   10606:     $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481     raeburn  10607:     my $ua=new LWP::UserAgent;
                   10608:     my $request=new HTTP::Request($reqtype,$uri);
                   10609:     my $response=$ua->request($request);
                   10610:     $$rtncode = $response->code;
1.482     albertel 10611:     if (! $response->is_success()) {
                   10612: 	return 'failed';
                   10613:     }      
                   10614:     if ($reqtype eq 'HEAD') {
1.486     www      10615: 	$$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482     albertel 10616:     } elsif ($reqtype eq 'GET') {
                   10617: 	$$info = $response->content;
1.472     albertel 10618:     }
1.482     albertel 10619:     return 'ok';
1.36      albertel 10620: }
                   10621: 
1.481     raeburn  10622: sub readfile {
                   10623:     my $file = shift;
                   10624:     if ( (! -e $file ) || ($file eq '') ) { return -1; };
                   10625:     my $fh;
                   10626:     open($fh,"<$file");
                   10627:     my $a='';
1.800     albertel 10628:     while (my $line = <$fh>) { $a .= $line; }
1.481     raeburn  10629:     return $a;
                   10630: }
                   10631: 
1.36      albertel 10632: sub filelocation {
1.590     banghart 10633:     my ($dir,$file) = @_;
                   10634:     my $location;
                   10635:     $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700     albertel 10636: 
                   10637:     if ($file =~ m-^/adm/-) {
                   10638: 	$file=~s-^/adm/wrapper/-/-;
                   10639: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
                   10640:     }
1.882     albertel 10641: 
1.1139    www      10642:     if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956     raeburn  10643:         $location = $file;
1.609     banghart 10644:     } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590     banghart 10645:         my ($udom,$uname,$filename)=
1.811     albertel 10646:   	    ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590     banghart 10647:         my $home=&homeserver($uname,$udom);
                   10648:         my $is_me=0;
                   10649:         my @ids=&current_machine_ids();
                   10650:         foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
                   10651:         if ($is_me) {
1.1117    foxr     10652:   	    $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590     banghart 10653:         } else {
                   10654:   	  $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
                   10655:   	      $udom.'/'.$uname.'/'.$filename;
                   10656:         }
1.882     albertel 10657:     } elsif ($file =~ m-^/adm/-) {
                   10658: 	$location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590     banghart 10659:     } else {
                   10660:         $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139    www      10661:         $file=~s:^/(res|priv)/:/:;
                   10662:         my $space=$1;
1.590     banghart 10663:         if ( !( $file =~ m:^/:) ) {
                   10664:             $location = $dir. '/'.$file;
                   10665:         } else {
1.1142    raeburn  10666:             $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590     banghart 10667:         }
1.59      albertel 10668:     }
1.590     banghart 10669:     $location=~s://+:/:g; # remove duplicate /
1.930     albertel 10670:     while ($location=~m{/\.\./}) {
                   10671: 	if ($location =~ m{/[^/]+/\.\./}) {
                   10672: 	    $location=~ s{/[^/]+/\.\./}{/}g;
                   10673: 	} else {
                   10674: 	    $location=~ s{/\.\./}{/}g;
                   10675: 	}
                   10676:     } #remove dir/..
1.590     banghart 10677:     while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
                   10678:     return $location;
1.46      www      10679: }
1.36      albertel 10680: 
1.46      www      10681: sub hreflocation {
                   10682:     my ($dir,$file)=@_;
1.980     raeburn  10683:     unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666     albertel 10684: 	$file=filelocation($dir,$file);
1.700     albertel 10685:     } elsif ($file=~m-^/adm/-) {
                   10686: 	$file=~s-^/adm/wrapper/-/-;
                   10687: 	$file=~s-^/adm/coursedocs/showdoc/-/-;
1.666     albertel 10688:     }
                   10689:     if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
                   10690: 	$file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
                   10691:     } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143    raeburn  10692: 	$file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
                   10693: 	        {/uploaded/$1/$2/}x;
1.46      www      10694:     }
1.913     albertel 10695:     if ($file=~ m{^/userfiles/}) {
                   10696: 	$file =~ s{^/userfiles/}{/uploaded/};
                   10697:     }
1.462     albertel 10698:     return $file;
1.465     albertel 10699: }
                   10700: 
1.1139    www      10701: 
                   10702: 
                   10703: 
                   10704: 
1.465     albertel 10705: sub current_machine_domains {
1.853     albertel 10706:     return &machine_domains(&hostname($perlvar{'lonHostID'}));
                   10707: }
                   10708: 
                   10709: sub machine_domains {
                   10710:     my ($hostname) = @_;
1.465     albertel 10711:     my @domains;
1.838     albertel 10712:     my %hostname = &all_hostnames();
1.465     albertel 10713:     while( my($id, $name) = each(%hostname)) {
1.467     matthew  10714: #	&logthis("-$id-$name-$hostname-");
1.465     albertel 10715: 	if ($hostname eq $name) {
1.844     albertel 10716: 	    push(@domains,&host_domain($id));
1.465     albertel 10717: 	}
                   10718:     }
                   10719:     return @domains;
                   10720: }
                   10721: 
                   10722: sub current_machine_ids {
1.853     albertel 10723:     return &machine_ids(&hostname($perlvar{'lonHostID'}));
                   10724: }
                   10725: 
                   10726: sub machine_ids {
                   10727:     my ($hostname) = @_;
                   10728:     $hostname ||= &hostname($perlvar{'lonHostID'});
1.465     albertel 10729:     my @ids;
1.888     albertel 10730:     my %name_to_host = &all_names();
1.889     albertel 10731:     if (ref($name_to_host{$hostname}) eq 'ARRAY') {
                   10732: 	return @{ $name_to_host{$hostname} };
                   10733:     }
                   10734:     return;
1.31      www      10735: }
                   10736: 
1.824     raeburn  10737: sub additional_machine_domains {
                   10738:     my @domains;
                   10739:     open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
                   10740:     while( my $line = <$fh>) {
                   10741:         $line =~ s/\s//g;
                   10742:         push(@domains,$line);
                   10743:     }
                   10744:     return @domains;
                   10745: }
                   10746: 
                   10747: sub default_login_domain {
                   10748:     my $domain = $perlvar{'lonDefDomain'};
                   10749:     my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
                   10750:     foreach my $posdom (&current_machine_domains(),
                   10751:                         &additional_machine_domains()) {
                   10752:         if (lc($posdom) eq lc($testdomain)) {
                   10753:             $domain=$posdom;
                   10754:             last;
                   10755:         }
                   10756:     }
                   10757:     return $domain;
                   10758: }
                   10759: 
1.31      www      10760: # ------------------------------------------------------------- Declutters URLs
                   10761: 
                   10762: sub declutter {
                   10763:     my $thisfn=shift;
1.569     albertel 10764:     if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479     albertel 10765:     $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31      www      10766:     $thisfn=~s/^\///;
1.697     albertel 10767:     $thisfn=~s|^adm/wrapper/||;
                   10768:     $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31      www      10769:     $thisfn=~s/^res\///;
1.1172    bisitz   10770:     $thisfn=~s/^priv\///;
1.1032    raeburn  10771:     unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
                   10772:         $thisfn=~s/\?.+$//;
                   10773:     }
1.268     www      10774:     return $thisfn;
                   10775: }
                   10776: 
                   10777: # ------------------------------------------------------------- Clutter up URLs
                   10778: 
                   10779: sub clutter {
                   10780:     my $thisfn='/'.&declutter(shift);
1.887     albertel 10781:     if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884     albertel 10782: 	|| $thisfn =~ m{^/adm/(includes|pages)} ) { 
1.270     www      10783:        $thisfn='/res'.$thisfn; 
                   10784:     }
1.1031    raeburn  10785:     if ($thisfn !~m|^/adm|) {
                   10786: 	if ($thisfn =~ m|^/ext/|) {
1.694     albertel 10787: 	    $thisfn='/adm/wrapper'.$thisfn;
1.695     albertel 10788: 	} else {
                   10789: 	    my ($ext) = ($thisfn =~ /\.(\w+)$/);
                   10790: 	    my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698     albertel 10791: 	    if ($embstyle eq 'ssi'
                   10792: 		|| ($embstyle eq 'hdn')
                   10793: 		|| ($embstyle eq 'rat')
                   10794: 		|| ($embstyle eq 'prv')
                   10795: 		|| ($embstyle eq 'ign')) {
                   10796: 		#do nothing with these
                   10797: 	    } elsif (($embstyle eq 'img') 
1.695     albertel 10798: 		|| ($embstyle eq 'emb')
                   10799: 		|| ($embstyle eq 'wrp')) {
                   10800: 		$thisfn='/adm/wrapper'.$thisfn;
1.698     albertel 10801: 	    } elsif ($embstyle eq 'unk'
                   10802: 		     && $thisfn!~/\.(sequence|page)$/) {
1.695     albertel 10803: 		$thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698     albertel 10804: 	    } else {
1.718     www      10805: #		&logthis("Got a blank emb style");
1.695     albertel 10806: 	    }
1.694     albertel 10807: 	}
                   10808:     }
1.31      www      10809:     return $thisfn;
1.12      www      10810: }
                   10811: 
1.787     albertel 10812: sub clutter_with_no_wrapper {
                   10813:     my $uri = &clutter(shift);
                   10814:     if ($uri =~ m-^/adm/-) {
                   10815: 	$uri =~ s-^/adm/wrapper/-/-;
                   10816: 	$uri =~ s-^/adm/coursedocs/showdoc/-/-;
                   10817:     }
                   10818:     return $uri;
                   10819: }
                   10820: 
1.557     albertel 10821: sub freeze_escape {
                   10822:     my ($value)=@_;
                   10823:     if (ref($value)) {
                   10824: 	$value=&nfreeze($value);
                   10825: 	return '__FROZEN__'.&escape($value);
                   10826:     }
                   10827:     return &escape($value);
                   10828: }
                   10829: 
1.11      www      10830: 
1.557     albertel 10831: sub thaw_unescape {
                   10832:     my ($value)=@_;
                   10833:     if ($value =~ /^__FROZEN__/) {
                   10834: 	substr($value,0,10,undef);
                   10835: 	$value=&unescape($value);
                   10836: 	return &thaw($value);
                   10837:     }
                   10838:     return &unescape($value);
                   10839: }
                   10840: 
1.436     albertel 10841: sub correct_line_ends {
                   10842:     my ($result)=@_;
                   10843:     $$result =~s/\r\n/\n/mg;
                   10844:     $$result =~s/\r/\n/mg;
1.415     albertel 10845: }
1.1       albertel 10846: # ================================================================ Main Program
                   10847: 
1.184     www      10848: sub goodbye {
1.204     albertel 10849:    &logthis("Starting Shut down");
1.443     albertel 10850: #not converted to using infrastruture and probably shouldn't be
1.870     albertel 10851:    &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443     albertel 10852: #converted
1.599     albertel 10853: #   &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870     albertel 10854:    &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
                   10855: #   &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
                   10856: #   &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425     albertel 10857: #1.1 only
1.870     albertel 10858: #   &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
                   10859: #   &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
                   10860: #   &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
                   10861: #   &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
                   10862:    &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599     albertel 10863:    &logthis(sprintf("%-20s is %s",'kicks',$kicks));
                   10864:    &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184     www      10865:    &flushcourselogs();
                   10866:    &logthis("Shutting down");
                   10867: }
                   10868: 
1.852     albertel 10869: sub get_dns {
1.869     albertel 10870:     my ($url,$func,$ignore_cache) = @_;
                   10871:     if (!$ignore_cache) {
                   10872: 	my ($content,$cached)=
                   10873: 	    &Apache::lonnet::is_cached_new('dns',$url);
                   10874: 	if ($cached) {
                   10875: 	    &$func($content);
                   10876: 	    return;
                   10877: 	}
                   10878:     }
                   10879: 
                   10880:     my %alldns;
1.852     albertel 10881:     open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   10882:     foreach my $dns (<$config>) {
                   10883: 	next if ($dns !~ /^\^(\S*)/x);
1.979     raeburn  10884:         my $line = $1;
                   10885:         my ($host,$protocol) = split(/:/,$line);
                   10886:         if ($protocol ne 'https') {
                   10887:             $protocol = 'http';
                   10888:         }
                   10889: 	$alldns{$host} = $protocol;
1.869     albertel 10890:     }
                   10891:     while (%alldns) {
                   10892: 	my ($dns) = keys(%alldns);
1.852     albertel 10893: 	my $ua=new LWP::UserAgent;
1.1134    raeburn  10894:         $ua->timeout(30);
1.979     raeburn  10895: 	my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852     albertel 10896: 	my $response=$ua->request($request);
1.979     raeburn  10897:         delete($alldns{$dns});
1.852     albertel 10898: 	next if ($response->is_error());
                   10899: 	my @content = split("\n",$response->content);
1.869     albertel 10900: 	&Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852     albertel 10901: 	&$func(\@content);
1.869     albertel 10902: 	return;
1.852     albertel 10903:     }
                   10904:     close($config);
1.871     albertel 10905:     my $which = (split('/',$url))[3];
                   10906:     &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
                   10907:     open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869     albertel 10908:     my @content = <$config>;
                   10909:     &$func(\@content);
                   10910:     return;
1.852     albertel 10911: }
1.327     albertel 10912: # ------------------------------------------------------------ Read domain file
                   10913: {
1.852     albertel 10914:     my $loaded;
1.846     albertel 10915:     my %domain;
                   10916: 
1.852     albertel 10917:     sub parse_domain_tab {
                   10918: 	my ($lines) = @_;
                   10919: 	foreach my $line (@$lines) {
                   10920: 	    next if ($line =~ /^(\#|\s*$ )/x);
1.403     www      10921: 
1.846     albertel 10922: 	    chomp($line);
1.852     albertel 10923: 	    my ($name,@elements) = split(/:/,$line,9);
1.846     albertel 10924: 	    my %this_domain;
                   10925: 	    foreach my $field ('description', 'auth_def', 'auth_arg_def',
                   10926: 			       'lang_def', 'city', 'longi', 'lati',
                   10927: 			       'primary') {
                   10928: 		$this_domain{$field} = shift(@elements);
                   10929: 	    }
                   10930: 	    $domain{$name} = \%this_domain;
1.852     albertel 10931: 	}
                   10932:     }
1.864     albertel 10933: 
                   10934:     sub reset_domain_info {
                   10935: 	undef($loaded);
                   10936: 	undef(%domain);
                   10937:     }
                   10938: 
1.852     albertel 10939:     sub load_domain_tab {
1.869     albertel 10940: 	my ($ignore_cache) = @_;
                   10941: 	&get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852     albertel 10942: 	my $fh;
                   10943: 	if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
                   10944: 	    my @lines = <$fh>;
                   10945: 	    &parse_domain_tab(\@lines);
1.448     albertel 10946: 	}
1.852     albertel 10947: 	close($fh);
                   10948: 	$loaded = 1;
1.327     albertel 10949:     }
1.846     albertel 10950: 
                   10951:     sub domain {
1.852     albertel 10952: 	&load_domain_tab() if (!$loaded);
                   10953: 
1.846     albertel 10954: 	my ($name,$what) = @_;
                   10955: 	return if ( !exists($domain{$name}) );
                   10956: 
                   10957: 	if (!$what) {
                   10958: 	    return $domain{$name}{'description'};
                   10959: 	}
                   10960: 	return $domain{$name}{$what};
                   10961:     }
1.974     raeburn  10962: 
                   10963:     sub domain_info {
                   10964:         &load_domain_tab() if (!$loaded);
                   10965:         return %domain;
                   10966:     }
                   10967: 
1.327     albertel 10968: }
                   10969: 
                   10970: 
1.1       albertel 10971: # ------------------------------------------------------------- Read hosts file
                   10972: {
1.838     albertel 10973:     my %hostname;
1.844     albertel 10974:     my %hostdom;
1.845     albertel 10975:     my %libserv;
1.852     albertel 10976:     my $loaded;
1.888     albertel 10977:     my %name_to_host;
1.1074    raeburn  10978:     my %internetdom;
1.1107    raeburn  10979:     my %LC_dns_serv;
1.852     albertel 10980: 
                   10981:     sub parse_hosts_tab {
                   10982: 	my ($file) = @_;
                   10983: 	foreach my $configline (@$file) {
                   10984: 	    next if ($configline =~ /^(\#|\s*$ )/x);
1.1107    raeburn  10985:             chomp($configline);
                   10986: 	    if ($configline =~ /^\^/) {
                   10987:                 if ($configline =~ /^\^([\w.\-]+)/) {
                   10988:                     $LC_dns_serv{$1} = 1;
                   10989:                 }
                   10990:                 next;
                   10991:             }
1.1074    raeburn  10992: 	    my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852     albertel 10993: 	    $name=~s/\s//g;
                   10994: 	    if ($id && $domain && $role && $name) {
                   10995: 		$hostname{$id}=$name;
1.888     albertel 10996: 		push(@{$name_to_host{$name}}, $id);
1.852     albertel 10997: 		$hostdom{$id}=$domain;
                   10998: 		if ($role eq 'library') { $libserv{$id}=$name; }
1.969     raeburn  10999:                 if (defined($protocol)) {
                   11000:                     if ($protocol eq 'https') {
                   11001:                         $protocol{$id} = $protocol;
                   11002:                     } else {
                   11003:                         $protocol{$id} = 'http'; 
                   11004:                     }
1.968     raeburn  11005:                 } else {
1.969     raeburn  11006:                     $protocol{$id} = 'http';
1.968     raeburn  11007:                 }
1.1074    raeburn  11008:                 if (defined($intdom)) {
                   11009:                     $internetdom{$id} = $intdom;
                   11010:                 }
1.852     albertel 11011: 	    }
                   11012: 	}
                   11013:     }
1.864     albertel 11014:     
                   11015:     sub reset_hosts_info {
1.897     albertel 11016: 	&purge_remembered();
1.864     albertel 11017: 	&reset_domain_info();
                   11018: 	&reset_hosts_ip_info();
1.892     albertel 11019: 	undef(%name_to_host);
1.864     albertel 11020: 	undef(%hostname);
                   11021: 	undef(%hostdom);
                   11022: 	undef(%libserv);
                   11023: 	undef($loaded);
                   11024:     }
1.1       albertel 11025: 
1.852     albertel 11026:     sub load_hosts_tab {
1.869     albertel 11027: 	my ($ignore_cache) = @_;
                   11028: 	&get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852     albertel 11029: 	open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
                   11030: 	my @config = <$config>;
                   11031: 	&parse_hosts_tab(\@config);
                   11032: 	close($config);
                   11033: 	$loaded=1;
1.1       albertel 11034:     }
1.852     albertel 11035: 
1.838     albertel 11036:     sub hostname {
1.852     albertel 11037: 	&load_hosts_tab() if (!$loaded);
                   11038: 
1.838     albertel 11039: 	my ($lonid) = @_;
                   11040: 	return $hostname{$lonid};
                   11041:     }
1.845     albertel 11042: 
1.838     albertel 11043:     sub all_hostnames {
1.852     albertel 11044: 	&load_hosts_tab() if (!$loaded);
                   11045: 
1.838     albertel 11046: 	return %hostname;
                   11047:     }
1.845     albertel 11048: 
1.888     albertel 11049:     sub all_names {
                   11050: 	&load_hosts_tab() if (!$loaded);
                   11051: 
                   11052: 	return %name_to_host;
                   11053:     }
                   11054: 
1.974     raeburn  11055:     sub all_host_domain {
                   11056:         &load_hosts_tab() if (!$loaded);
                   11057:         return %hostdom;
                   11058:     }
                   11059: 
1.845     albertel 11060:     sub is_library {
1.852     albertel 11061: 	&load_hosts_tab() if (!$loaded);
                   11062: 
1.845     albertel 11063: 	return exists($libserv{$_[0]});
                   11064:     }
                   11065: 
                   11066:     sub all_library {
1.852     albertel 11067: 	&load_hosts_tab() if (!$loaded);
                   11068: 
1.845     albertel 11069: 	return %libserv;
                   11070:     }
                   11071: 
1.1062    droeschl 11072:     sub unique_library {
                   11073: 	#2x reverse removes all hostnames that appear more than once
                   11074:         my %unique = reverse &all_library();
                   11075:         return reverse %unique;
                   11076:     }
                   11077: 
1.841     albertel 11078:     sub get_servers {
1.852     albertel 11079: 	&load_hosts_tab() if (!$loaded);
                   11080: 
1.841     albertel 11081: 	my ($domain,$type) = @_;
                   11082: 	my %possible_hosts = ($type eq 'library') ? %libserv
                   11083: 	                                          : %hostname;
                   11084: 	my %result;
1.842     albertel 11085: 	if (ref($domain) eq 'ARRAY') {
                   11086: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843     albertel 11087: 		if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842     albertel 11088: 		    $result{$host} = $hostname;
                   11089: 		}
                   11090: 	    }
                   11091: 	} else {
                   11092: 	    while ( my ($host,$hostname) = each(%possible_hosts)) {
                   11093: 		if ($hostdom{$host} eq $domain) {
                   11094: 		    $result{$host} = $hostname;
                   11095: 		}
1.841     albertel 11096: 	    }
                   11097: 	}
                   11098: 	return %result;
                   11099:     }
1.845     albertel 11100: 
1.1062    droeschl 11101:     sub get_unique_servers {
                   11102:         my %unique = reverse &get_servers(@_);
                   11103: 	return reverse %unique;
                   11104:     }
                   11105: 
1.844     albertel 11106:     sub host_domain {
1.852     albertel 11107: 	&load_hosts_tab() if (!$loaded);
                   11108: 
1.844     albertel 11109: 	my ($lonid) = @_;
                   11110: 	return $hostdom{$lonid};
                   11111:     }
                   11112: 
1.841     albertel 11113:     sub all_domains {
1.852     albertel 11114: 	&load_hosts_tab() if (!$loaded);
                   11115: 
1.841     albertel 11116: 	my %seen;
                   11117: 	my @uniq = grep(!$seen{$_}++, values(%hostdom));
                   11118: 	return @uniq;
                   11119:     }
1.1074    raeburn  11120: 
                   11121:     sub internet_dom {
                   11122:         &load_hosts_tab() if (!$loaded);
                   11123: 
                   11124:         my ($lonid) = @_;
                   11125:         return $internetdom{$lonid};
                   11126:     }
1.1107    raeburn  11127: 
                   11128:     sub is_LC_dns {
                   11129:         &load_hosts_tab() if (!$loaded);
                   11130: 
                   11131:         my ($hostname) = @_;
                   11132:         return exists($LC_dns_serv{$hostname});
                   11133:     }
                   11134: 
1.1       albertel 11135: }
                   11136: 
1.847     albertel 11137: { 
                   11138:     my %iphost;
1.856     albertel 11139:     my %name_to_ip;
                   11140:     my %lonid_to_ip;
1.869     albertel 11141: 
1.847     albertel 11142:     sub get_hosts_from_ip {
                   11143: 	my ($ip) = @_;
                   11144: 	my %iphosts = &get_iphost();
                   11145: 	if (ref($iphosts{$ip})) {
                   11146: 	    return @{$iphosts{$ip}};
                   11147: 	}
                   11148: 	return;
1.839     albertel 11149:     }
1.864     albertel 11150:     
                   11151:     sub reset_hosts_ip_info {
                   11152: 	undef(%iphost);
                   11153: 	undef(%name_to_ip);
                   11154: 	undef(%lonid_to_ip);
                   11155:     }
1.856     albertel 11156: 
                   11157:     sub get_host_ip {
                   11158: 	my ($lonid) = @_;
                   11159: 	if (exists($lonid_to_ip{$lonid})) {
                   11160: 	    return $lonid_to_ip{$lonid};
                   11161: 	}
                   11162: 	my $name=&hostname($lonid);
                   11163:    	my $ip = gethostbyname($name);
                   11164: 	return if (!$ip || length($ip) ne 4);
                   11165: 	$ip=inet_ntoa($ip);
                   11166: 	$name_to_ip{$name}   = $ip;
                   11167: 	$lonid_to_ip{$lonid} = $ip;
                   11168: 	return $ip;
                   11169:     }
1.847     albertel 11170:     
                   11171:     sub get_iphost {
1.869     albertel 11172: 	my ($ignore_cache) = @_;
1.894     albertel 11173: 
1.869     albertel 11174: 	if (!$ignore_cache) {
                   11175: 	    if (%iphost) {
                   11176: 		return %iphost;
                   11177: 	    }
                   11178: 	    my ($ip_info,$cached)=
                   11179: 		&Apache::lonnet::is_cached_new('iphost','iphost');
                   11180: 	    if ($cached) {
                   11181: 		%iphost      = %{$ip_info->[0]};
                   11182: 		%name_to_ip  = %{$ip_info->[1]};
                   11183: 		%lonid_to_ip = %{$ip_info->[2]};
                   11184: 		return %iphost;
                   11185: 	    }
                   11186: 	}
1.894     albertel 11187: 
                   11188: 	# get yesterday's info for fallback
                   11189: 	my %old_name_to_ip;
                   11190: 	my ($ip_info,$cached)=
                   11191: 	    &Apache::lonnet::is_cached_new('iphost','iphost');
                   11192: 	if ($cached) {
                   11193: 	    %old_name_to_ip = %{$ip_info->[1]};
                   11194: 	}
                   11195: 
1.888     albertel 11196: 	my %name_to_host = &all_names();
                   11197: 	foreach my $name (keys(%name_to_host)) {
1.847     albertel 11198: 	    my $ip;
                   11199: 	    if (!exists($name_to_ip{$name})) {
                   11200: 		$ip = gethostbyname($name);
                   11201: 		if (!$ip || length($ip) ne 4) {
1.894     albertel 11202: 		    if (defined($old_name_to_ip{$name})) {
                   11203: 			$ip = $old_name_to_ip{$name};
                   11204: 			&logthis("Can't find $name defaulting to old $ip");
                   11205: 		    } else {
                   11206: 			&logthis("Name $name no IP found");
                   11207: 			next;
                   11208: 		    }
                   11209: 		} else {
                   11210: 		    $ip=inet_ntoa($ip);
1.847     albertel 11211: 		}
                   11212: 		$name_to_ip{$name} = $ip;
                   11213: 	    } else {
                   11214: 		$ip = $name_to_ip{$name};
1.653     albertel 11215: 	    }
1.888     albertel 11216: 	    foreach my $id (@{ $name_to_host{$name} }) {
                   11217: 		$lonid_to_ip{$id} = $ip;
                   11218: 	    }
                   11219: 	    push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598     albertel 11220: 	}
1.869     albertel 11221: 	&Apache::lonnet::do_cache_new('iphost','iphost',
                   11222: 				      [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894     albertel 11223: 				      48*60*60);
1.869     albertel 11224: 
1.847     albertel 11225: 	return %iphost;
1.598     albertel 11226:     }
                   11227: 
1.992     raeburn  11228:     #
                   11229:     #  Given a DNS returns the loncapa host name for that DNS 
                   11230:     # 
                   11231:     sub host_from_dns {
                   11232:         my ($dns) = @_;
                   11233:         my @hosts;
                   11234:         my $ip;
                   11235: 
1.993     raeburn  11236:         if (exists($name_to_ip{$dns})) {
1.992     raeburn  11237:             $ip = $name_to_ip{$dns};
                   11238:         }
                   11239:         if (!$ip) {
                   11240:             $ip = gethostbyname($dns); # Initial translation to IP is in net order.
                   11241:             if (length($ip) == 4) { 
                   11242: 	        $ip   = &IO::Socket::inet_ntoa($ip);
                   11243:             }
                   11244:         }
                   11245:         if ($ip) {
                   11246: 	    @hosts = get_hosts_from_ip($ip);
                   11247: 	    return $hosts[0];
                   11248:         }
                   11249:         return undef;
1.986     foxr     11250:     }
1.992     raeburn  11251: 
1.1074    raeburn  11252:     sub get_internet_names {
                   11253:         my ($lonid) = @_;
                   11254:         return if ($lonid eq '');
                   11255:         my ($idnref,$cached)=
                   11256:             &Apache::lonnet::is_cached_new('internetnames',$lonid);
                   11257:         if ($cached) {
                   11258:             return $idnref;
                   11259:         }
                   11260:         my $ip = &get_host_ip($lonid);
                   11261:         my @hosts = &get_hosts_from_ip($ip);
                   11262:         my %iphost = &get_iphost();
                   11263:         my (@idns,%seen);
                   11264:         foreach my $id (@hosts) {
                   11265:             my $dom = &host_domain($id);
                   11266:             my $prim_id = &domain($dom,'primary');
                   11267:             my $prim_ip = &get_host_ip($prim_id);
                   11268:             next if ($seen{$prim_ip});
                   11269:             if (ref($iphost{$prim_ip}) eq 'ARRAY') {
                   11270:                 foreach my $id (@{$iphost{$prim_ip}}) {
                   11271:                     my $intdom = &internet_dom($id);
                   11272:                     unless (grep(/^\Q$intdom\E$/,@idns)) {
                   11273:                         push(@idns,$intdom);
                   11274:                     }
                   11275:                 }
                   11276:             }
                   11277:             $seen{$prim_ip} = 1;
                   11278:         }
                   11279:         return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
                   11280:     }
                   11281: 
1.986     foxr     11282: }
                   11283: 
1.1079    raeburn  11284: sub all_loncaparevs {
                   11285:     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);
                   11286: }
                   11287: 
1.862     albertel 11288: BEGIN {
                   11289: 
                   11290: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
                   11291:     unless ($readit) {
                   11292: {
                   11293:     my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
                   11294:     %perlvar = (%perlvar,%{$configvars});
                   11295: }
                   11296: 
                   11297: 
1.1       albertel 11298: # ------------------------------------------------------ Read spare server file
                   11299: {
1.448     albertel 11300:     open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1       albertel 11301: 
                   11302:     while (my $configline=<$config>) {
                   11303:        chomp($configline);
1.284     matthew  11304:        if ($configline) {
1.784     albertel 11305: 	   my ($host,$type) = split(':',$configline,2);
1.785     albertel 11306: 	   if (!defined($type) || $type eq '') { $type = 'default' };
1.784     albertel 11307: 	   push(@{ $spareid{$type} }, $host);
1.1       albertel 11308:        }
                   11309:     }
1.448     albertel 11310:     close($config);
1.1       albertel 11311: }
1.11      www      11312: # ------------------------------------------------------------ Read permissions
                   11313: {
1.448     albertel 11314:     open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11      www      11315: 
                   11316:     while (my $configline=<$config>) {
1.448     albertel 11317: 	chomp($configline);
                   11318: 	if ($configline) {
                   11319: 	    my ($role,$perm)=split(/ /,$configline);
                   11320: 	    if ($perm ne '') { $pr{$role}=$perm; }
                   11321: 	}
1.11      www      11322:     }
1.448     albertel 11323:     close($config);
1.11      www      11324: }
                   11325: 
                   11326: # -------------------------------------------- Read plain texts for permissions
                   11327: {
1.448     albertel 11328:     open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11      www      11329: 
                   11330:     while (my $configline=<$config>) {
1.448     albertel 11331: 	chomp($configline);
                   11332: 	if ($configline) {
1.742     raeburn  11333: 	    my ($short,@plain)=split(/:/,$configline);
                   11334:             %{$prp{$short}} = ();
                   11335: 	    if (@plain > 0) {
                   11336:                 $prp{$short}{'std'} = $plain[0];
                   11337:                 for (my $i=1; $i<@plain; $i++) {
                   11338:                     $prp{$short}{'alt'.$i} = $plain[$i];  
                   11339:                 }
                   11340:             }
1.448     albertel 11341: 	}
1.135     www      11342:     }
1.448     albertel 11343:     close($config);
1.135     www      11344: }
                   11345: 
                   11346: # ---------------------------------------------------------- Read package table
                   11347: {
1.448     albertel 11348:     open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135     www      11349: 
                   11350:     while (my $configline=<$config>) {
1.483     albertel 11351: 	if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448     albertel 11352: 	chomp($configline);
                   11353: 	my ($short,$plain)=split(/:/,$configline);
                   11354: 	my ($pack,$name)=split(/\&/,$short);
                   11355: 	if ($plain ne '') {
                   11356: 	    $packagetab{$pack.'&'.$name.'&name'}=$name; 
                   11357: 	    $packagetab{$short}=$plain; 
                   11358: 	}
1.11      www      11359:     }
1.448     albertel 11360:     close($config);
1.329     matthew  11361: }
                   11362: 
1.1073    raeburn  11363: # ---------------------------------------------------------- Read loncaparev table
                   11364: {
                   11365:     if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
                   11366:         if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
                   11367:             while (my $configline=<$config>) {
                   11368:                 chomp($configline);
                   11369:                 my ($hostid,$loncaparev)=split(/:/,$configline);
                   11370:                 $loncaparevs{$hostid}=$loncaparev;
                   11371:             }
                   11372:             close($config);
                   11373:         }
                   11374:     }
                   11375: }
                   11376: 
1.1074    raeburn  11377: # ---------------------------------------------------------- Read serverhostID table
                   11378: {
                   11379:     if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
                   11380:         if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
                   11381:             while (my $configline=<$config>) {
                   11382:                 chomp($configline);
                   11383:                 my ($name,$id)=split(/:/,$configline);
                   11384:                 $serverhomeIDs{$name}=$id;
                   11385:             }
                   11386:             close($config);
                   11387:         }
                   11388:     }
                   11389: }
                   11390: 
1.1079    raeburn  11391: {
                   11392:     my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
                   11393:     if (-e $file) {
                   11394:         my $parser = HTML::LCParser->new($file);
                   11395:         while (my $token = $parser->get_token()) {
                   11396:             if ($token->[0] eq 'S') {
                   11397:                 my $item = $token->[1];
                   11398:                 my $name = $token->[2]{'name'};
                   11399:                 my $value = $token->[2]{'value'};
                   11400:                 if ($item ne '' && $name ne '' && $value ne '') {
                   11401:                     my $release = $parser->get_text();
                   11402:                     $release =~ s/(^\s*|\s*$ )//gx;
                   11403:                     $needsrelease{$item.':'.$name.':'.$value} = $release;
                   11404:                 }
                   11405:             }
                   11406:         }
                   11407:     }
1.1073    raeburn  11408: }
                   11409: 
1.1138    raeburn  11410: # ---------------------------------------------------------- Read managers table
                   11411: {
                   11412:     if (-e "$perlvar{'lonTabDir'}/managers.tab") {
                   11413:         if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
                   11414:             while (my $configline=<$config>) {
                   11415:                 chomp($configline);
                   11416:                 next if ($configline =~ /^\#/);
                   11417:                 if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
                   11418:                     $managerstab{$configline} = 1;
                   11419:                 }
                   11420:             }
                   11421:             close($config);
                   11422:         }
                   11423:     }
                   11424: }
                   11425: 
1.329     matthew  11426: # ------------- set up temporary directory
                   11427: {
1.1117    foxr     11428:     $tmpdir = LONCAPA::tempdir();
1.329     matthew  11429: 
1.11      www      11430: }
                   11431: 
1.794     albertel 11432: $memcache=new Cache::Memcached({'servers'           => ['127.0.0.1:11211'],
                   11433: 				'compress_threshold'=> 20_000,
                   11434:  			        });
1.185     www      11435: 
1.281     www      11436: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186     www      11437: $dumpcount=0;
1.958     www      11438: $locknum=0;
1.22      www      11439: 
1.163     harris41 11440: &logtouch();
1.672     albertel 11441: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195     www      11442: $readit=1;
1.564     albertel 11443:     {
                   11444: 	use integer;
                   11445: 	my $test=(2**32)+1;
1.568     albertel 11446: 	if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564     albertel 11447: 	&logthis(" Detected 64bit platform ($_64bit)");
                   11448:     }
1.195     www      11449: }
1.1       albertel 11450: }
1.179     www      11451: 
1.1       albertel 11452: 1;
1.191     harris41 11453: __END__
                   11454: 
1.243     albertel 11455: =pod
                   11456: 
1.191     harris41 11457: =head1 NAME
                   11458: 
1.243     albertel 11459: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191     harris41 11460: 
                   11461: =head1 SYNOPSIS
                   11462: 
1.243     albertel 11463: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191     harris41 11464: 
                   11465:  &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
                   11466: 
1.243     albertel 11467: Common parameters:
                   11468: 
                   11469: =over 4
                   11470: 
                   11471: =item *
                   11472: 
                   11473: $uname : an internal username (if $cname expecting a course Id specifically)
                   11474: 
                   11475: =item *
                   11476: 
                   11477: $udom : a domain (if $cdom expecting a course's domain specifically)
                   11478: 
                   11479: =item *
                   11480: 
                   11481: $symb : a resource instance identifier
                   11482: 
                   11483: =item *
                   11484: 
                   11485: $namespace : the name of a .db file that contains the data needed or
                   11486: being set.
                   11487: 
                   11488: =back
                   11489: 
1.394     bowersj2 11490: =head1 OVERVIEW
1.191     harris41 11491: 
1.394     bowersj2 11492: lonnet provides subroutines which interact with the
                   11493: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
                   11494: about classes, users, and resources.
1.243     albertel 11495: 
                   11496: For many of these objects you can also use this to store data about
                   11497: them or modify them in various ways.
1.191     harris41 11498: 
1.394     bowersj2 11499: =head2 Symbs
1.191     harris41 11500: 
1.394     bowersj2 11501: To identify a specific instance of a resource, LON-CAPA uses symbols
                   11502: or "symbs"X<symb>. These identifiers are built from the URL of the
                   11503: map, the resource number of the resource in the map, and the URL of
                   11504: the resource itself. The latter is somewhat redundant, but might help
                   11505: if maps change.
                   11506: 
                   11507: An example is
                   11508: 
                   11509:  msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
                   11510: 
                   11511: The respective map entry is
                   11512: 
                   11513:  <resource id="19" src="/res/msu/korte/tests/part12.problem"
                   11514:   title="Problem 2">
                   11515:  </resource>
                   11516: 
                   11517: Symbs are used by the random number generator, as well as to store and
                   11518: restore data specific to a certain instance of for example a problem.
                   11519: 
                   11520: =head2 Storing And Retrieving Data
                   11521: 
                   11522: X<store()>X<cstore()>X<restore()>Three of the most important functions
                   11523: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
                   11524: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
                   11525: is is the non-critical message twin of cstore. These functions are for
                   11526: handlers to store a perl hash to a user's permanent data space in an
                   11527: easy manner, and to retrieve it again on another call. It is expected
                   11528: that a handler would use this once at the beginning to retrieve data,
                   11529: and then again once at the end to send only the new data back.
                   11530: 
                   11531: The data is stored in the user's data directory on the user's
                   11532: homeserver under the ID of the course.
                   11533: 
                   11534: The hash that is returned by restore will have all of the previous
                   11535: value for all of the elements of the hash.
                   11536: 
                   11537: Example:
                   11538: 
                   11539:  #creating a hash
                   11540:  my %hash;
                   11541:  $hash{'foo'}='bar';
                   11542: 
                   11543:  #storing it
                   11544:  &Apache::lonnet::cstore(\%hash);
                   11545: 
                   11546:  #changing a value
                   11547:  $hash{'foo'}='notbar';
                   11548: 
                   11549:  #adding a new value
                   11550:  $hash{'bar'}='foo';
                   11551:  &Apache::lonnet::cstore(\%hash);
                   11552: 
                   11553:  #retrieving the hash
                   11554:  my %history=&Apache::lonnet::restore();
                   11555: 
                   11556:  #print the hash
                   11557:  foreach my $key (sort(keys(%history))) {
                   11558:    print("\%history{$key} = $history{$key}");
                   11559:  }
                   11560: 
                   11561: Will print out:
1.191     harris41 11562: 
1.394     bowersj2 11563:  %history{1:foo} = bar
                   11564:  %history{1:keys} = foo:timestamp
                   11565:  %history{1:timestamp} = 990455579
                   11566:  %history{2:bar} = foo
                   11567:  %history{2:foo} = notbar
                   11568:  %history{2:keys} = foo:bar:timestamp
                   11569:  %history{2:timestamp} = 990455580
                   11570:  %history{bar} = foo
                   11571:  %history{foo} = notbar
                   11572:  %history{timestamp} = 990455580
                   11573:  %history{version} = 2
                   11574: 
                   11575: Note that the special hash entries C<keys>, C<version> and
                   11576: C<timestamp> were added to the hash. C<version> will be equal to the
                   11577: total number of versions of the data that have been stored. The
                   11578: C<timestamp> attribute will be the UNIX time the hash was
                   11579: stored. C<keys> is available in every historical section to list which
                   11580: keys were added or changed at a specific historical revision of a
                   11581: hash.
                   11582: 
                   11583: B<Warning>: do not store the hash that restore returns directly. This
                   11584: will cause a mess since it will restore the historical keys as if the
                   11585: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191     harris41 11586: 
1.394     bowersj2 11587: Calling convention:
1.191     harris41 11588: 
1.394     bowersj2 11589:  my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
                   11590:  &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191     harris41 11591: 
1.394     bowersj2 11592: For more detailed information, see lonnet specific documentation.
1.191     harris41 11593: 
1.394     bowersj2 11594: =head1 RETURN MESSAGES
1.191     harris41 11595: 
1.394     bowersj2 11596: =over 4
1.191     harris41 11597: 
1.394     bowersj2 11598: =item * B<con_lost>: unable to contact remote host
1.191     harris41 11599: 
1.394     bowersj2 11600: =item * B<con_delayed>: unable to contact remote host, message will be delivered
                   11601: when the connection is brought back up
1.191     harris41 11602: 
1.394     bowersj2 11603: =item * B<con_failed>: unable to contact remote host and unable to save message
                   11604: for later delivery
1.191     harris41 11605: 
1.967     bisitz   11606: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191     harris41 11607: 
1.394     bowersj2 11608: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243     albertel 11609: that was requested
1.191     harris41 11610: 
1.243     albertel 11611: =back
1.191     harris41 11612: 
1.243     albertel 11613: =head1 PUBLIC SUBROUTINES
1.191     harris41 11614: 
1.243     albertel 11615: =head2 Session Environment Functions
1.191     harris41 11616: 
1.243     albertel 11617: =over 4
1.191     harris41 11618: 
1.394     bowersj2 11619: =item * 
                   11620: X<appenv()>
1.949     raeburn  11621: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394     bowersj2 11622: the user envirnoment file, and will be restored for each access this
1.620     albertel 11623: user makes during this session, also modifies the %env for the current
1.949     raeburn  11624: process. Optional rolesarrayref - if defined contains a reference to an array
                   11625: of roles which are exempt from the restriction on modifying user.role entries 
                   11626: in the user's environment.db and in %env.    
1.191     harris41 11627: 
                   11628: =item *
1.394     bowersj2 11629: X<delenv()>
1.987     raeburn  11630: B<delenv($delthis,$regexp)>: removes all items from the session
                   11631: environment file that begin with $delthis. If the 
                   11632: optional second arg - $regexp - is true, $delthis is treated as a 
                   11633: regular expression, otherwise \Q$delthis\E is used. 
                   11634: The values are also deleted from the current processes %env.
1.191     harris41 11635: 
1.795     albertel 11636: =item * get_env_multiple($name) 
                   11637: 
                   11638: gets $name from the %env hash, it seemlessly handles the cases where multiple
                   11639: values may be defined and end up as an array ref.
                   11640: 
                   11641: returns an array of values
                   11642: 
1.243     albertel 11643: =back
                   11644: 
                   11645: =head2 User Information
1.191     harris41 11646: 
1.243     albertel 11647: =over 4
1.191     harris41 11648: 
                   11649: =item *
1.394     bowersj2 11650: X<queryauthenticate()>
                   11651: B<queryauthenticate($uname,$udom)>: try to determine user's current 
1.191     harris41 11652: authentication scheme
                   11653: 
                   11654: =item *
1.394     bowersj2 11655: X<authenticate()>
1.1073    raeburn  11656: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394     bowersj2 11657: authenticate user from domain's lib servers (first use the current
                   11658: one). C<$upass> should be the users password.
1.1073    raeburn  11659: $checkdefauth is optional (value is 1 if a check should be made to
                   11660:    authenticate user using default authentication method, and allow
                   11661:    account creation if username does not have account in the domain).
                   11662: $clientcancheckhost is optional (value is 1 if checking whether the
                   11663:    server can host will occur on the client side in lonauth.pm).   
1.191     harris41 11664: 
                   11665: =item *
1.394     bowersj2 11666: X<homeserver()>
                   11667: B<homeserver($uname,$udom)>: find the server which has
                   11668: the user's directory and files (there must be only one), this caches
                   11669: the answer, and also caches if there is a borken connection.
1.191     harris41 11670: 
                   11671: =item *
1.394     bowersj2 11672: X<idget()>
                   11673: B<idget($udom,@ids)>: find the usernames behind a list of IDs
                   11674: (IDs are a unique resource in a domain, there must be only 1 ID per
                   11675: username, and only 1 username per ID in a specific domain) (returns
                   11676: hash: id=>name,id=>name)
1.191     harris41 11677: 
                   11678: =item *
1.394     bowersj2 11679: X<idrget()>
                   11680: B<idrget($udom,@unames)>: find the IDs behind a list of
                   11681: usernames (returns hash: name=>id,name=>id)
1.191     harris41 11682: 
                   11683: =item *
1.394     bowersj2 11684: X<idput()>
                   11685: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191     harris41 11686: 
                   11687: =item *
1.394     bowersj2 11688: X<rolesinit()>
1.1169    droeschl 11689: B<rolesinit($udom,$username)>: get user privileges.
                   11690: returns user role, first access and timer interval hashes
1.243     albertel 11691: 
                   11692: =item *
1.1171    droeschl 11693: X<privileged()>
                   11694: B<privileged($username,$domain)>: returns a true if user has a
                   11695: privileged and active role (i.e. su or dc), false otherwise.
                   11696: 
                   11697: =item *
1.551     albertel 11698: X<getsection()>
                   11699: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243     albertel 11700: course $cname, return section name/number or '' for "not in course"
                   11701: and '-1' for "no section"
                   11702: 
                   11703: =item *
1.394     bowersj2 11704: X<userenvironment()>
                   11705: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243     albertel 11706: passed in @what from the requested user's environment, returns a hash
                   11707: 
1.858     raeburn  11708: =item * 
                   11709: X<userlog_query()>
1.859     albertel 11710: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
                   11711: activity.log file. %filters defines filters applied when parsing the
                   11712: log file. These can be start or end timestamps, or the type of action
                   11713: - log to look for Login or Logout events, check for Checkin or
                   11714: Checkout, role for role selection. The response is in the form
                   11715: timestamp1:hostid1:event1&timestamp2:hostid2:event2 where events are
                   11716: escaped strings of the action recorded in the activity.log file.
1.858     raeburn  11717: 
1.243     albertel 11718: =back
                   11719: 
                   11720: =head2 User Roles
                   11721: 
                   11722: =over 4
                   11723: 
                   11724: =item *
                   11725: 
1.810     raeburn  11726: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243     albertel 11727:  F: full access
                   11728:  U,I,K: authentication modes (cxx only)
                   11729:  '': forbidden
                   11730:  1: user needs to choose course
                   11731:  2: browse allowed
1.766     albertel 11732:  A: passphrase authentication needed
1.243     albertel 11733: 
                   11734: =item *
                   11735: 
                   11736: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
                   11737: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
                   11738: and course level
                   11739: 
                   11740: =item *
                   11741: 
1.988     raeburn  11742: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash 
                   11743: (rolesplain.tab); plain text explanation of a user role term.
1.1008    raeburn  11744: $type is Course (default) or Community.
1.988     raeburn  11745: If $forcedefault evaluates to true, text returned will be default 
                   11746: text for $type. Otherwise, if this is a course, the text returned 
                   11747: will be a custom name for the role (if defined in the course's 
                   11748: environment).  If no custom name is defined the default is returned.
                   11749:    
1.832     raeburn  11750: =item *
                   11751: 
1.935     raeburn  11752: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858     raeburn  11753: All arguments are optional. Returns a hash of a roles, either for
                   11754: co-author/assistant author roles for a user's Construction Space
1.906     albertel 11755: (default), or if $context is 'userroles', roles for the user himself,
1.933     raeburn  11756: In the hash, keys are set to colon-separated $uname,$udom,$role, and
                   11757: (optionally) if $withsec is true, a fourth colon-separated item - $section.
                   11758: For each key, value is set to colon-separated start and end times for
                   11759: the role.  If no username and domain are specified, will default to
1.934     raeburn  11760: current user/domain. Types, roles, and roledoms are references to arrays
1.858     raeburn  11761: of role statuses (active, future or previous), roles 
                   11762: (e.g., cc,in, st etc.) and domains of the roles which can be used
                   11763: to restrict the list of roles reported. If no array ref is 
                   11764: provided for types, will default to return only active roles.
1.834     albertel 11765: 
1.243     albertel 11766: =back
                   11767: 
                   11768: =head2 User Modification
                   11769: 
                   11770: =over 4
                   11771: 
                   11772: =item *
                   11773: 
1.957     raeburn  11774: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243     albertel 11775: user for the level given by URL.  Optional start and end dates (leave empty
                   11776: string or zero for "no date")
1.191     harris41 11777: 
                   11778: =item *
                   11779: 
1.243     albertel 11780: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
                   11781: change a users, password, possible return values are: ok,
                   11782: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
                   11783: refused
1.191     harris41 11784: 
                   11785: =item *
                   11786: 
1.243     albertel 11787: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191     harris41 11788: 
                   11789: =item *
                   11790: 
1.1058    raeburn  11791: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
                   11792:            $forceid,$desiredhome,$email,$inststatus,$candelete) :
                   11793: 
                   11794: will update user information (firstname,middlename,lastname,generation,
                   11795: permanentemail), and if forceid is true, student/employee ID also.
                   11796: A user's institutional affiliation(s) can also be updated.
                   11797: User information fields will not be overwritten with empty entries 
                   11798: unless the field is included in the $candelete array reference.
                   11799: This array is included when a single user is modified via "Manage Users",
                   11800: or when Autoupdate.pl is run by cron in a domain.
1.191     harris41 11801: 
                   11802: =item *
                   11803: 
1.286     matthew  11804: modifystudent
                   11805: 
1.957     raeburn  11806: modify a student's enrollment and identification information.
1.286     matthew  11807: The course id is resolved based on the current users environment.  
                   11808: This means the envoking user must be a course coordinator or otherwise
                   11809: associated with a course.
                   11810: 
1.297     matthew  11811: This call is essentially a wrapper for lonnet::modifyuser and
                   11812: lonnet::modify_student_enrollment
1.286     matthew  11813: 
                   11814: Inputs: 
                   11815: 
                   11816: =over 4
                   11817: 
1.957     raeburn  11818: =item B<$udom> Student's loncapa domain
1.286     matthew  11819: 
1.957     raeburn  11820: =item B<$uname> Student's loncapa login name
1.286     matthew  11821: 
1.964     bisitz   11822: =item B<$uid> Student/Employee ID
1.286     matthew  11823: 
1.957     raeburn  11824: =item B<$umode> Student's authentication mode
1.286     matthew  11825: 
1.957     raeburn  11826: =item B<$upass> Student's password
1.286     matthew  11827: 
1.957     raeburn  11828: =item B<$first> Student's first name
1.286     matthew  11829: 
1.957     raeburn  11830: =item B<$middle> Student's middle name
1.286     matthew  11831: 
1.957     raeburn  11832: =item B<$last> Student's last name
1.286     matthew  11833: 
1.957     raeburn  11834: =item B<$gene> Student's generation
1.286     matthew  11835: 
1.957     raeburn  11836: =item B<$usec> Student's section in course
1.286     matthew  11837: 
                   11838: =item B<$end> Unix time of the roles expiration
                   11839: 
                   11840: =item B<$start> Unix time of the roles start date
                   11841: 
                   11842: =item B<$forceid> If defined, allow $uid to be changed
                   11843: 
                   11844: =item B<$desiredhome> server to use as home server for student
                   11845: 
1.957     raeburn  11846: =item B<$email> Student's permanent e-mail address
                   11847: 
                   11848: =item B<$type> Type of enrollment (auto or manual)
                   11849: 
1.963     raeburn  11850: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto    
                   11851: 
                   11852: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957     raeburn  11853: 
1.963     raeburn  11854: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957     raeburn  11855: 
1.963     raeburn  11856: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957     raeburn  11857: 
1.963     raeburn  11858: =item B<$inststatus> institutional status of user - : separated string of escaped status types  
1.957     raeburn  11859: 
1.286     matthew  11860: =back
1.297     matthew  11861: 
                   11862: =item *
                   11863: 
                   11864: modify_student_enrollment
                   11865: 
                   11866: Change a students enrollment status in a class.  The environment variable
                   11867: 'role.request.course' must be defined for this function to proceed.
                   11868: 
                   11869: Inputs:
                   11870: 
                   11871: =over 4
                   11872: 
                   11873: =item $udom, students domain
                   11874: 
                   11875: =item $uname, students name
                   11876: 
                   11877: =item $uid, students user id
                   11878: 
                   11879: =item $first, students first name
                   11880: 
                   11881: =item $middle
                   11882: 
                   11883: =item $last
                   11884: 
                   11885: =item $gene
                   11886: 
                   11887: =item $usec
                   11888: 
                   11889: =item $end
                   11890: 
                   11891: =item $start
                   11892: 
1.957     raeburn  11893: =item $type
                   11894: 
                   11895: =item $locktype
                   11896: 
                   11897: =item $cid
                   11898: 
                   11899: =item $selfenroll
                   11900: 
                   11901: =item $context
                   11902: 
1.297     matthew  11903: =back
                   11904: 
1.191     harris41 11905: 
                   11906: =item *
                   11907: 
1.243     albertel 11908: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
                   11909: custom role; give a custom role to a user for the level given by URL.  Specify
                   11910: name and domain of role author, and role name
1.191     harris41 11911: 
                   11912: =item *
                   11913: 
1.243     albertel 11914: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191     harris41 11915: 
                   11916: =item *
                   11917: 
1.243     albertel 11918: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
                   11919: 
                   11920: =back
                   11921: 
                   11922: =head2 Course Infomation
                   11923: 
                   11924: =over 4
1.191     harris41 11925: 
                   11926: =item *
                   11927: 
1.1118    foxr     11928: coursedescription($courseid,$options) : returns a hash of information about the
1.631     albertel 11929: specified course id, including all environment settings for the
                   11930: course, the description of the course will be in the hash under the
                   11931: key 'description'
1.191     harris41 11932: 
1.1118    foxr     11933: $options is an optional parameter that if supplied is a hash reference that controls
                   11934: what how this function works.  It has the following key/values:
                   11935: 
                   11936: =over 4
                   11937: 
                   11938: =item freshen_cache
                   11939: 
                   11940: If defined, and the environment cache for the course is valid, it is 
                   11941: returned in the returned hash.
                   11942: 
                   11943: =item one_time
                   11944: 
                   11945: If defined, the last cache time is set to _now_
                   11946: 
                   11947: =item user
                   11948: 
                   11949: If defined, the supplied username is used instead of the current user.
                   11950: 
                   11951: 
                   11952: =back
                   11953: 
1.191     harris41 11954: =item *
                   11955: 
1.624     albertel 11956: resdata($name,$domain,$type,@which) : request for current parameter
                   11957: setting for a specific $type, where $type is either 'course' or 'user',
                   11958: @what should be a list of parameters to ask about. This routine caches
                   11959: answers for 5 minutes.
1.243     albertel 11960: 
1.877     foxr     11961: =item *
                   11962: 
                   11963: get_courseresdata($courseid, $domain) : dump the entire course resource
                   11964: data base, returning a hash that is keyed by the resource name and has
                   11965: values that are the resource value.  I believe that the timestamps and
                   11966: versions are also returned.
                   11967: 
                   11968: 
1.243     albertel 11969: =back
                   11970: 
                   11971: =head2 Course Modification
                   11972: 
                   11973: =over 4
1.191     harris41 11974: 
                   11975: =item *
                   11976: 
1.243     albertel 11977: writecoursepref($courseid,%prefs) : write preferences (environment
                   11978: database) for a course
1.191     harris41 11979: 
                   11980: =item *
                   11981: 
1.1011    raeburn  11982: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
                   11983: 
                   11984: =item *
                   11985: 
1.1038    raeburn  11986: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243     albertel 11987: 
1.1167    droeschl 11988: =item *
                   11989: 
                   11990: is_course($courseid), is_course($cdom, $cnum)
                   11991: 
                   11992: Accepts either a combined $courseid (in the form of domain_courseid) or the
                   11993: two component version $cdom, $cnum. It checks if the specified course exists.
                   11994: 
                   11995: Returns:
                   11996:     undef if the course doesn't exist, otherwise
                   11997:     in scalar context the combined courseid.
                   11998:     in list context the two components of the course identifier, domain and 
                   11999:     courseid.    
                   12000: 
1.243     albertel 12001: =back
                   12002: 
                   12003: =head2 Resource Subroutines
                   12004: 
                   12005: =over 4
1.191     harris41 12006: 
                   12007: =item *
                   12008: 
1.243     albertel 12009: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191     harris41 12010: 
                   12011: =item *
                   12012: 
1.243     albertel 12013: repcopy($filename) : subscribes to the requested file, and attempts to
                   12014: replicate from the owning library server, Might return
1.607     raeburn  12015: 'unavailable', 'not_found', 'forbidden', 'ok', or
                   12016: 'bad_request', also attempts to grab the metadata for the
1.243     albertel 12017: resource. Expects the local filesystem pathname
                   12018: (/home/httpd/html/res/....)
                   12019: 
                   12020: =back
                   12021: 
                   12022: =head2 Resource Information
                   12023: 
                   12024: =over 4
1.191     harris41 12025: 
                   12026: =item *
                   12027: 
1.243     albertel 12028: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
                   12029: a vairety of different possible values, $varname should be a request
                   12030: string, and the other parameters can be used to specify who and what
                   12031: one is asking about.
                   12032: 
                   12033: Possible values for $varname are environment.lastname (or other item
                   12034: from the envirnment hash), user.name (or someother aspect about the
                   12035: user), resource.0.maxtries (or some other part and parameter of a
                   12036: resource)
1.204     albertel 12037: 
                   12038: =item *
                   12039: 
1.243     albertel 12040: directcondval($number) : get current value of a condition; reads from a state
                   12041: string
1.204     albertel 12042: 
                   12043: =item *
                   12044: 
1.243     albertel 12045: condval($condidx) : value of condition index based on state
1.204     albertel 12046: 
                   12047: =item *
                   12048: 
1.243     albertel 12049: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
                   12050: resource's metadata, $what should be either a specific key, or either
                   12051: 'keys' (to get a list of possible keys) or 'packages' to get a list of
                   12052: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
                   12053: 
                   12054: this function automatically caches all requests
1.191     harris41 12055: 
                   12056: =item *
                   12057: 
1.243     albertel 12058: metadata_query($query,$custom,$customshow) : make a metadata query against the
                   12059: network of library servers; returns file handle of where SQL and regex results
                   12060: will be stored for query
1.191     harris41 12061: 
                   12062: =item *
                   12063: 
1.243     albertel 12064: symbread($filename) : return symbolic list entry (filename argument optional);
                   12065: returns the data handle
1.191     harris41 12066: 
                   12067: =item *
                   12068: 
1.243     albertel 12069: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582     albertel 12070: a possible symb for the URL in $thisfn, and if is an encryypted
                   12071: resource that the user accessed using /enc/ returns a 1 on success, 0
                   12072: on failure, user must be in a course, as it assumes the existance of
1.620     albertel 12073: the course initial hash, and uses $env('request.course.id'}
1.243     albertel 12074: 
1.191     harris41 12075: 
                   12076: =item *
                   12077: 
1.243     albertel 12078: symbclean($symb) : removes versions numbers from a symb, returns the
                   12079: cleaned symb
1.191     harris41 12080: 
                   12081: =item *
                   12082: 
1.243     albertel 12083: is_on_map($uri) : checks if the $uri is somewhere on the current
                   12084: course map, user must be in a course for it to work.
1.191     harris41 12085: 
                   12086: =item *
                   12087: 
1.243     albertel 12088: numval($salt) : return random seed value (addend for rndseed)
1.191     harris41 12089: 
                   12090: =item *
                   12091: 
1.243     albertel 12092: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
                   12093: a random seed, all arguments are optional, if they aren't sent it uses the
                   12094: environment to derive them. Note: if symb isn't sent and it can't get one
                   12095: from &symbread it will use the current time as its return value
1.191     harris41 12096: 
                   12097: =item *
                   12098: 
1.243     albertel 12099: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
                   12100: unfakeable, receipt
1.191     harris41 12101: 
                   12102: =item *
                   12103: 
1.620     albertel 12104: receipt() : API to ireceipt working off of env values; given out to users
1.191     harris41 12105: 
                   12106: =item *
                   12107: 
1.243     albertel 12108: countacc($url) : count the number of accesses to a given URL
1.191     harris41 12109: 
                   12110: =item *
                   12111: 
1.243     albertel 12112: 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 12113: 
                   12114: =item *
                   12115: 
1.243     albertel 12116: 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 12117: 
                   12118: =item *
                   12119: 
1.243     albertel 12120: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191     harris41 12121: 
                   12122: =item *
                   12123: 
1.243     albertel 12124: devalidate($symb) : devalidate temporary spreadsheet calculations,
                   12125: forcing spreadsheet to reevaluate the resource scores next time.
                   12126: 
                   12127: =back
                   12128: 
                   12129: =head2 Storing/Retreiving Data
                   12130: 
                   12131: =over 4
1.191     harris41 12132: 
                   12133: =item *
                   12134: 
1.243     albertel 12135: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
                   12136: for this url; hashref needs to be given and should be a \%hashname; the
                   12137: remaining args aren't required and if they aren't passed or are '' they will
1.620     albertel 12138: be derived from the env
1.191     harris41 12139: 
                   12140: =item *
                   12141: 
1.243     albertel 12142: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
                   12143: uses critical subroutine
1.191     harris41 12144: 
                   12145: =item *
                   12146: 
1.243     albertel 12147: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
                   12148: all args are optional
1.191     harris41 12149: 
                   12150: =item *
                   12151: 
1.717     albertel 12152: dumpstore($namespace,$udom,$uname,$regexp,$range) : 
                   12153: dumps the complete (or key matching regexp) namespace into a hash
                   12154: ($udom, $uname, $regexp, $range are optional) for a namespace that is
                   12155: normally &store()ed into
                   12156: 
                   12157: $range should be either an integer '100' (give me the first 100
                   12158:                                            matching records)
                   12159:               or be  two integers sperated by a - with no spaces
                   12160:                  '30-50' (give me the 30th through the 50th matching
                   12161:                           records)
                   12162: 
                   12163: 
                   12164: =item *
                   12165: 
                   12166: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
                   12167: replaces a &store() version of data with a replacement set of data
                   12168: for a particular resource in a namespace passed in the $storehash hash 
                   12169: reference
                   12170: 
                   12171: =item *
                   12172: 
1.243     albertel 12173: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
                   12174: works very similar to store/cstore, but all data is stored in a
                   12175: temporary location and can be reset using tmpreset, $storehash should
                   12176: be a hash reference, returns nothing on success
1.191     harris41 12177: 
                   12178: =item *
                   12179: 
1.243     albertel 12180: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
                   12181: similar to restore, but all data is stored in a temporary location and
                   12182: can be reset using tmpreset. Returns a hash of values on success,
                   12183: error string otherwise.
1.191     harris41 12184: 
                   12185: =item *
                   12186: 
1.243     albertel 12187: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
                   12188: deltes all keys for $symb form the temporary storage hash.
1.191     harris41 12189: 
                   12190: =item *
                   12191: 
1.243     albertel 12192: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12193: reference filled in from namesp ($udom and $uname are optional)
1.191     harris41 12194: 
                   12195: =item *
                   12196: 
1.243     albertel 12197: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
                   12198: namesp ($udom and $uname are optional)
1.191     harris41 12199: 
                   12200: =item *
                   12201: 
1.702     albertel 12202: dump($namespace,$udom,$uname,$regexp,$range) : 
1.243     albertel 12203: dumps the complete (or key matching regexp) namespace into a hash
1.702     albertel 12204: ($udom, $uname, $regexp, $range are optional)
1.449     matthew  12205: 
1.702     albertel 12206: $range should be either an integer '100' (give me the first 100
                   12207:                                            matching records)
                   12208:               or be  two integers sperated by a - with no spaces
                   12209:                  '30-50' (give me the 30th through the 50th matching
                   12210:                           records)
1.449     matthew  12211: =item *
                   12212: 
                   12213: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
                   12214: $store can be a scalar, an array reference, or if the amount to be 
                   12215: incremented is > 1, a hash reference.
                   12216: 
                   12217: ($udom and $uname are optional)
1.191     harris41 12218: 
                   12219: =item *
                   12220: 
1.243     albertel 12221: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
                   12222: ($udom and $uname are optional)
1.191     harris41 12223: 
                   12224: =item *
                   12225: 
1.243     albertel 12226: cput($namespace,$storehash,$udom,$uname) : critical put
                   12227: ($udom and $uname are optional)
1.191     harris41 12228: 
                   12229: =item *
                   12230: 
1.748     albertel 12231: newput($namespace,$storehash,$udom,$uname) :
                   12232: 
                   12233: Attempts to store the items in the $storehash, but only if they don't
                   12234: currently exist, if this succeeds you can be certain that you have 
                   12235: successfully created a new key value pair in the $namespace db.
                   12236: 
                   12237: 
                   12238: Args:
                   12239:  $namespace: name of database to store values to
                   12240:  $storehash: hashref to store to the db
                   12241:  $udom: (optional) domain of user containing the db
                   12242:  $uname: (optional) name of user caontaining the db
                   12243: 
                   12244: Returns:
                   12245:  'ok' -> succeeded in storing all keys of $storehash
                   12246:  'key_exists: <key>' -> failed to anything out of $storehash, as at
                   12247:                         least <key> already existed in the db (other
                   12248:                         requested keys may also already exist)
1.967     bisitz   12249:  'error: <msg>' -> unable to tie the DB or other error occurred
1.748     albertel 12250:  'con_lost' -> unable to contact request server
                   12251:  'refused' -> action was not allowed by remote machine
                   12252: 
                   12253: 
                   12254: =item *
                   12255: 
1.243     albertel 12256: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
                   12257: reference filled in from namesp (encrypts the return communication)
                   12258: ($udom and $uname are optional)
1.191     harris41 12259: 
                   12260: =item *
                   12261: 
1.243     albertel 12262: log($udom,$name,$home,$message) : write to permanent log for user; use
                   12263: critical subroutine
                   12264: 
1.806     raeburn  12265: =item *
                   12266: 
1.860     raeburn  12267: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
                   12268: array reference filled in from namespace found in domain level on either
                   12269: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806     raeburn  12270: 
                   12271: =item *
                   12272: 
1.860     raeburn  12273: put_dom($namespace,$storehash,$udom,$uhome) :  stores hash in namespace at 
                   12274: domain level either on specified domain server ($uhome) or primary domain 
                   12275: server ($udom and $uhome are optional)
1.806     raeburn  12276: 
1.943     raeburn  12277: =item * 
                   12278: 
                   12279: get_domain_defaults($target_domain) : returns hash with defaults for
                   12280: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
                   12281: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
                   12282: or localauth), initial password or a kerberos realm, language (e.g., en-us).
                   12283: Values are retrieved from cache (if current), or from domain's configuration.db
                   12284: (if available), or lastly from values in lonTabs/dns_domain,tab, 
                   12285: or lonTabs/domain.tab. 
                   12286: 
                   12287: %domdefaults = &get_auth_defaults($target_domain);
                   12288: 
1.243     albertel 12289: =back
                   12290: 
                   12291: =head2 Network Status Functions
                   12292: 
                   12293: =over 4
1.191     harris41 12294: 
                   12295: =item *
                   12296: 
1.1137    raeburn  12297: dirlist() : return directory list based on URI (first arg).
                   12298: 
                   12299: Inputs: 1 required, 5 optional.
                   12300: 
                   12301: =over
                   12302: 
                   12303: =item 
                   12304: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
                   12305: 
                   12306: =item
                   12307: $userdomain - domain of user/course to be listed. Extracted from $uri if absent. 
                   12308: 
                   12309: =item
                   12310: $username -  username of user/course to be listed. Extracted from $uri if absent. 
                   12311: 
                   12312: =item
                   12313: $getpropath - boolean: 1 if prepend path using &propath(). 
                   12314: 
                   12315: =item
                   12316: $getuserdir - boolean: 1 if prepend path for "userfiles".
                   12317: 
                   12318: =item 
                   12319: $alternateRoot - path to prepend in place of path from $uri.
                   12320: 
                   12321: =back
                   12322: 
                   12323: Returns: Array of up to two items.
                   12324: 
                   12325: =over
                   12326: 
                   12327: a reference to an array of files/subdirectories
                   12328: 
                   12329: =over
                   12330: 
                   12331: Each element in the array of files/subdirectories is a & separated list of
                   12332: item name and the result of running stat on the item.  If dirlist was requested
                   12333: for a file instead of a directory, the item name will be ''. For a directory 
                   12334: listing, if the item is a metadata file, the element will end &N&M 
                   12335: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
                   12336: default copyright set (1).  
                   12337: 
                   12338: =back
                   12339: 
                   12340: a scalar containing error condition (if encountered).
                   12341: 
                   12342: =over
                   12343: 
                   12344: =item 
                   12345: no_host (no homeserver identified for $username:$domain).
                   12346: 
                   12347: =item 
                   12348: no_such_host (server contacted for listing not identified as valid host).
                   12349: 
                   12350: =item 
                   12351: con_lost (connection to remote server failed).
                   12352: 
                   12353: =item 
                   12354: refused (invalid $username:$domain received on lond side).
                   12355: 
                   12356: =item 
                   12357: no_such_dir (directory at specified path on lond side does not exist). 
                   12358: 
                   12359: =item 
                   12360: empty (directory at specified path on lond side is empty).
                   12361: 
                   12362: =over
                   12363: 
                   12364: This is currently not encountered because the &ls3, &ls2, 
                   12365: &ls (_handler) routines on the lond side do not filter out
                   12366: . and .. from a directory listing. 
                   12367: 
                   12368: =back
                   12369: 
                   12370: =back
                   12371: 
                   12372: =back
1.191     harris41 12373: 
                   12374: =item *
                   12375: 
1.243     albertel 12376: spareserver() : find server with least workload from spare.tab
                   12377: 
1.986     foxr     12378: 
                   12379: =item *
                   12380: 
                   12381: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
                   12382: if there is no corresponding loncapa host.
                   12383: 
1.243     albertel 12384: =back
                   12385: 
1.986     foxr     12386: 
1.243     albertel 12387: =head2 Apache Request
                   12388: 
                   12389: =over 4
1.191     harris41 12390: 
                   12391: =item *
                   12392: 
1.243     albertel 12393: ssi($url,%hash) : server side include, does a complete request cycle on url to
                   12394: localhost, posts hash
                   12395: 
                   12396: =back
                   12397: 
                   12398: =head2 Data to String to Data
                   12399: 
                   12400: =over 4
1.191     harris41 12401: 
                   12402: =item *
                   12403: 
1.243     albertel 12404: hash2str(%hash) : convert a hash into a string complete with escaping and '='
                   12405: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191     harris41 12406: 
                   12407: =item *
                   12408: 
1.243     albertel 12409: hashref2str($hashref) : convert a hashref into a string complete with
                   12410: escaping and '=' and '&' separators, supports elements that are
                   12411: arrayrefs and hashrefs
1.191     harris41 12412: 
                   12413: =item *
                   12414: 
1.243     albertel 12415: arrayref2str($arrayref) : convert an arrayref into a string complete
                   12416: with escaping and '&' separators, supports elements that are arrayrefs
                   12417: and hashrefs
1.191     harris41 12418: 
                   12419: =item *
                   12420: 
1.243     albertel 12421: str2hash($string) : convert string to hash using unescaping and
                   12422: splitting on '=' and '&', supports elements that are arrayrefs and
                   12423: hashrefs
1.191     harris41 12424: 
                   12425: =item *
                   12426: 
1.243     albertel 12427: str2array($string) : convert string to hash using unescaping and
                   12428: splitting on '&', supports elements that are arrayrefs and hashrefs
                   12429: 
                   12430: =back
                   12431: 
                   12432: =head2 Logging Routines
                   12433: 
                   12434: 
                   12435: These routines allow one to make log messages in the lonnet.log and
                   12436: lonnet.perm logfiles.
1.191     harris41 12437: 
1.1119    foxr     12438: =over 4
                   12439: 
1.191     harris41 12440: =item *
                   12441: 
1.243     albertel 12442: logtouch() : make sure the logfile, lonnet.log, exists
1.191     harris41 12443: 
                   12444: =item *
                   12445: 
1.243     albertel 12446: logthis() : append message to the normal lonnet.log file, it gets
                   12447: preiodically rolled over and deleted.
1.191     harris41 12448: 
                   12449: =item *
                   12450: 
1.243     albertel 12451: logperm() : append a permanent message to lonnet.perm.log, this log
                   12452: file never gets deleted by any automated portion of the system, only
                   12453: messages of critical importance should go in here.
                   12454: 
1.1119    foxr     12455: 
1.243     albertel 12456: =back
                   12457: 
                   12458: =head2 General File Helper Routines
                   12459: 
                   12460: =over 4
1.191     harris41 12461: 
                   12462: =item *
                   12463: 
1.481     raeburn  12464: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
                   12465: (a) files in /uploaded
                   12466:   (i) If a local copy of the file exists - 
                   12467:       compares modification date of local copy with last-modified date for 
                   12468:       definitive version stored on home server for course. If local copy is 
                   12469:       stale, requests a new version from the home server and stores it. 
                   12470:       If the original has been removed from the home server, then local copy 
                   12471:       is unlinked.
                   12472:   (ii) If local copy does not exist -
                   12473:       requests the file from the home server and stores it. 
                   12474:   
                   12475:   If $caller is 'uploadrep':  
                   12476:     This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
                   12477:     for request for files originally uploaded via DOCS. 
                   12478:      - returns 'ok' if fresh local copy now available, -1 otherwise.
                   12479:   
                   12480:   Otherwise:
                   12481:      This indicates a call from the content generation phase of the request.
                   12482:      -  returns the entire contents of the file or -1.
                   12483:      
                   12484: (b) files in /res
                   12485:    - returns the entire contents of a file or -1; 
                   12486:    it properly subscribes to and replicates the file if neccessary.
1.191     harris41 12487: 
1.712     albertel 12488: 
                   12489: =item *
                   12490: 
                   12491: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
                   12492:                   reference
                   12493: 
                   12494: returns either a stat() list of data about the file or an empty list
                   12495: if the file doesn't exist or couldn't find out about it (connection
                   12496: problems or user unknown)
                   12497: 
1.191     harris41 12498: =item *
                   12499: 
1.243     albertel 12500: filelocation($dir,$file) : returns file system location of a file
                   12501: based on URI; meant to be "fairly clean" absolute reference, $dir is a
                   12502: directory that relative $file lookups are to looked in ($dir of /a/dir
                   12503: and a file of ../bob will become /a/bob)
1.191     harris41 12504: 
                   12505: =item *
                   12506: 
                   12507: hreflocation($dir,$file) : returns file system location or a URL; same as
                   12508: filelocation except for hrefs
                   12509: 
                   12510: =item *
                   12511: 
                   12512: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
                   12513: 
1.243     albertel 12514: =back
                   12515: 
1.608     albertel 12516: =head2 Usererfile file routines (/uploaded*)
                   12517: 
                   12518: =over 4
                   12519: 
                   12520: =item *
                   12521: 
                   12522: userfileupload(): main rotine for putting a file in a user or course's
                   12523:                   filespace, arguments are,
                   12524: 
1.620     albertel 12525:  formname - required - this is the name of the element in $env where the
1.608     albertel 12526:            filename, and the contents of the file to create/modifed exist
1.620     albertel 12527:            the filename is in $env{'form.'.$formname.'.filename'} and the
                   12528:            contents of the file is located in $env{'form.'.$formname}
1.1090    raeburn  12529:  context - if coursedoc, store the file in the course of the active role
                   12530:              of the current user; 
                   12531:            if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
                   12532:            if 'canceloverwrite': delete file in tmp/overwrites directory
1.608     albertel 12533:  subdir - required - subdirectory to put the file in under ../userfiles/
                   12534:          if undefined, it will be placed in "unknown"
                   12535: 
                   12536:  (This routine calls clean_filename() to remove any dangerous
                   12537:  characters from the filename, and then calls finuserfileupload() to
                   12538:  complete the transaction)
                   12539: 
                   12540:  returns either the url of the uploaded file (/uploaded/....) if successful
                   12541:  and /adm/notfound.html if unsuccessful
                   12542: 
                   12543: =item *
                   12544: 
                   12545: clean_filename(): routine for cleaing a filename up for storage in
                   12546:                  userfile space, argument is:
                   12547: 
                   12548:  filename - proposed filename
                   12549: 
                   12550: returns: the new clean filename
                   12551: 
                   12552: =item *
                   12553: 
1.1090    raeburn  12554: finishuserfileupload(): routine that creates and sends the file to
1.608     albertel 12555: userspace, probably shouldn't be called directly
                   12556: 
                   12557:   docuname: username or courseid of destination for the file
                   12558:   docudom: domain of user/course of destination for the file
                   12559:   formname: same as for userfileupload()
1.1090    raeburn  12560:   fname: filename (including subdirectories) for the file
                   12561:   parser: if 'parse', will parse (html) file to extract references to objects, links etc.
                   12562:   allfiles: reference to hash used to store objects found by parser
                   12563:   codebase: reference to hash used for codebases of java objects found by parser
                   12564:   thumbwidth: width (pixels) of thumbnail to be created for uploaded image
                   12565:   thumbheight: height (pixels) of thumbnail to be created for uploaded image
                   12566:   resizewidth: width to be used to resize image using resizeImage from ImageMagick
                   12567:   resizeheight: height to be used to resize image using resizeImage from ImageMagick
                   12568:   context: if 'overwrite', will move the uploaded file from its temporary location to
                   12569:             userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095    raeburn  12570:   mimetype: reference to scalar to accommodate mime type determined
                   12571:             from File::MMagic if $parser = parse.
1.608     albertel 12572: 
                   12573:  returns either the url of the uploaded file (/uploaded/....) if successful
1.1090    raeburn  12574:  and /adm/notfound.html if unsuccessful (or an error message if context 
                   12575:  was 'overwrite').
                   12576:  
1.608     albertel 12577: 
                   12578: =item *
                   12579: 
                   12580: renameuserfile(): renames an existing userfile to a new name
                   12581: 
                   12582:   Args:
                   12583:    docuname: username or courseid of destination for the file
                   12584:    docudom: domain of user/course of destination for the file
                   12585:    old: current file name (including any subdirs under userfiles)
                   12586:    new: desired file name (including any subdirs under userfiles)
                   12587: 
                   12588: =item *
                   12589: 
                   12590: mkdiruserfile(): creates a directory is a userfiles dir
                   12591: 
                   12592:   Args:
                   12593:    docuname: username or courseid of destination for the file
                   12594:    docudom: domain of user/course of destination for the file
                   12595:    dir: dir to create (including any subdirs under userfiles)
                   12596: 
                   12597: =item *
                   12598: 
                   12599: removeuserfile(): removes a file that exists in userfiles
                   12600: 
                   12601:   Args:
                   12602:    docuname: username or courseid of destination for the file
                   12603:    docudom: domain of user/course of destination for the file
                   12604:    fname: filname to delete (including any subdirs under userfiles)
                   12605: 
                   12606: =item *
                   12607: 
                   12608: removeuploadedurl(): convience function for removeuserfile()
                   12609: 
                   12610:   Args:
                   12611:    url:  a full /uploaded/... url to delete
                   12612: 
1.747     albertel 12613: =item * 
                   12614: 
                   12615: get_portfile_permissions():
                   12616:   Args:
                   12617:     domain: domain of user or course contain the portfolio files
                   12618:     user: name of user or num of course contain the portfolio files
                   12619:   Returns:
                   12620:     hashref of a dump of the proper file_permissions.db
                   12621:    
                   12622: 
                   12623: =item * 
                   12624: 
                   12625: get_access_controls():
                   12626: 
                   12627: Args:
                   12628:   current_permissions: the hash ref returned from get_portfile_permissions()
                   12629:   group: (optional) the group you want the files associated with
                   12630:   file: (optional) the file you want access info on
                   12631: 
                   12632: Returns:
1.749     raeburn  12633:     a hash (keys are file names) of hashes containing
                   12634:         keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
                   12635:         values are XML containing access control settings (see below) 
1.747     albertel 12636: 
                   12637: Internal notes:
                   12638: 
1.749     raeburn  12639:  access controls are stored in file_permissions.db as key=value pairs.
                   12640:     key -> path to file/file_name\0uniqueID:scope_end_start
                   12641:         where scope -> public,guest,course,group,domains or users.
                   12642:               end -> UNIX time for end of access (0 -> no end date)
                   12643:               start -> UNIX time for start of access
                   12644: 
                   12645:     value -> XML description of access control
                   12646:            <scope type=""> (type =1 of: public,guest,course,group,domains,users">
                   12647:             <start></start>
                   12648:             <end></end>
                   12649: 
                   12650:             <password></password>  for scope type = guest
                   12651: 
                   12652:             <domain></domain>     for scope type = course or group
                   12653:             <number></number>
                   12654:             <roles id="">
                   12655:              <role></role>
                   12656:              <access></access>
                   12657:              <section></section>
                   12658:              <group></group>
                   12659:             </roles>
                   12660: 
                   12661:             <dom></dom>         for scope type = domains
                   12662: 
                   12663:             <users>             for scope type = users
                   12664:              <user>
                   12665:               <uname></uname>
                   12666:               <udom></udom>
                   12667:              </user>
                   12668:             </users>
                   12669:            </scope> 
                   12670:               
                   12671:  Access data is also aggregated for each file in an additional key=value pair:
                   12672:  key -> path to file/file_name\0accesscontrol 
                   12673:  value -> reference to hash
                   12674:           hash contains key = value pairs
                   12675:           where key = uniqueID:scope_end_start
                   12676:                 value = UNIX time record was last updated
                   12677: 
                   12678:           Used to improve speed of look-ups of access controls for each file.  
                   12679:  
                   12680:  Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
                   12681: 
                   12682: modify_access_controls():
                   12683: 
                   12684: Modifies access controls for a portfolio file
                   12685: Args
                   12686: 1. file name
                   12687: 2. reference to hash of required changes,
                   12688: 3. domain
                   12689: 4. username
                   12690:   where domain,username are the domain of the portfolio owner 
                   12691:   (either a user or a course) 
                   12692: 
                   12693: Returns:
                   12694: 1. result of additions or updates ('ok' or 'error', with error message). 
                   12695: 2. result of deletions ('ok' or 'error', with error message).
                   12696: 3. reference to hash of any new or updated access controls.
                   12697: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
                   12698:    key = integer (inbound ID)
                   12699:    value = uniqueID  
1.747     albertel 12700: 
1.608     albertel 12701: =back
                   12702: 
1.243     albertel 12703: =head2 HTTP Helper Routines
                   12704: 
                   12705: =over 4
                   12706: 
1.191     harris41 12707: =item *
                   12708: 
                   12709: escape() : unpack non-word characters into CGI-compatible hex codes
                   12710: 
                   12711: =item *
                   12712: 
                   12713: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
                   12714: 
1.243     albertel 12715: =back
                   12716: 
                   12717: =head1 PRIVATE SUBROUTINES
                   12718: 
                   12719: =head2 Underlying communication routines (Shouldn't call)
                   12720: 
                   12721: =over 4
                   12722: 
                   12723: =item *
                   12724: 
                   12725: subreply() : tries to pass a message to lonc, returns con_lost if incapable
                   12726: 
                   12727: =item *
                   12728: 
                   12729: reply() : uses subreply to send a message to remote machine, logs all failures
                   12730: 
                   12731: =item *
                   12732: 
                   12733: critical() : passes a critical message to another server; if cannot
                   12734: get through then place message in connection buffer directory and
                   12735: returns con_delayed, if incapable of saving message, returns
                   12736: con_failed
                   12737: 
                   12738: =item *
                   12739: 
                   12740: reconlonc() : tries to reconnect lonc client processes.
                   12741: 
                   12742: =back
                   12743: 
                   12744: =head2 Resource Access Logging
                   12745: 
                   12746: =over 4
                   12747: 
                   12748: =item *
                   12749: 
                   12750: flushcourselogs() : flush (save) buffer logs and access logs
                   12751: 
                   12752: =item *
                   12753: 
                   12754: courselog($what) : save message for course in hash
                   12755: 
                   12756: =item *
                   12757: 
                   12758: courseacclog($what) : save message for course using &courselog().  Perform
                   12759: special processing for specific resource types (problems, exams, quizzes, etc).
                   12760: 
1.191     harris41 12761: =item *
                   12762: 
                   12763: goodbye() : flush course logs and log shutting down; it is called in srm.conf
                   12764: as a PerlChildExitHandler
1.243     albertel 12765: 
                   12766: =back
                   12767: 
                   12768: =head2 Other
                   12769: 
                   12770: =over 4
                   12771: 
                   12772: =item *
                   12773: 
                   12774: symblist($mapname,%newhash) : update symbolic storage links
1.191     harris41 12775: 
                   12776: =back
                   12777: 
                   12778: =cut
1.877     foxr     12779: 

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